function zI(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 a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).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 u0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function GI(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 by={exports:{}},Qd={};var T_;function VI(){if(T_)return Qd;T_=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,n,r){var a=null;if(r!==void 0&&(a=""+r),n.key!==void 0&&(a=""+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:a,ref:n!==void 0?n:null,props:r}}return Qd.Fragment=e,Qd.jsx=t,Qd.jsxs=t,Qd}var S_;function qI(){return S_||(S_=1,by.exports=VI()),by.exports}var g=qI(),Ty={exports:{}},pi={};var __;function KI(){if(__)return pi;__=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"),a=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"),y=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=y&&j[y]||j["@@iterator"],typeof j=="function"?j:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function L(j,X,se){this.props=j,this.context=X,this.refs=E,this.updater=se||b}L.prototype.isReactComponent={},L.prototype.setState=function(j,X){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,X,"setState")},L.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function N(){}N.prototype=L.prototype;function R(j,X,se){this.props=j,this.context=X,this.refs=E,this.updater=se||b}var H=R.prototype=new N;H.constructor=R,S(H,L.prototype),H.isPureReactComponent=!0;var F=Array.isArray;function $(){}var M={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function D(j,X,se){var fe=se.ref;return{$$typeof:s,type:j,key:X,ref:fe!==void 0?fe:null,props:se}}function I(j,X){return D(j.type,X,j.props)}function Q(j){return typeof j=="object"&&j!==null&&j.$$typeof===s}function K(j){var X={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(se){return X[se]})}var q=/\/+/g;function le(j,X){return typeof j=="object"&&j!==null&&j.key!=null?K(""+j.key):X.toString(36)}function te(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then($,$):(j.status="pending",j.then(function(X){j.status==="pending"&&(j.status="fulfilled",j.value=X)},function(X){j.status==="pending"&&(j.status="rejected",j.reason=X)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function V(j,X,se,fe,pe){var de=typeof j;(de==="undefined"||de==="boolean")&&(j=null);var Ve=!1;if(j===null)Ve=!0;else switch(de){case"bigint":case"string":case"number":Ve=!0;break;case"object":switch(j.$$typeof){case s:case e:Ve=!0;break;case f:return Ve=j._init,V(Ve(j._payload),X,se,fe,pe)}}if(Ve)return pe=pe(j),Ve=fe===""?"."+le(j,0):fe,F(pe)?(se="",Ve!=null&&(se=Ve.replace(q,"$&/")+"/"),V(pe,X,se,"",function(Pe){return Pe})):pe!=null&&(Q(pe)&&(pe=I(pe,se+(pe.key==null||j&&j.key===pe.key?"":(""+pe.key).replace(q,"$&/")+"/")+Ve)),X.push(pe)),1;Ve=0;var Ze=fe===""?".":fe+":";if(F(j))for(var Je=0;Je>>1,oe=V[ie];if(0>>1;ien(se,J))fen(pe,se)?(V[ie]=pe,V[fe]=J,ie=fe):(V[ie]=se,V[X]=J,ie=X);else if(fen(pe,J))V[ie]=pe,V[fe]=J,ie=fe;else break e}}return G}function n(V,G){var J=V.sortIndex-G.sortIndex;return J!==0?J:V.id-G.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 a=Date,u=a.now();s.unstable_now=function(){return a.now()-u}}var c=[],d=[],f=1,p=null,y=3,v=!1,b=!1,S=!1,E=!1,L=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function H(V){for(var G=t(d);G!==null;){if(G.callback===null)i(d);else if(G.startTime<=V)i(d),G.sortIndex=G.expirationTime,e(c,G);else break;G=t(d)}}function F(V){if(S=!1,H(V),!b)if(t(c)!==null)b=!0,$||($=!0,K());else{var G=t(d);G!==null&&te(F,G.startTime-V)}}var $=!1,M=-1,W=5,D=-1;function I(){return E?!0:!(s.unstable_now()-DV&&I());){var ie=p.callback;if(typeof ie=="function"){p.callback=null,y=p.priorityLevel;var oe=ie(p.expirationTime<=V);if(V=s.unstable_now(),typeof oe=="function"){p.callback=oe,H(V),G=!0;break t}p===t(c)&&i(c),H(V)}else i(c);p=t(c)}if(p!==null)G=!0;else{var j=t(d);j!==null&&te(F,j.startTime-V),G=!1}}break e}finally{p=null,y=J,v=!1}G=void 0}}finally{G?K():$=!1}}}var K;if(typeof R=="function")K=function(){R(Q)};else if(typeof MessageChannel<"u"){var q=new MessageChannel,le=q.port2;q.port1.onmessage=Q,K=function(){le.postMessage(null)}}else K=function(){L(Q,0)};function te(V,G){M=L(function(){V(s.unstable_now())},G)}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(V){V.callback=null},s.unstable_forceFrameRate=function(V){0>V||125ie?(V.sortIndex=J,e(d,V),t(c)===null&&V===t(d)&&(S?(N(M),M=-1):S=!0,te(F,J-ie))):(V.sortIndex=oe,e(c,V),b||v||(b=!0,$||($=!0,K()))),V},s.unstable_shouldYield=I,s.unstable_wrapCallback=function(V){var G=y;return function(){var J=y;y=G;try{return V.apply(this,arguments)}finally{y=J}}}})(Ey)),Ey}var k_;function YI(){return k_||(k_=1,_y.exports=WI()),_y.exports}var wy={exports:{}},$n={};var C_;function XI(){if(C_)return $n;C_=1;var s=X0();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(),wy.exports=XI(),wy.exports}var L_;function QI(){if(L_)return Zd;L_=1;var s=YI(),e=X0(),t=mA();function i(o){var l="https://react.dev/errors/"+o;if(1oe||(o.current=ie[oe],ie[oe]=null,oe--)}function se(o,l){oe++,ie[oe]=o.current,o.current=l}var fe=j(null),pe=j(null),de=j(null),Ve=j(null);function Ze(o,l){switch(se(de,l),se(pe,o),se(fe,null),l.nodeType){case 9:case 11:o=(o=l.documentElement)&&(o=o.namespaceURI)?GS(o):0;break;default:if(o=l.tagName,l=l.namespaceURI)l=GS(l),o=VS(l,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}X(fe),se(fe,o)}function Je(){X(fe),X(pe),X(de)}function Pe(o){o.memoizedState!==null&&se(Ve,o);var l=fe.current,h=VS(l,o.type);l!==h&&(se(pe,o),se(fe,h))}function Fe(o){pe.current===o&&(X(fe),X(pe)),Ve.current===o&&(X(Ve),Kd._currentValue=J)}var qe,dt;function Ge(o){if(qe===void 0)try{throw Error()}catch(h){var l=h.stack.trim().match(/\n( *(at )?)/);qe=l&&l[1]||"",dt=-1)":-1T||ge[m]!==Oe[T]){var et=` `+ge[m].replace(" at new "," at ");return o.displayName&&et.includes("")&&(et=et.replace("",o.displayName)),et}while(1<=m&&0<=T);break}}}finally{At=!1,Error.prepareStackTrace=h}return(h=o?o.displayName||o.name:"")?Ge(h):""}function bt(o,l){switch(o.tag){case 26:case 27:case 5:return Ge(o.type);case 16:return Ge("Lazy");case 13:return o.child!==l&&l!==null?Ge("Suspense Fallback"):Ge("Suspense");case 19:return Ge("SuspenseList");case 0:case 15:return lt(o.type,!1);case 11:return lt(o.type.render,!1);case 1:return lt(o.type,!0);case 31:return Ge("Activity");default:return""}}function nt(o){try{var l="",h=null;do l+=bt(o,h),h=o,o=o.return;while(o);return l}catch(m){return` Error generating stack: `+m.message+` `+m.stack}}var wt=Object.prototype.hasOwnProperty,ht=s.unstable_scheduleCallback,Et=s.unstable_cancelCallback,ye=s.unstable_shouldYield,mt=s.unstable_requestPaint,st=s.unstable_now,Xe=s.unstable_getCurrentPriorityLevel,xt=s.unstable_ImmediatePriority,ft=s.unstable_UserBlockingPriority,Pt=s.unstable_NormalPriority,qt=s.unstable_LowPriority,It=s.unstable_IdlePriority,ni=s.log,Gt=s.unstable_setDisableYieldValue,yi=null,Zt=null;function Jt(o){if(typeof ni=="function"&&Gt(o),Zt&&typeof Zt.setStrictMode=="function")try{Zt.setStrictMode(yi,o)}catch{}}var di=Math.clz32?Math.clz32:Mi,Zi=Math.log,Di=Math.LN2;function Mi(o){return o>>>=0,o===0?32:31-(Zi(o)/Di|0)|0}var Ki=256,As=262144,xe=4194304;function B(o){var l=o&42;if(l!==0)return l;switch(o&-o){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 o&261888;case 262144:case 524288:case 1048576:case 2097152:return o&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return o&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return o}}function Z(o,l,h){var m=o.pendingLanes;if(m===0)return 0;var T=0,w=o.suspendedLanes,U=o.pingedLanes;o=o.warmLanes;var ee=m&134217727;return ee!==0?(m=ee&~w,m!==0?T=B(m):(U&=ee,U!==0?T=B(U):h||(h=ee&~o,h!==0&&(T=B(h))))):(ee=m&~w,ee!==0?T=B(ee):U!==0?T=B(U):h||(h=m&~o,h!==0&&(T=B(h)))),T===0?0:l!==0&&l!==T&&(l&w)===0&&(w=T&-T,h=l&-l,w>=h||w===32&&(h&4194048)!==0)?l:T}function re(o,l){return(o.pendingLanes&~(o.suspendedLanes&~o.pingedLanes)&l)===0}function Te(o,l){switch(o){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 Ke(){var o=xe;return xe<<=1,(xe&62914560)===0&&(xe=4194304),o}function vt(o){for(var l=[],h=0;31>h;h++)l.push(o);return l}function Tt(o,l){o.pendingLanes|=l,l!==268435456&&(o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0)}function Li(o,l,h,m,T,w){var U=o.pendingLanes;o.pendingLanes=h,o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0,o.expiredLanes&=h,o.entangledLanes&=h,o.errorRecoveryDisabledLanes&=h,o.shellSuspendCounter=0;var ee=o.entanglements,ge=o.expirationTimes,Oe=o.hiddenUpdates;for(h=U&~h;0"u")return null;try{return o.activeElement||o.body}catch{return o.body}}var vs=/[\n"\\]/g;function Ji(o){return o.replace(vs,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function Tr(o,l,h,m,T,w,U,ee){o.name="",U!=null&&typeof U!="function"&&typeof U!="symbol"&&typeof U!="boolean"?o.type=U:o.removeAttribute("type"),l!=null?U==="number"?(l===0&&o.value===""||o.value!=l)&&(o.value=""+Yi(l)):o.value!==""+Yi(l)&&(o.value=""+Yi(l)):U!=="submit"&&U!=="reset"||o.removeAttribute("value"),l!=null?Ee(o,U,Yi(l)):h!=null?Ee(o,U,Yi(h)):m!=null&&o.removeAttribute("value"),T==null&&w!=null&&(o.defaultChecked=!!w),T!=null&&(o.checked=T&&typeof T!="function"&&typeof T!="symbol"),ee!=null&&typeof ee!="function"&&typeof ee!="symbol"&&typeof ee!="boolean"?o.name=""+Yi(ee):o.removeAttribute("name")}function Ds(o,l,h,m,T,w,U,ee){if(w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(o.type=w),l!=null||h!=null){if(!(w!=="submit"&&w!=="reset"||l!=null)){Pn(o);return}h=h!=null?""+Yi(h):"",l=l!=null?""+Yi(l):h,ee||l===o.value||(o.value=l),o.defaultValue=l}m=m??T,m=typeof m!="function"&&typeof m!="symbol"&&!!m,o.checked=ee?o.checked:!!m,o.defaultChecked=!!m,U!=null&&typeof U!="function"&&typeof U!="symbol"&&typeof U!="boolean"&&(o.name=U),Pn(o)}function Ee(o,l,h){l==="number"&&wn(o.ownerDocument)===o||o.defaultValue===""+h||(o.defaultValue=""+h)}function Ie(o,l,h,m){if(o=o.options,l){l={};for(var T=0;T"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),tt=!1;if($e)try{var ut={};Object.defineProperty(ut,"passive",{get:function(){tt=!0}}),window.addEventListener("test",ut,ut),window.removeEventListener("test",ut,ut)}catch{tt=!1}var Qe=null,at=null,pt=null;function Mt(){if(pt)return pt;var o,l=at,h=l.length,m,T="value"in Qe?Qe.value:Qe.textContent,w=T.length;for(o=0;o=Fl),cf=" ",sd=!1;function Iu(o,l){switch(o){case"keyup":return Fp.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function df(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var Po=!1;function Up(o,l){switch(o){case"compositionend":return df(l);case"keypress":return l.which!==32?null:(sd=!0,cf);case"textInput":return o=l.data,o===cf&&sd?null:o;default:return null}}function nd(o,l){if(Po)return o==="compositionend"||!Mo&&Iu(o,l)?(o=Mt(),pt=at=Qe=null,Po=!1,o):null;switch(o){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-o};o=m}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=Fo(h)}}function eo(o,l){return o&&l?o===l?!0:o&&o.nodeType===3?!1:l&&l.nodeType===3?eo(o,l.parentNode):"contains"in o?o.contains(l):o.compareDocumentPosition?!!(o.compareDocumentPosition(l)&16):!1:!1}function Nu(o){o=o!=null&&o.ownerDocument!=null&&o.ownerDocument.defaultView!=null?o.ownerDocument.defaultView:window;for(var l=wn(o.document);l instanceof o.HTMLIFrameElement;){try{var h=typeof l.contentWindow.location.href=="string"}catch{h=!1}if(h)o=l.contentWindow;else break;l=wn(o.document)}return l}function cd(o){var l=o&&o.nodeName&&o.nodeName.toLowerCase();return l&&(l==="input"&&(o.type==="text"||o.type==="search"||o.type==="tel"||o.type==="url"||o.type==="password")||l==="textarea"||o.contentEditable==="true")}var Vp=$e&&"documentMode"in document&&11>=document.documentMode,Uo=null,dd=null,jo=null,Ou=!1;function hd(o,l,h){var m=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Ou||Uo==null||Uo!==wn(m)||(m=Uo,"selectionStart"in m&&cd(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}),jo&&ya(jo,m)||(jo=m,m=nm(dd,"onSelect"),0>=U,T-=U,Er=1<<32-di(l)+T|h<xi?(Bi=jt,jt=null):Bi=jt.sibling;var Vi=Be(Ae,jt,Ne[xi],ot);if(Vi===null){jt===null&&(jt=Bi);break}o&&jt&&Vi.alternate===null&&l(Ae,jt),be=w(Vi,be,xi),Gi===null?Wt=Vi:Gi.sibling=Vi,Gi=Vi,jt=Bi}if(xi===Ne.length)return h(Ae,jt),Ii&&_i(Ae,xi),Wt;if(jt===null){for(;xixi?(Bi=jt,jt=null):Bi=jt.sibling;var dl=Be(Ae,jt,Vi.value,ot);if(dl===null){jt===null&&(jt=Bi);break}o&&jt&&dl.alternate===null&&l(Ae,jt),be=w(dl,be,xi),Gi===null?Wt=dl:Gi.sibling=dl,Gi=dl,jt=Bi}if(Vi.done)return h(Ae,jt),Ii&&_i(Ae,xi),Wt;if(jt===null){for(;!Vi.done;xi++,Vi=Ne.next())Vi=ct(Ae,Vi.value,ot),Vi!==null&&(be=w(Vi,be,xi),Gi===null?Wt=Vi:Gi.sibling=Vi,Gi=Vi);return Ii&&_i(Ae,xi),Wt}for(jt=m(jt);!Vi.done;xi++,Vi=Ne.next())Vi=ze(jt,Ae,xi,Vi.value,ot),Vi!==null&&(o&&Vi.alternate!==null&&jt.delete(Vi.key===null?xi:Vi.key),be=w(Vi,be,xi),Gi===null?Wt=Vi:Gi.sibling=Vi,Gi=Vi);return o&&jt.forEach(function(HI){return l(Ae,HI)}),Ii&&_i(Ae,xi),Wt}function us(Ae,be,Ne,ot){if(typeof Ne=="object"&&Ne!==null&&Ne.type===S&&Ne.key===null&&(Ne=Ne.props.children),typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case v:e:{for(var Wt=Ne.key;be!==null;){if(be.key===Wt){if(Wt=Ne.type,Wt===S){if(be.tag===7){h(Ae,be.sibling),ot=T(be,Ne.props.children),ot.return=Ae,Ae=ot;break e}}else if(be.elementType===Wt||typeof Wt=="object"&&Wt!==null&&Wt.$$typeof===W&&Yl(Wt)===be.type){h(Ae,be.sibling),ot=T(be,Ne.props),Ed(ot,Ne),ot.return=Ae,Ae=ot;break e}h(Ae,be);break}else l(Ae,be);be=be.sibling}Ne.type===S?(ot=xa(Ne.props.children,Ae.mode,ot,Ne.key),ot.return=Ae,Ae=ot):(ot=xd(Ne.type,Ne.key,Ne.props,null,Ae.mode,ot),Ed(ot,Ne),ot.return=Ae,Ae=ot)}return U(Ae);case b:e:{for(Wt=Ne.key;be!==null;){if(be.key===Wt)if(be.tag===4&&be.stateNode.containerInfo===Ne.containerInfo&&be.stateNode.implementation===Ne.implementation){h(Ae,be.sibling),ot=T(be,Ne.children||[]),ot.return=Ae,Ae=ot;break e}else{h(Ae,be);break}else l(Ae,be);be=be.sibling}ot=Vo(Ne,Ae.mode,ot),ot.return=Ae,Ae=ot}return U(Ae);case W:return Ne=Yl(Ne),us(Ae,be,Ne,ot)}if(te(Ne))return Ot(Ae,be,Ne,ot);if(K(Ne)){if(Wt=K(Ne),typeof Wt!="function")throw Error(i(150));return Ne=Wt.call(Ne),si(Ae,be,Ne,ot)}if(typeof Ne.then=="function")return us(Ae,be,Cf(Ne),ot);if(Ne.$$typeof===R)return us(Ae,be,hi(Ae,Ne),ot);Df(Ae,Ne)}return typeof Ne=="string"&&Ne!==""||typeof Ne=="number"||typeof Ne=="bigint"?(Ne=""+Ne,be!==null&&be.tag===6?(h(Ae,be.sibling),ot=T(be,Ne),ot.return=Ae,Ae=ot):(h(Ae,be),ot=Gl(Ne,Ae.mode,ot),ot.return=Ae,Ae=ot),U(Ae)):h(Ae,be)}return function(Ae,be,Ne,ot){try{_d=0;var Wt=us(Ae,be,Ne,ot);return ju=null,Wt}catch(jt){if(jt===Uu||jt===Af)throw jt;var Gi=Hs(29,jt,null,Ae.mode);return Gi.lanes=ot,Gi.return=Ae,Gi}}}var Ql=M1(!0),P1=M1(!1),Wo=!1;function Xp(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Qp(o,l){o=o.updateQueue,l.updateQueue===o&&(l.updateQueue={baseState:o.baseState,firstBaseUpdate:o.firstBaseUpdate,lastBaseUpdate:o.lastBaseUpdate,shared:o.shared,callbacks:null})}function Yo(o){return{lane:o,tag:0,payload:null,callback:null,next:null}}function Xo(o,l,h){var m=o.updateQueue;if(m===null)return null;if(m=m.shared,(Xi&2)!==0){var T=m.pending;return T===null?l.next=l:(l.next=T.next,T.next=l),m.pending=l,l=Bu(o),Tf(o,null,h),l}return Pu(o,m,l,h),Bu(o)}function wd(o,l,h){if(l=l.updateQueue,l!==null&&(l=l.shared,(h&4194048)!==0)){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,ji(o,h)}}function Zp(o,l){var h=o.updateQueue,m=o.alternate;if(m!==null&&(m=m.updateQueue,h===m)){var T=null,w=null;if(h=h.firstBaseUpdate,h!==null){do{var U={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};w===null?T=w=U:w=w.next=U,h=h.next}while(h!==null);w===null?T=w=l:w=w.next=l}else T=w=l;h={baseState:m.baseState,firstBaseUpdate:T,lastBaseUpdate:w,shared:m.shared,callbacks:m.callbacks},o.updateQueue=h;return}o=h.lastBaseUpdate,o===null?h.firstBaseUpdate=l:o.next=l,h.lastBaseUpdate=l}var Jp=!1;function Ad(){if(Jp){var o=gn;if(o!==null)throw o}}function kd(o,l,h,m){Jp=!1;var T=o.updateQueue;Wo=!1;var w=T.firstBaseUpdate,U=T.lastBaseUpdate,ee=T.shared.pending;if(ee!==null){T.shared.pending=null;var ge=ee,Oe=ge.next;ge.next=null,U===null?w=Oe:U.next=Oe,U=ge;var et=o.alternate;et!==null&&(et=et.updateQueue,ee=et.lastBaseUpdate,ee!==U&&(ee===null?et.firstBaseUpdate=Oe:ee.next=Oe,et.lastBaseUpdate=ge))}if(w!==null){var ct=T.baseState;U=0,et=Oe=ge=null,ee=w;do{var Be=ee.lane&-536870913,ze=Be!==ee.lane;if(ze?(Pi&Be)===Be:(m&Be)===Be){Be!==0&&Be===Gr&&(Jp=!0),et!==null&&(et=et.next={lane:0,tag:ee.tag,payload:ee.payload,callback:null,next:null});e:{var Ot=o,si=ee;Be=l;var us=h;switch(si.tag){case 1:if(Ot=si.payload,typeof Ot=="function"){ct=Ot.call(us,ct,Be);break e}ct=Ot;break e;case 3:Ot.flags=Ot.flags&-65537|128;case 0:if(Ot=si.payload,Be=typeof Ot=="function"?Ot.call(us,ct,Be):Ot,Be==null)break e;ct=p({},ct,Be);break e;case 2:Wo=!0}}Be=ee.callback,Be!==null&&(o.flags|=64,ze&&(o.flags|=8192),ze=T.callbacks,ze===null?T.callbacks=[Be]:ze.push(Be))}else ze={lane:Be,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},et===null?(Oe=et=ze,ge=ct):et=et.next=ze,U|=Be;if(ee=ee.next,ee===null){if(ee=T.shared.pending,ee===null)break;ze=ee,ee=ze.next,ze.next=null,T.lastBaseUpdate=ze,T.shared.pending=null}}while(!0);et===null&&(ge=ct),T.baseState=ge,T.firstBaseUpdate=Oe,T.lastBaseUpdate=et,w===null&&(T.shared.lanes=0),tl|=U,o.lanes=U,o.memoizedState=ct}}function B1(o,l){if(typeof o!="function")throw Error(i(191,o));o.call(l)}function F1(o,l){var h=o.callbacks;if(h!==null)for(o.callbacks=null,o=0;ow?w:8;var U=V.T,ee={};V.T=ee,vg(o,!1,l,h);try{var ge=T(),Oe=V.S;if(Oe!==null&&Oe(ee,ge),ge!==null&&typeof ge=="object"&&typeof ge.then=="function"){var et=RR(ge,m);Ld(o,l,et,Dr(o))}else Ld(o,l,m,Dr(o))}catch(ct){Ld(o,l,{then:function(){},status:"rejected",reason:ct},Dr())}finally{G.p=w,U!==null&&ee.types!==null&&(U.types=ee.types),V.T=U}}function BR(){}function gg(o,l,h,m){if(o.tag!==5)throw Error(i(476));var T=gT(o).queue;pT(o,T,l,J,h===null?BR:function(){return yT(o),h(m)})}function gT(o){var l=o.memoizedState;if(l!==null)return l;l={memoizedState:J,baseState:J,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ro,lastRenderedState:J},next:null};var h={};return l.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ro,lastRenderedState:h},next:null},o.memoizedState=l,o=o.alternate,o!==null&&(o.memoizedState=l),l}function yT(o){var l=gT(o);l.next===null&&(l=o.alternate.memoizedState),Ld(o,l.next.queue,{},Dr())}function yg(){return Dt(Kd)}function vT(){return Js().memoizedState}function xT(){return Js().memoizedState}function FR(o){for(var l=o.return;l!==null;){switch(l.tag){case 24:case 3:var h=Dr();o=Yo(h);var m=Xo(l,o,h);m!==null&&(ur(m,l,h),wd(m,l,h)),l={cache:so()},o.payload=l;return}l=l.return}}function UR(o,l,h){var m=Dr();h={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},Uf(o)?TT(l,h):(h=yd(o,l,h,m),h!==null&&(ur(h,o,m),ST(h,l,m)))}function bT(o,l,h){var m=Dr();Ld(o,l,h,m)}function Ld(o,l,h,m){var T={lane:m,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(Uf(o))TT(l,T);else{var w=o.alternate;if(o.lanes===0&&(w===null||w.lanes===0)&&(w=l.lastRenderedReducer,w!==null))try{var U=l.lastRenderedState,ee=w(U,h);if(T.hasEagerState=!0,T.eagerState=ee,Un(ee,U))return Pu(o,l,T,0),ms===null&&Mu(),!1}catch{}if(h=yd(o,l,T,m),h!==null)return ur(h,o,m),ST(h,l,m),!0}return!1}function vg(o,l,h,m){if(m={lane:2,revertLane:Xg(),gesture:null,action:m,hasEagerState:!1,eagerState:null,next:null},Uf(o)){if(l)throw Error(i(479))}else l=yd(o,h,m,2),l!==null&&ur(l,o,2)}function Uf(o){var l=o.alternate;return o===vi||l!==null&&l===vi}function TT(o,l){Hu=If=!0;var h=o.pending;h===null?l.next=l:(l.next=h.next,h.next=l),o.pending=l}function ST(o,l,h){if((h&4194048)!==0){var m=l.lanes;m&=o.pendingLanes,h|=m,l.lanes=h,ji(o,h)}}var Rd={readContext:Dt,use:Mf,useCallback:zs,useContext:zs,useEffect:zs,useImperativeHandle:zs,useLayoutEffect:zs,useInsertionEffect:zs,useMemo:zs,useReducer:zs,useRef:zs,useState:zs,useDebugValue:zs,useDeferredValue:zs,useTransition:zs,useSyncExternalStore:zs,useId:zs,useHostTransitionStatus:zs,useFormState:zs,useActionState:zs,useOptimistic:zs,useMemoCache:zs,useCacheRefresh:zs};Rd.useEffectEvent=zs;var _T={readContext:Dt,use:Mf,useCallback:function(o,l){return qn().memoizedState=[o,l===void 0?null:l],o},useContext:Dt,useEffect:aT,useImperativeHandle:function(o,l,h){h=h!=null?h.concat([o]):null,Bf(4194308,4,cT.bind(null,l,o),h)},useLayoutEffect:function(o,l){return Bf(4194308,4,o,l)},useInsertionEffect:function(o,l){Bf(4,2,o,l)},useMemo:function(o,l){var h=qn();l=l===void 0?null:l;var m=o();if(Zl){Jt(!0);try{o()}finally{Jt(!1)}}return h.memoizedState=[m,l],m},useReducer:function(o,l,h){var m=qn();if(h!==void 0){var T=h(l);if(Zl){Jt(!0);try{h(l)}finally{Jt(!1)}}}else T=l;return m.memoizedState=m.baseState=T,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:o,lastRenderedState:T},m.queue=o,o=o.dispatch=UR.bind(null,vi,o),[m.memoizedState,o]},useRef:function(o){var l=qn();return o={current:o},l.memoizedState=o},useState:function(o){o=dg(o);var l=o.queue,h=bT.bind(null,vi,l);return l.dispatch=h,[o.memoizedState,h]},useDebugValue:mg,useDeferredValue:function(o,l){var h=qn();return pg(h,o,l)},useTransition:function(){var o=dg(!1);return o=pT.bind(null,vi,o.queue,!0,!1),qn().memoizedState=o,[!1,o]},useSyncExternalStore:function(o,l,h){var m=vi,T=qn();if(Ii){if(h===void 0)throw Error(i(407));h=h()}else{if(h=l(),ms===null)throw Error(i(349));(Pi&127)!==0||G1(m,l,h)}T.memoizedState=h;var w={value:h,getSnapshot:l};return T.queue=w,aT(q1.bind(null,m,w,o),[o]),m.flags|=2048,Gu(9,{destroy:void 0},V1.bind(null,m,w,h,l),null),h},useId:function(){var o=qn(),l=ms.identifierPrefix;if(Ii){var h=kn,m=Er;h=(m&~(1<<32-di(m)-1)).toString(32)+h,l="_"+l+"R_"+h,h=Nf++,0<\/script>",w=w.removeChild(w.firstChild);break;case"select":w=typeof m.is=="string"?U.createElement("select",{is:m.is}):U.createElement("select"),m.multiple?w.multiple=!0:m.size&&(w.size=m.size);break;default:w=typeof m.is=="string"?U.createElement(T,{is:m.is}):U.createElement(T)}}w[ii]=l,w[Ht]=m;e:for(U=l.child;U!==null;){if(U.tag===5||U.tag===6)w.appendChild(U.stateNode);else if(U.tag!==4&&U.tag!==27&&U.child!==null){U.child.return=U,U=U.child;continue}if(U===l)break e;for(;U.sibling===null;){if(U.return===null||U.return===l)break e;U=U.return}U.sibling.return=U.return,U=U.sibling}l.stateNode=w;e:switch(Dn(w,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&&oo(l)}}return ws(l),Ig(l,l.type,o===null?null:o.memoizedProps,l.pendingProps,h),null;case 6:if(o&&l.stateNode!=null)o.memoizedProps!==m&&oo(l);else{if(typeof m!="string"&&l.stateNode===null)throw Error(i(166));if(o=de.current,x(l)){if(o=l.stateNode,h=l.memoizedProps,m=null,T=nn,T!==null)switch(T.tag){case 27:case 5:m=T.memoizedProps}o[ii]=l,o=!!(o.nodeValue===h||m!==null&&m.suppressHydrationWarning===!0||HS(o.nodeValue,h)),o||_a(l,!0)}else o=rm(o).createTextNode(m),o[ii]=l,l.stateNode=o}return ws(l),null;case 31:if(h=l.memoizedState,o===null||o.memoizedState!==null){if(m=x(l),h!==null){if(o===null){if(!m)throw Error(i(318));if(o=l.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(i(557));o[ii]=l}else A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ws(l),o=!1}else h=C(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=h),o=!0;if(!o)return l.flags&256?(Ar(l),l):(Ar(l),null);if((l.flags&128)!==0)throw Error(i(558))}return ws(l),null;case 13:if(m=l.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(T=x(l),m!==null&&m.dehydrated!==null){if(o===null){if(!T)throw Error(i(318));if(T=l.memoizedState,T=T!==null?T.dehydrated:null,!T)throw Error(i(317));T[ii]=l}else A(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;ws(l),T=!1}else T=C(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=T),T=!0;if(!T)return l.flags&256?(Ar(l),l):(Ar(l),null)}return Ar(l),(l.flags&128)!==0?(l.lanes=h,l):(h=m!==null,o=o!==null&&o.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),w=null,m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),w!==T&&(m.flags|=2048)),h!==o&&h&&(l.child.flags|=8192),Gf(l,l.updateQueue),ws(l),null);case 4:return Je(),o===null&&ey(l.stateNode.containerInfo),ws(l),null;case 10:return ce(l.type),ws(l),null;case 19:if(X(Zs),m=l.memoizedState,m===null)return ws(l),null;if(T=(l.flags&128)!==0,w=m.rendering,w===null)if(T)Nd(m,!1);else{if(Gs!==0||o!==null&&(o.flags&128)!==0)for(o=l.child;o!==null;){if(w=Rf(o),w!==null){for(l.flags|=128,Nd(m,!1),o=w.updateQueue,l.updateQueue=o,Gf(l,o),l.subtreeFlags=0,o=h,h=l.child;h!==null;)Sf(h,o),h=h.sibling;return se(Zs,Zs.current&1|2),Ii&&_i(l,m.treeForkCount),l.child}o=o.sibling}m.tail!==null&&st()>Yf&&(l.flags|=128,T=!0,Nd(m,!1),l.lanes=4194304)}else{if(!T)if(o=Rf(w),o!==null){if(l.flags|=128,T=!0,o=o.updateQueue,l.updateQueue=o,Gf(l,o),Nd(m,!0),m.tail===null&&m.tailMode==="hidden"&&!w.alternate&&!Ii)return ws(l),null}else 2*st()-m.renderingStartTime>Yf&&h!==536870912&&(l.flags|=128,T=!0,Nd(m,!1),l.lanes=4194304);m.isBackwards?(w.sibling=l.child,l.child=w):(o=m.last,o!==null?o.sibling=w:l.child=w,m.last=w)}return m.tail!==null?(o=m.tail,m.rendering=o,m.tail=o.sibling,m.renderingStartTime=st(),o.sibling=null,h=Zs.current,se(Zs,T?h&1|2:h&1),Ii&&_i(l,m.treeForkCount),o):(ws(l),null);case 22:case 23:return Ar(l),tg(),m=l.memoizedState!==null,o!==null?o.memoizedState!==null!==m&&(l.flags|=8192):m&&(l.flags|=8192),m?(h&536870912)!==0&&(l.flags&128)===0&&(ws(l),l.subtreeFlags&6&&(l.flags|=8192)):ws(l),h=l.updateQueue,h!==null&&Gf(l,h.retryQueue),h=null,o!==null&&o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==h&&(l.flags|=2048),o!==null&&X(Wl),null;case 24:return h=null,o!==null&&(h=o.memoizedState.cache),l.memoizedState.cache!==h&&(l.flags|=2048),ce(bs),ws(l),null;case 25:return null;case 30:return null}throw Error(i(156,l.tag))}function GR(o,l){switch(sr(l),l.tag){case 1:return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 3:return ce(bs),Je(),o=l.flags,(o&65536)!==0&&(o&128)===0?(l.flags=o&-65537|128,l):null;case 26:case 27:case 5:return Fe(l),null;case 31:if(l.memoizedState!==null){if(Ar(l),l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 13:if(Ar(l),o=l.memoizedState,o!==null&&o.dehydrated!==null){if(l.alternate===null)throw Error(i(340));A()}return o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 19:return X(Zs),null;case 4:return Je(),null;case 10:return ce(l.type),null;case 22:case 23:return Ar(l),tg(),o!==null&&X(Wl),o=l.flags,o&65536?(l.flags=o&-65537|128,l):null;case 24:return ce(bs),null;case 25:return null;default:return null}}function KT(o,l){switch(sr(l),l.tag){case 3:ce(bs),Je();break;case 26:case 27:case 5:Fe(l);break;case 4:Je();break;case 31:l.memoizedState!==null&&Ar(l);break;case 13:Ar(l);break;case 19:X(Zs);break;case 10:ce(l.type);break;case 22:case 23:Ar(l),tg(),o!==null&&X(Wl);break;case 24:ce(bs)}}function Od(o,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&o)===o){m=void 0;var w=h.create,U=h.inst;m=w(),U.destroy=m}h=h.next}while(h!==T)}}catch(ee){is(l,l.return,ee)}}function Jo(o,l,h){try{var m=l.updateQueue,T=m!==null?m.lastEffect:null;if(T!==null){var w=T.next;m=w;do{if((m.tag&o)===o){var U=m.inst,ee=U.destroy;if(ee!==void 0){U.destroy=void 0,T=l;var ge=h,Oe=ee;try{Oe()}catch(et){is(T,ge,et)}}}m=m.next}while(m!==w)}}catch(et){is(l,l.return,et)}}function WT(o){var l=o.updateQueue;if(l!==null){var h=o.stateNode;try{F1(l,h)}catch(m){is(o,o.return,m)}}}function YT(o,l,h){h.props=Jl(o.type,o.memoizedProps),h.state=o.memoizedState;try{h.componentWillUnmount()}catch(m){is(o,l,m)}}function Md(o,l){try{var h=o.ref;if(h!==null){switch(o.tag){case 26:case 27:case 5:var m=o.stateNode;break;case 30:m=o.stateNode;break;default:m=o.stateNode}typeof h=="function"?o.refCleanup=h(m):h.current=m}}catch(T){is(o,l,T)}}function Aa(o,l){var h=o.ref,m=o.refCleanup;if(h!==null)if(typeof m=="function")try{m()}catch(T){is(o,l,T)}finally{o.refCleanup=null,o=o.alternate,o!=null&&(o.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(T){is(o,l,T)}else h.current=null}function XT(o){var l=o.type,h=o.memoizedProps,m=o.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){is(o,o.return,T)}}function Ng(o,l,h){try{var m=o.stateNode;hI(m,o.type,h,l),m[Ht]=l}catch(T){is(o,o.return,T)}}function QT(o){return o.tag===5||o.tag===3||o.tag===26||o.tag===27&&al(o.type)||o.tag===4}function Og(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||QT(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.tag===27&&al(o.type)||o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function Mg(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(o,l):(l=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,l.appendChild(o),h=h._reactRootContainer,h!=null||l.onclick!==null||(l.onclick=Ls));else if(m!==4&&(m===27&&al(o.type)&&(h=o.stateNode,l=null),o=o.child,o!==null))for(Mg(o,l,h),o=o.sibling;o!==null;)Mg(o,l,h),o=o.sibling}function Vf(o,l,h){var m=o.tag;if(m===5||m===6)o=o.stateNode,l?h.insertBefore(o,l):h.appendChild(o);else if(m!==4&&(m===27&&al(o.type)&&(h=o.stateNode),o=o.child,o!==null))for(Vf(o,l,h),o=o.sibling;o!==null;)Vf(o,l,h),o=o.sibling}function ZT(o){var l=o.stateNode,h=o.memoizedProps;try{for(var m=o.type,T=l.attributes;T.length;)l.removeAttributeNode(T[0]);Dn(l,m,h),l[ii]=o,l[Ht]=h}catch(w){is(o,o.return,w)}}var lo=!1,on=!1,Pg=!1,JT=typeof WeakSet=="function"?WeakSet:Set,yn=null;function VR(o,l){if(o=o.containerInfo,sy=hm,o=Nu(o),cd(o)){if("selectionStart"in o)var h={start:o.selectionStart,end:o.selectionEnd};else e:{h=(h=o.ownerDocument)&&h.defaultView||window;var m=h.getSelection&&h.getSelection();if(m&&m.rangeCount!==0){h=m.anchorNode;var T=m.anchorOffset,w=m.focusNode;m=m.focusOffset;try{h.nodeType,w.nodeType}catch{h=null;break e}var U=0,ee=-1,ge=-1,Oe=0,et=0,ct=o,Be=null;t:for(;;){for(var ze;ct!==h||T!==0&&ct.nodeType!==3||(ee=U+T),ct!==w||m!==0&&ct.nodeType!==3||(ge=U+m),ct.nodeType===3&&(U+=ct.nodeValue.length),(ze=ct.firstChild)!==null;)Be=ct,ct=ze;for(;;){if(ct===o)break t;if(Be===h&&++Oe===T&&(ee=U),Be===w&&++et===m&&(ge=U),(ze=ct.nextSibling)!==null)break;ct=Be,Be=ct.parentNode}ct=ze}h=ee===-1||ge===-1?null:{start:ee,end:ge}}else h=null}h=h||{start:0,end:0}}else h=null;for(ny={focusedElem:o,selectionRange:h},hm=!1,yn=l;yn!==null;)if(l=yn,o=l.child,(l.subtreeFlags&1028)!==0&&o!==null)o.return=l,yn=o;else for(;yn!==null;){switch(l=yn,w=l.alternate,o=l.flags,l.tag){case 0:if((o&4)!==0&&(o=l.updateQueue,o=o!==null?o.events:null,o!==null))for(h=0;h title"))),Dn(w,m,h),w[ii]=o,Ut(w),m=w;break e;case"link":var U=r_("link","href",T).get(m+(h.href||""));if(U){for(var ee=0;eeus&&(U=us,us=si,si=U);var Ae=Rs(ee,si),be=Rs(ee,us);if(Ae&&be&&(ze.rangeCount!==1||ze.anchorNode!==Ae.node||ze.anchorOffset!==Ae.offset||ze.focusNode!==be.node||ze.focusOffset!==be.offset)){var Ne=ct.createRange();Ne.setStart(Ae.node,Ae.offset),ze.removeAllRanges(),si>us?(ze.addRange(Ne),ze.extend(be.node,be.offset)):(Ne.setEnd(be.node,be.offset),ze.addRange(Ne))}}}}for(ct=[],ze=ee;ze=ze.parentNode;)ze.nodeType===1&&ct.push({element:ze,left:ze.scrollLeft,top:ze.scrollTop});for(typeof ee.focus=="function"&&ee.focus(),ee=0;eeh?32:h,V.T=null,h=zg,zg=null;var w=sl,U=mo;if(dn=0,Yu=sl=null,mo=0,(Xi&6)!==0)throw Error(i(331));var ee=Xi;if(Xi|=4,cS(w.current),oS(w,w.current,U,h),Xi=ee,$d(0,!1),Zt&&typeof Zt.onPostCommitFiberRoot=="function")try{Zt.onPostCommitFiberRoot(yi,w)}catch{}return!0}finally{G.p=T,V.T=m,CS(o,l)}}function LS(o,l,h){l=tr(h,l),l=Sg(o.stateNode,l,2),o=Xo(o,l,2),o!==null&&(Tt(o,2),ka(o))}function is(o,l,h){if(o.tag===3)LS(o,o,h);else for(;l!==null;){if(l.tag===3){LS(l,o,h);break}else if(l.tag===1){var m=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof m.componentDidCatch=="function"&&(il===null||!il.has(m))){o=tr(h,o),h=RT(2),m=Xo(l,h,2),m!==null&&(IT(h,m,l,o),Tt(m,2),ka(m));break}}l=l.return}}function Kg(o,l,h){var m=o.pingCache;if(m===null){m=o.pingCache=new WR;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)||(Ug=!0,T.add(h),o=JR.bind(null,o,l,h),l.then(o,o))}function JR(o,l,h){var m=o.pingCache;m!==null&&m.delete(l),o.pingedLanes|=o.suspendedLanes&h,o.warmLanes&=~h,ms===o&&(Pi&h)===h&&(Gs===4||Gs===3&&(Pi&62914560)===Pi&&300>st()-Wf?(Xi&2)===0&&Xu(o,0):jg|=h,Wu===Pi&&(Wu=0)),ka(o)}function RS(o,l){l===0&&(l=Ke()),o=io(o,l),o!==null&&(Tt(o,l),ka(o))}function eI(o){var l=o.memoizedState,h=0;l!==null&&(h=l.retryLane),RS(o,h)}function tI(o,l){var h=0;switch(o.tag){case 31:case 13:var m=o.stateNode,T=o.memoizedState;T!==null&&(h=T.retryLane);break;case 19:m=o.stateNode;break;case 22:m=o.stateNode._retryCache;break;default:throw Error(i(314))}m!==null&&m.delete(l),RS(o,h)}function iI(o,l){return ht(o,l)}var tm=null,Zu=null,Wg=!1,im=!1,Yg=!1,rl=0;function ka(o){o!==Zu&&o.next===null&&(Zu===null?tm=Zu=o:Zu=Zu.next=o),im=!0,Wg||(Wg=!0,nI())}function $d(o,l){if(!Yg&&im){Yg=!0;do for(var h=!1,m=tm;m!==null;){if(o!==0){var T=m.pendingLanes;if(T===0)var w=0;else{var U=m.suspendedLanes,ee=m.pingedLanes;w=(1<<31-di(42|o)+1)-1,w&=T&~(U&~ee),w=w&201326741?w&201326741|1:w?w|2:0}w!==0&&(h=!0,MS(m,w))}else w=Pi,w=Z(m,m===ms?w:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),(w&3)===0||re(m,w)||(h=!0,MS(m,w));m=m.next}while(h);Yg=!1}}function sI(){IS()}function IS(){im=Wg=!1;var o=0;rl!==0&&mI()&&(o=rl);for(var l=st(),h=null,m=tm;m!==null;){var T=m.next,w=NS(m,l);w===0?(m.next=null,h===null?tm=T:h.next=T,T===null&&(Zu=h)):(h=m,(o!==0||(w&3)!==0)&&(im=!0)),m=T}dn!==0&&dn!==5||$d(o),rl!==0&&(rl=0)}function NS(o,l){for(var h=o.suspendedLanes,m=o.pingedLanes,T=o.expirationTimes,w=o.pendingLanes&-62914561;0ee)break;var et=ge.transferSize,ct=ge.initiatorType;et&&zS(ct)&&(ge=ge.responseEnd,U+=et*(ge"u"?null:document;function t_(o,l,h){var m=Ju;if(m&&typeof l=="string"&&l){var T=Ji(l);T='link[rel="'+o+'"][href="'+T+'"]',typeof h=="string"&&(T+='[crossorigin="'+h+'"]'),e_.has(T)||(e_.add(T),o={rel:o,crossOrigin:h,href:l},m.querySelector(T)===null&&(l=m.createElement("link"),Dn(l,"link",o),Ut(l),m.head.appendChild(l)))}}function _I(o){po.D(o),t_("dns-prefetch",o,null)}function EI(o,l){po.C(o,l),t_("preconnect",o,l)}function wI(o,l,h){po.L(o,l,h);var m=Ju;if(m&&o&&l){var T='link[rel="preload"][as="'+Ji(l)+'"]';l==="image"&&h&&h.imageSrcSet?(T+='[imagesrcset="'+Ji(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(T+='[imagesizes="'+Ji(h.imageSizes)+'"]')):T+='[href="'+Ji(o)+'"]';var w=T;switch(l){case"style":w=ec(o);break;case"script":w=tc(o)}Kr.has(w)||(o=p({rel:"preload",href:l==="image"&&h&&h.imageSrcSet?void 0:o,as:l},h),Kr.set(w,o),m.querySelector(T)!==null||l==="style"&&m.querySelector(Vd(w))||l==="script"&&m.querySelector(qd(w))||(l=m.createElement("link"),Dn(l,"link",o),Ut(l),m.head.appendChild(l)))}}function AI(o,l){po.m(o,l);var h=Ju;if(h&&o){var m=l&&typeof l.as=="string"?l.as:"script",T='link[rel="modulepreload"][as="'+Ji(m)+'"][href="'+Ji(o)+'"]',w=T;switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":w=tc(o)}if(!Kr.has(w)&&(o=p({rel:"modulepreload",href:o},l),Kr.set(w,o),h.querySelector(T)===null)){switch(m){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(qd(w)))return}m=h.createElement("link"),Dn(m,"link",o),Ut(m),h.head.appendChild(m)}}}function kI(o,l,h){po.S(o,l,h);var m=Ju;if(m&&o){var T=mi(m).hoistableStyles,w=ec(o);l=l||"default";var U=T.get(w);if(!U){var ee={loading:0,preload:null};if(U=m.querySelector(Vd(w)))ee.loading=5;else{o=p({rel:"stylesheet",href:o,"data-precedence":l},h),(h=Kr.get(w))&&dy(o,h);var ge=U=m.createElement("link");Ut(ge),Dn(ge,"link",o),ge._p=new Promise(function(Oe,et){ge.onload=Oe,ge.onerror=et}),ge.addEventListener("load",function(){ee.loading|=1}),ge.addEventListener("error",function(){ee.loading|=2}),ee.loading|=4,om(U,l,m)}U={type:"stylesheet",instance:U,count:1,state:ee},T.set(w,U)}}}function CI(o,l){po.X(o,l);var h=Ju;if(h&&o){var m=mi(h).hoistableScripts,T=tc(o),w=m.get(T);w||(w=h.querySelector(qd(T)),w||(o=p({src:o,async:!0},l),(l=Kr.get(T))&&hy(o,l),w=h.createElement("script"),Ut(w),Dn(w,"link",o),h.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},m.set(T,w))}}function DI(o,l){po.M(o,l);var h=Ju;if(h&&o){var m=mi(h).hoistableScripts,T=tc(o),w=m.get(T);w||(w=h.querySelector(qd(T)),w||(o=p({src:o,async:!0,type:"module"},l),(l=Kr.get(T))&&hy(o,l),w=h.createElement("script"),Ut(w),Dn(w,"link",o),h.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},m.set(T,w))}}function i_(o,l,h,m){var T=(T=de.current)?am(T):null;if(!T)throw Error(i(446));switch(o){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(l=ec(h.href),h=mi(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"){o=ec(h.href);var w=mi(T).hoistableStyles,U=w.get(o);if(U||(T=T.ownerDocument||T,U={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},w.set(o,U),(w=T.querySelector(Vd(o)))&&!w._p&&(U.instance=w,U.state.loading=5),Kr.has(o)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},Kr.set(o,h),w||LI(T,o,h,U.state))),l&&m===null)throw Error(i(528,""));return U}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=tc(h),h=mi(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,o))}}function ec(o){return'href="'+Ji(o)+'"'}function Vd(o){return'link[rel="stylesheet"]['+o+"]"}function s_(o){return p({},o,{"data-precedence":o.precedence,precedence:null})}function LI(o,l,h,m){o.querySelector('link[rel="preload"][as="style"]['+l+"]")?m.loading=1:(l=o.createElement("link"),m.preload=l,l.addEventListener("load",function(){return m.loading|=1}),l.addEventListener("error",function(){return m.loading|=2}),Dn(l,"link",h),Ut(l),o.head.appendChild(l))}function tc(o){return'[src="'+Ji(o)+'"]'}function qd(o){return"script[async]"+o}function n_(o,l,h){if(l.count++,l.instance===null)switch(l.type){case"style":var m=o.querySelector('style[data-href~="'+Ji(h.href)+'"]');if(m)return l.instance=m,Ut(m),m;var T=p({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return m=(o.ownerDocument||o).createElement("style"),Ut(m),Dn(m,"style",T),om(m,h.precedence,o),l.instance=m;case"stylesheet":T=ec(h.href);var w=o.querySelector(Vd(T));if(w)return l.state.loading|=4,l.instance=w,Ut(w),w;m=s_(h),(T=Kr.get(T))&&dy(m,T),w=(o.ownerDocument||o).createElement("link"),Ut(w);var U=w;return U._p=new Promise(function(ee,ge){U.onload=ee,U.onerror=ge}),Dn(w,"link",m),l.state.loading|=4,om(w,h.precedence,o),l.instance=w;case"script":return w=tc(h.src),(T=o.querySelector(qd(w)))?(l.instance=T,Ut(T),T):(m=h,(T=Kr.get(w))&&(m=p({},h),hy(m,T)),o=o.ownerDocument||o,T=o.createElement("script"),Ut(T),Dn(T,"link",m),o.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,om(m,h.precedence,o));return l.instance}function om(o,l,h){for(var m=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),T=m.length?m[m.length-1]:null,w=T,U=0;U title"):null)}function RI(o,l,h){if(h===1||l.itemProp!=null)return!1;switch(o){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"?(o=l.disabled,typeof l.precedence=="string"&&o==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 o_(o){return!(o.type==="stylesheet"&&(o.state.loading&3)===0)}function II(o,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=ec(m.href),w=l.querySelector(Vd(T));if(w){l=w._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(o.count++,o=um.bind(o),l.then(o,o)),h.state.loading|=4,h.instance=w,Ut(w);return}w=l.ownerDocument||l,m=s_(m),(T=Kr.get(T))&&dy(m,T),w=w.createElement("link"),Ut(w);var U=w;U._p=new Promise(function(ee,ge){U.onload=ee,U.onerror=ge}),Dn(w,"link",m),h.instance=w}o.stylesheets===null&&(o.stylesheets=new Map),o.stylesheets.set(h,l),(l=h.state.preload)&&(h.state.loading&3)===0&&(o.count++,h=um.bind(o),l.addEventListener("load",h),l.addEventListener("error",h))}}var fy=0;function NI(o,l){return o.stylesheets&&o.count===0&&dm(o,o.stylesheets),0fy?50:800)+l);return o.unsuspend=h,function(){o.unsuspend=null,clearTimeout(m),clearTimeout(T)}}:null}function um(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)dm(this,this.stylesheets);else if(this.unsuspend){var o=this.unsuspend;this.unsuspend=null,o()}}}var cm=null;function dm(o,l){o.stylesheets=null,o.unsuspend!==null&&(o.count++,cm=new Map,l.forEach(OI,o),cm=null,um.call(o))}function OI(o,l){if(!(l.state.loading&4)){var h=cm.get(o);if(h)var m=h.get(null);else{h=new Map,cm.set(o,h);for(var T=o.querySelectorAll("link[data-precedence],style[data-precedence]"),w=0;w"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Sy.exports=QI(),Sy.exports}var pA=ZI();function JI(...s){return s.filter(Boolean).join(" ")}const e5="inline-flex items-center justify-center font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",t5={sm:"rounded-sm",md:"rounded-md",full:"rounded-full"},i5={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"},s5={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 n5(){return g.jsxs("svg",{viewBox:"0 0 24 24",className:"size-4 animate-spin","aria-hidden":"true",children:[g.jsx("circle",{cx:"12",cy:"12",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.25"}),g.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.9"})]})}function oi({children:s,variant:e="primary",color:t="indigo",size:i="md",rounded:n="md",leadingIcon:r,trailingIcon:a,isLoading:u=!1,disabled:c,className:d,type:f="button",...p}){const y=r||a||u?"gap-x-1.5":"";return g.jsxs("button",{type:f,disabled:c||u,className:JI(e5,t5[n],i5[i],s5[t][e],y,d),...p,children:[u?g.jsx("span",{className:"-ml-0.5",children:g.jsx(n5,{})}):r&&g.jsx("span",{className:"-ml-0.5",children:r}),g.jsx("span",{children:s}),a&&!u&&g.jsx("span",{className:"-mr-0.5",children:a})]})}function gA(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?r5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ay=(s,e,t)=>(a5(s,typeof e!="symbol"?e+"":e,t),t);let o5=class{constructor(){Ay(this,"current",this.detect()),Ay(this,"handoffState","pending"),Ay(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"}},Ha=new o5;function qh(s){var e;return Ha.isServer?null:s==null?document:(e=s?.ownerDocument)!=null?e:document}function ex(s){var e,t;return Ha.isServer?null:s==null?document:(t=(e=s?.getRootNode)==null?void 0:e.call(s))!=null?t:document}function yA(s){var e,t;return(t=(e=ex(s))==null?void 0:e.activeElement)!=null?t:null}function l5(s){return yA(s)===s}function Q0(s){typeof queueMicrotask=="function"?queueMicrotask(s):Promise.resolve().then(s).catch(e=>setTimeout(()=>{throw e}))}function Io(){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 Q0(()=>{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=Io();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 Z0(){let[s]=_.useState(Io);return _.useEffect(()=>()=>s.dispose(),[s]),s}let vr=(s,e)=>{Ha.isServer?_.useEffect(s,e):_.useLayoutEffect(s,e)};function Cu(s){let e=_.useRef(s);return vr(()=>{e.current=s},[s]),e}let gs=function(s){let e=Cu(s);return Qt.useCallback((...t)=>e.current(...t),[e])};function Kh(s){return _.useMemo(()=>s,Object.values(s))}let u5=_.createContext(void 0);function c5(){return _.useContext(u5)}function tx(...s){return Array.from(new Set(s.flatMap(e=>typeof e=="string"?e.split(" "):[]))).filter(Boolean).join(" ")}function Lo(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,Lo),i}var c0=(s=>(s[s.None=0]="None",s[s.RenderStrategy=1]="RenderStrategy",s[s.Static=2]="Static",s))(c0||{}),wl=(s=>(s[s.Unmount=0]="Unmount",s[s.Hidden=1]="Hidden",s))(wl||{});function ea(){let s=h5();return _.useCallback(e=>d5({mergeRefs:s,...e}),[s])}function d5({ourProps:s,theirProps:e,slot:t,defaultTag:i,features:n,visible:r=!0,name:a,mergeRefs:u}){u=u??f5;let c=vA(e,s);if(r)return xm(c,t,i,a,u);let d=n??0;if(d&2){let{static:f=!1,...p}=c;if(f)return xm(p,t,i,a,u)}if(d&1){let{unmount:f=!0,...p}=c;return Lo(f?0:1,{0(){return null},1(){return xm({...p,hidden:!0,style:{display:"none"}},t,i,a,u)}})}return xm(c,t,i,a,u)}function xm(s,e={},t,i,n){let{as:r=t,children:a,refName:u="ref",...c}=ky(s,["unmount","static"]),d=s.ref!==void 0?{[u]:s.ref}:{},f=typeof a=="function"?a(e):a;"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 y=!1,v=[];for(let[b,S]of Object.entries(e))typeof S=="boolean"&&(y=!0),S===!0&&v.push(b.replace(/([A-Z])/g,E=>`-${E.toLowerCase()}`));if(y){p["data-headlessui-state"]=v.join(" ");for(let b of v)p[`data-${b}`]=""}}if(yh(r)&&(Object.keys(lu(c)).length>0||Object.keys(lu(p)).length>0))if(!_.isValidElement(f)||Array.isArray(f)&&f.length>1||p5(f)){if(Object.keys(lu(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(lu(c)).concat(Object.keys(lu(p))).map(y=>` - ${y}`).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(y=>` - ${y}`).join(` `)].join(` `))}else{let y=f.props,v=y?.className,b=typeof v=="function"?(...L)=>tx(v(...L),c.className):tx(v,c.className),S=b?{className:b}:{},E=vA(f.props,lu(ky(c,["ref"])));for(let L in p)L in E&&delete p[L];return _.cloneElement(f,Object.assign({},E,p,d,{ref:n(m5(f),d.ref)},S))}return _.createElement(r,Object.assign({},ky(c,["ref"]),!yh(r)&&d,!yh(r)&&p),f)}function h5(){let s=_.useRef([]),e=_.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 f5(...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 vA(...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 a=t[i];for(let u of a){if((n instanceof Event||n?.nativeEvent instanceof Event)&&n.defaultPrevented)return;u(n,...r)}}});return e}function br(s){var e;return Object.assign(_.forwardRef(s),{displayName:(e=s.displayName)!=null?e:s.name})}function lu(s){let e=Object.assign({},s);for(let t in e)e[t]===void 0&&delete e[t];return e}function ky(s,e=[]){let t=Object.assign({},s);for(let i of e)i in t&&delete t[i];return t}function m5(s){return Qt.version.split(".")[0]>="19"?s.props.ref:s.ref}function yh(s){return s===_.Fragment||s===Symbol.for("react.fragment")}function p5(s){return yh(s.type)}let g5="span";var d0=(s=>(s[s.None=1]="None",s[s.Focusable=2]="Focusable",s[s.Hidden=4]="Hidden",s))(d0||{});function y5(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 ea()({ourProps:r,theirProps:n,slot:{},defaultTag:g5,name:"Hidden"})}let ix=br(y5);function v5(s){return typeof s!="object"||s===null?!1:"nodeType"in s}function kl(s){return v5(s)&&"tagName"in s}function Su(s){return kl(s)&&"accessKey"in s}function Al(s){return kl(s)&&"tabIndex"in s}function x5(s){return kl(s)&&"style"in s}function b5(s){return Su(s)&&s.nodeName==="IFRAME"}function T5(s){return Su(s)&&s.nodeName==="INPUT"}let xA=Symbol();function S5(s,e=!0){return Object.assign(s,{[xA]:e})}function Xa(...s){let e=_.useRef(s);_.useEffect(()=>{e.current=s},[s]);let t=gs(i=>{for(let n of e.current)n!=null&&(typeof n=="function"?n(i):n.current=i)});return s.every(i=>i==null||i?.[xA])?void 0:t}let ab=_.createContext(null);ab.displayName="DescriptionContext";function bA(){let s=_.useContext(ab);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,bA),e}return s}function _5(){let[s,e]=_.useState([]);return[s.length>0?s.join(" "):void 0,_.useMemo(()=>function(t){let i=gs(r=>(e(a=>[...a,r]),()=>e(a=>{let u=a.slice(),c=u.indexOf(r);return c!==-1&&u.splice(c,1),u}))),n=_.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 Qt.createElement(ab.Provider,{value:n},t.children)},[e])]}let E5="p";function w5(s,e){let t=_.useId(),i=c5(),{id:n=`headlessui-description-${t}`,...r}=s,a=bA(),u=Xa(e);vr(()=>a.register(n),[n,a.register]);let c=Kh({...a.slot,disabled:i||!1}),d={ref:u,...a.props,id:n};return ea()({ourProps:d,theirProps:r,slot:c,defaultTag:E5,name:a.name||"Description"})}let A5=br(w5),k5=Object.assign(A5,{});var TA=(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))(TA||{});let C5=_.createContext(()=>{});function D5({value:s,children:e}){return Qt.createElement(C5.Provider,{value:s},e)}let SA=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 L5=Object.defineProperty,R5=(s,e,t)=>e in s?L5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,I5=(s,e,t)=>(R5(s,e+"",t),t),_A=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Wr=(s,e,t)=>(_A(s,e,"read from private field"),t?t.call(s):e.get(s)),Cy=(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)},I_=(s,e,t,i)=>(_A(s,e,"write to private field"),e.set(s,t),t),Ra,uh,ch;let N5=class{constructor(e){Cy(this,Ra,{}),Cy(this,uh,new SA(()=>new Set)),Cy(this,ch,new Set),I5(this,"disposables",Io()),I_(this,Ra,e),Ha.isServer&&this.disposables.microTask(()=>{this.dispose()})}dispose(){this.disposables.dispose()}get state(){return Wr(this,Ra)}subscribe(e,t){if(Ha.isServer)return()=>{};let i={selector:e,callback:t,current:e(Wr(this,Ra))};return Wr(this,ch).add(i),this.disposables.add(()=>{Wr(this,ch).delete(i)})}on(e,t){return Ha.isServer?()=>{}:(Wr(this,uh).get(e).add(t),this.disposables.add(()=>{Wr(this,uh).get(e).delete(t)}))}send(e){let t=this.reduce(Wr(this,Ra),e);if(t!==Wr(this,Ra)){I_(this,Ra,t);for(let i of Wr(this,ch)){let n=i.selector(Wr(this,Ra));EA(i.current,n)||(i.current=n,i.callback(n))}for(let i of Wr(this,uh).get(e.type))i(Wr(this,Ra),e)}}};Ra=new WeakMap,uh=new WeakMap,ch=new WeakMap;function EA(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:Dy(s[Symbol.iterator](),e[Symbol.iterator]()):s instanceof Map&&e instanceof Map||s instanceof Set&&e instanceof Set?s.size!==e.size?!1:Dy(s.entries(),e.entries()):N_(s)&&N_(e)?Dy(Object.entries(s)[Symbol.iterator](),Object.entries(e)[Symbol.iterator]()):!1}function Dy(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 N_(s){if(Object.prototype.toString.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||Object.getPrototypeOf(e)===null}var O5=Object.defineProperty,M5=(s,e,t)=>e in s?O5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,O_=(s,e,t)=>(M5(s,typeof e!="symbol"?e+"":e,t),t),P5=(s=>(s[s.Push=0]="Push",s[s.Pop=1]="Pop",s))(P5||{});let B5={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}}},F5=class wA extends N5{constructor(){super(...arguments),O_(this,"actions",{push:e=>this.send({type:0,id:e}),pop:e=>this.send({type:1,id:e})}),O_(this,"selectors",{isTop:(e,t)=>e.stack[e.stack.length-1]===t,inStack:(e,t)=>e.stack.includes(t)})}static new(){return new wA({stack:[]})}reduce(e,t){return Lo(t.type,B5,e,t)}};const AA=new SA(()=>F5.new());var Ly={exports:{}},Ry={};var M_;function U5(){if(M_)return Ry;M_=1;var s=X0();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,a=s.useMemo,u=s.useDebugValue;return Ry.useSyncExternalStoreWithSelector=function(c,d,f,p,y){var v=n(null);if(v.current===null){var b={hasValue:!1,value:null};v.current=b}else b=v.current;v=a(function(){function E(F){if(!L){if(L=!0,N=F,F=p(F),y!==void 0&&b.hasValue){var $=b.value;if(y($,F))return R=$}return R=F}if($=R,t(N,F))return $;var M=p(F);return y!==void 0&&y($,M)?(N=F,$):(N=F,R=M)}var L=!1,N,R,H=f===void 0?null:f;return[function(){return E(d())},H===null?void 0:function(){return E(H())}]},[d,f,p,y]);var S=i(c,v[0],v[1]);return r(function(){b.hasValue=!0,b.value=S},[S]),u(S),S},Ry}var P_;function j5(){return P_||(P_=1,Ly.exports=U5()),Ly.exports}var $5=j5();function kA(s,e,t=EA){return $5.useSyncExternalStoreWithSelector(gs(i=>s.subscribe(H5,i)),gs(()=>s.state),gs(()=>s.state),gs(e),t)}function H5(s){return s}function Wh(s,e){let t=_.useId(),i=AA.get(e),[n,r]=kA(i,_.useCallback(a=>[i.selectors.isTop(a,t),i.selectors.inStack(a,t)],[i,t]));return vr(()=>{if(s)return i.actions.push(t),()=>i.actions.pop(t)},[i,s,t]),s?r?n:!0:!1}let sx=new Map,vh=new Map;function B_(s){var e;let t=(e=vh.get(s))!=null?e:0;return vh.set(s,t+1),t!==0?()=>F_(s):(sx.set(s,{"aria-hidden":s.getAttribute("aria-hidden"),inert:s.inert}),s.setAttribute("aria-hidden","true"),s.inert=!0,()=>F_(s))}function F_(s){var e;let t=(e=vh.get(s))!=null?e:1;if(t===1?vh.delete(s):vh.set(s,t-1),t!==1)return;let i=sx.get(s);i&&(i["aria-hidden"]===null?s.removeAttribute("aria-hidden"):s.setAttribute("aria-hidden",i["aria-hidden"]),s.inert=i.inert,sx.delete(s))}function z5(s,{allowed:e,disallowed:t}={}){let i=Wh(s,"inert-others");vr(()=>{var n,r;if(!i)return;let a=Io();for(let c of(n=t?.())!=null?n:[])c&&a.add(B_(c));let u=(r=e?.())!=null?r:[];for(let c of u){if(!c)continue;let d=qh(c);if(!d)continue;let f=c.parentElement;for(;f&&f!==d.body;){for(let p of f.children)u.some(y=>p.contains(y))||a.add(B_(p));f=f.parentElement}}return a.dispose},[i,e,t])}function G5(s,e,t){let i=Cu(n=>{let r=n.getBoundingClientRect();r.x===0&&r.y===0&&r.width===0&&r.height===0&&t()});_.useEffect(()=>{if(!s)return;let n=e===null?null:Su(e)?e:e.current;if(!n)return;let r=Io();if(typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}if(typeof IntersectionObserver<"u"){let a=new IntersectionObserver(()=>i.current(n));a.observe(n),r.add(()=>a.disconnect())}return()=>r.dispose()},[e,i,s])}let h0=["[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(","),V5=["[data-autofocus]"].map(s=>`${s}:not([tabindex='-1'])`).join(",");var Eo=(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))(Eo||{}),nx=(s=>(s[s.Error=0]="Error",s[s.Overflow=1]="Overflow",s[s.Success=2]="Success",s[s.Underflow=3]="Underflow",s))(nx||{}),q5=(s=>(s[s.Previous=-1]="Previous",s[s.Next=1]="Next",s))(q5||{});function K5(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(h0)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}function W5(s=document.body){return s==null?[]:Array.from(s.querySelectorAll(V5)).sort((e,t)=>Math.sign((e.tabIndex||Number.MAX_SAFE_INTEGER)-(t.tabIndex||Number.MAX_SAFE_INTEGER)))}var CA=(s=>(s[s.Strict=0]="Strict",s[s.Loose=1]="Loose",s))(CA||{});function Y5(s,e=0){var t;return s===((t=qh(s))==null?void 0:t.body)?!1:Lo(e,{0(){return s.matches(h0)},1(){let i=s;for(;i!==null;){if(i.matches(h0))return!0;i=i.parentElement}return!1}})}var X5=(s=>(s[s.Keyboard=0]="Keyboard",s[s.Mouse=1]="Mouse",s))(X5||{});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 ko(s){s?.focus({preventScroll:!0})}let Q5=["textarea","input"].join(",");function Z5(s){var e,t;return(t=(e=s?.matches)==null?void 0:e.call(s,Q5))!=null?t:!1}function J5(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 a=n.compareDocumentPosition(r);return a&Node.DOCUMENT_POSITION_FOLLOWING?-1:a&Node.DOCUMENT_POSITION_PRECEDING?1:0})}function xh(s,e,{sorted:t=!0,relativeTo:i=null,skipElements:n=[]}={}){let r=Array.isArray(s)?s.length>0?ex(s[0]):document:ex(s),a=Array.isArray(s)?t?J5(s):s:e&64?W5(s):K5(s);n.length>0&&a.length>1&&(a=a.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,a.indexOf(i))-1;if(e&4)return Math.max(0,a.indexOf(i))+1;if(e&8)return a.length-1;throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last")})(),d=e&32?{preventScroll:!0}:{},f=0,p=a.length,y;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}y=a[v],y?.focus(d),f+=u}while(y!==yA(y));return e&6&&Z5(y)&&y.select(),2}function DA(){return/iPhone/gi.test(window.navigator.platform)||/Mac/gi.test(window.navigator.platform)&&window.navigator.maxTouchPoints>0}function eN(){return/Android/gi.test(window.navigator.userAgent)}function U_(){return DA()||eN()}function bm(s,e,t,i){let n=Cu(t);_.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return document.addEventListener(e,r,i),()=>document.removeEventListener(e,r,i)},[s,e,i])}function LA(s,e,t,i){let n=Cu(t);_.useEffect(()=>{if(!s)return;function r(a){n.current(a)}return window.addEventListener(e,r,i),()=>window.removeEventListener(e,r,i)},[s,e,i])}const j_=30;function tN(s,e,t){let i=Cu(t),n=_.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(y){return typeof y=="function"?p(y()):Array.isArray(y)||y instanceof Set?y:[y]})(e);for(let p of f)if(p!==null&&(p.contains(d)||u.composed&&u.composedPath().includes(p)))return;return!Y5(d,CA.Loose)&&d.tabIndex!==-1&&u.preventDefault(),i.current(u,d)},[i,e]),r=_.useRef(null);bm(s,"pointerdown",u=>{var c,d;U_()||(r.current=((d=(c=u.composedPath)==null?void 0:c.call(u))==null?void 0:d[0])||u.target)},!0),bm(s,"pointerup",u=>{if(U_()||!r.current)return;let c=r.current;return r.current=null,n(u,()=>c)},!0);let a=_.useRef({x:0,y:0});bm(s,"touchstart",u=>{a.current.x=u.touches[0].clientX,a.current.y=u.touches[0].clientY},!0),bm(s,"touchend",u=>{let c={x:u.changedTouches[0].clientX,y:u.changedTouches[0].clientY};if(!(Math.abs(c.x-a.current.x)>=j_||Math.abs(c.y-a.current.y)>=j_))return n(u,()=>Al(u.target)?u.target:null)},!0),LA(s,"blur",u=>n(u,()=>b5(window.document.activeElement)?window.document.activeElement:null),!0)}function ob(...s){return _.useMemo(()=>qh(...s),[...s])}function RA(s,e,t,i){let n=Cu(t);_.useEffect(()=>{s=s??window;function r(a){n.current(a)}return s.addEventListener(e,r,i),()=>s.removeEventListener(e,r,i)},[s,e,i])}function iN(s){return _.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getSnapshot)}function sN(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 a=e[n].call(t,...r);a&&(t=a,i.forEach(u=>u()))}}}function nN(){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 rN(){return DA()?{before({doc:s,d:e,meta:t}){function i(n){for(let r of t().containers)for(let a of r())if(a.contains(n))return!0;return!1}e.microTask(()=>{var n;if(window.getComputedStyle(s.documentElement).scrollBehavior!=="auto"){let u=Io();u.style(s.documentElement,"scrollBehavior","auto"),e.add(()=>e.microTask(()=>u.dispose()))}let r=(n=window.scrollY)!=null?n:window.pageYOffset,a=null;e.addEventListener(s,"click",u=>{if(Al(u.target))try{let c=u.target.closest("a");if(!c)return;let{hash:d}=new URL(c.href),f=s.querySelector(d);Al(f)&&!i(f)&&(a=f)}catch{}},!0),e.group(u=>{e.addEventListener(s,"touchstart",c=>{if(u.dispose(),Al(c.target)&&x5(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(Al(u.target)){if(T5(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),a&&a.isConnected&&(a.scrollIntoView({block:"nearest"}),a=null)})})}}:{}}function aN(){return{before({doc:s,d:e}){e.style(s.documentElement,"overflow","hidden")}}}function $_(s){let e={};for(let t of s)Object.assign(e,t(e));return e}let fu=sN(()=>new Map,{PUSH(s,e){var t;let i=(t=this.get(s))!=null?t:{doc:s,count:0,d:Io(),meta:new Set,computedMeta:{}};return i.count++,i.meta.add(e),i.computedMeta=$_(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=$_(t.meta)),this},SCROLL_PREVENT(s){let e={doc:s.doc,d:s.d,meta(){return s.computedMeta}},t=[rN(),nN(),aN()];t.forEach(({before:i})=>i?.(e)),t.forEach(({after:i})=>i?.(e))},SCROLL_ALLOW({d:s}){s.dispose()},TEARDOWN({doc:s}){this.delete(s)}});fu.subscribe(()=>{let s=fu.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)&&fu.dispatch(t.count>0?"SCROLL_PREVENT":"SCROLL_ALLOW",t),t.count===0&&fu.dispatch("TEARDOWN",t)}});function oN(s,e,t=()=>({containers:[]})){let i=iN(fu),n=e?i.get(e):void 0,r=n?n.count>0:!1;return vr(()=>{if(!(!e||!s))return fu.dispatch("PUSH",e,t),()=>fu.dispatch("POP",e,t)},[s,e]),r}function lN(s,e,t=()=>[document.body]){let i=Wh(s,"scroll-lock");oN(i,e,n=>{var r;return{containers:[...(r=n.containers)!=null?r:[],t]}})}function uN(s=0){let[e,t]=_.useState(s),i=_.useCallback(c=>t(c),[]),n=_.useCallback(c=>t(d=>d|c),[]),r=_.useCallback(c=>(e&c)===c,[e]),a=_.useCallback(c=>t(d=>d&~c),[]),u=_.useCallback(c=>t(d=>d^c),[]);return{flags:e,setFlag:i,addFlag:n,hasFlag:r,removeFlag:a,toggleFlag:u}}var cN={},H_,z_;typeof process<"u"&&typeof globalThis<"u"&&typeof Element<"u"&&((H_=process==null?void 0:cN)==null?void 0:H_.NODE_ENV)==="test"&&typeof((z_=Element?.prototype)==null?void 0:z_.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 dN=(s=>(s[s.None=0]="None",s[s.Closed=1]="Closed",s[s.Enter=2]="Enter",s[s.Leave=4]="Leave",s))(dN||{});function hN(s){let e={};for(let t in s)s[t]===!0&&(e[`data-${t}`]="");return e}function fN(s,e,t,i){let[n,r]=_.useState(t),{hasFlag:a,addFlag:u,removeFlag:c}=uN(s&&n?3:0),d=_.useRef(!1),f=_.useRef(!1),p=Z0();return vr(()=>{var y;if(s){if(t&&r(!0),!e){t&&u(3);return}return(y=i?.start)==null||y.call(i,t),mN(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&&yN(e)||(d.current=!1,c(7),t||r(!1),(v=i?.end)==null||v.call(i,t))}})}},[s,t,e,p]),s?[n,{closed:a(1),enter:a(2),leave:a(4),transition:a(2)||a(4)}]:[t,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}function mN(s,{prepare:e,run:t,done:i,inFlight:n}){let r=Io();return gN(s,{prepare:e,inFlight:n}),r.nextFrame(()=>{t(),r.requestAnimationFrame(()=>{r.add(pN(s,i))})}),r.dispose}function pN(s,e){var t,i;let n=Io();if(!s)return n.dispose;let r=!1;n.add(()=>{r=!0});let a=(i=(t=s.getAnimations)==null?void 0:t.call(s).filter(u=>u instanceof CSSTransition))!=null?i:[];return a.length===0?(e(),n.dispose):(Promise.allSettled(a.map(u=>u.finished)).then(()=>{r||e()}),n.dispose)}function gN(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 yN(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 lb(s,e){let t=_.useRef([]),i=gs(s);_.useEffect(()=>{let n=[...t.current];for(let[r,a]of e.entries())if(t.current[r]!==a){let u=i(e,n);return t.current=e,u}},[i,...e])}let J0=_.createContext(null);J0.displayName="OpenClosedContext";var ha=(s=>(s[s.Open=1]="Open",s[s.Closed=2]="Closed",s[s.Closing=4]="Closing",s[s.Opening=8]="Opening",s))(ha||{});function ep(){return _.useContext(J0)}function vN({value:s,children:e}){return Qt.createElement(J0.Provider,{value:s},e)}function xN({children:s}){return Qt.createElement(J0.Provider,{value:null},s)}function bN(s){function e(){document.readyState!=="loading"&&(s(),document.removeEventListener("DOMContentLoaded",e))}typeof window<"u"&&typeof document<"u"&&(document.addEventListener("DOMContentLoaded",e),e())}let El=[];bN(()=>{function s(e){if(!Al(e.target)||e.target===document.body||El[0]===e.target)return;let t=e.target;t=t.closest(h0),El.unshift(t??e.target),El=El.filter(i=>i!=null&&i.isConnected),El.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 IA(s){let e=gs(s),t=_.useRef(!1);_.useEffect(()=>(t.current=!1,()=>{t.current=!0,Q0(()=>{t.current&&e()})}),[e])}let NA=_.createContext(!1);function TN(){return _.useContext(NA)}function G_(s){return Qt.createElement(NA.Provider,{value:s.force},s.children)}function SN(s){let e=TN(),t=_.useContext(MA),[i,n]=_.useState(()=>{var r;if(!e&&t!==null)return(r=t.current)!=null?r:null;if(Ha.isServer)return null;let a=s?.getElementById("headlessui-portal-root");if(a)return a;if(s===null)return null;let u=s.createElement("div");return u.setAttribute("id","headlessui-portal-root"),s.body.appendChild(u)});return _.useEffect(()=>{i!==null&&(s!=null&&s.body.contains(i)||s==null||s.body.appendChild(i))},[i,s]),_.useEffect(()=>{e||t!==null&&n(t.current)},[t,n,e]),i}let OA=_.Fragment,_N=br(function(s,e){let{ownerDocument:t=null,...i}=s,n=_.useRef(null),r=Xa(S5(y=>{n.current=y}),e),a=ob(n.current),u=t??a,c=SN(u),d=_.useContext(rx),f=Z0(),p=ea();return IA(()=>{var y;c&&c.childNodes.length<=0&&((y=c.parentElement)==null||y.removeChild(c))}),c?Oc.createPortal(Qt.createElement("div",{"data-headlessui-portal":"",ref:y=>{f.dispose(),d&&y&&f.add(d.register(y))}},p({ourProps:{ref:r},theirProps:i,slot:{},defaultTag:OA,name:"Portal"})),c):null});function EN(s,e){let t=Xa(e),{enabled:i=!0,ownerDocument:n,...r}=s,a=ea();return i?Qt.createElement(_N,{...r,ownerDocument:n,ref:t}):a({ourProps:{ref:t},theirProps:r,slot:{},defaultTag:OA,name:"Portal"})}let wN=_.Fragment,MA=_.createContext(null);function AN(s,e){let{target:t,...i}=s,n={ref:Xa(e)},r=ea();return Qt.createElement(MA.Provider,{value:t},r({ourProps:n,theirProps:i,defaultTag:wN,name:"Popover.Group"}))}let rx=_.createContext(null);function kN(){let s=_.useContext(rx),e=_.useRef([]),t=gs(r=>(e.current.push(r),s&&s.register(r),()=>i(r))),i=gs(r=>{let a=e.current.indexOf(r);a!==-1&&e.current.splice(a,1),s&&s.unregister(r)}),n=_.useMemo(()=>({register:t,unregister:i,portals:e}),[t,i,e]);return[e,_.useMemo(()=>function({children:r}){return Qt.createElement(rx.Provider,{value:n},r)},[n])]}let CN=br(EN),PA=br(AN),DN=Object.assign(CN,{Group:PA});function LN(s,e=typeof document<"u"?document.defaultView:null,t){let i=Wh(s,"escape");RA(e,"keydown",n=>{i&&(n.defaultPrevented||n.key===TA.Escape&&t(n))})}function RN(){var s;let[e]=_.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null),[t,i]=_.useState((s=e?.matches)!=null?s:!1);return vr(()=>{if(!e)return;function n(r){i(r.matches)}return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[e]),t}function IN({defaultContainers:s=[],portals:e,mainTreeNode:t}={}){let i=gs(()=>{var n,r;let a=qh(t),u=[];for(let c of s)c!==null&&(kl(c)?u.push(c):"current"in c&&kl(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=a?.querySelectorAll("html > *, body > *"))!=null?n:[])c!==document.body&&c!==document.head&&kl(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:gs(n=>i().some(r=>r.contains(n)))}}let BA=_.createContext(null);function V_({children:s,node:e}){let[t,i]=_.useState(null),n=FA(e??t);return Qt.createElement(BA.Provider,{value:n},s,n===null&&Qt.createElement(ix,{features:d0.Hidden,ref:r=>{var a,u;if(r){for(let c of(u=(a=qh(r))==null?void 0:a.querySelectorAll("html > *, body > *"))!=null?u:[])if(c!==document.body&&c!==document.head&&kl(c)&&c!=null&&c.contains(r)){i(c);break}}}}))}function FA(s=null){var e;return(e=_.useContext(BA))!=null?e:s}function NN(){let s=typeof document>"u";return"useSyncExternalStore"in w_?(e=>e.useSyncExternalStore)(w_)(()=>()=>{},()=>!1,()=>!s):!1}function tp(){let s=NN(),[e,t]=_.useState(Ha.isHandoffComplete);return e&&Ha.isHandoffComplete===!1&&t(!1),_.useEffect(()=>{e!==!0&&t(!0)},[e]),_.useEffect(()=>Ha.handoff(),[]),s?!1:e}function ub(){let s=_.useRef(!1);return vr(()=>(s.current=!0,()=>{s.current=!1}),[]),s}var dh=(s=>(s[s.Forwards=0]="Forwards",s[s.Backwards=1]="Backwards",s))(dh||{});function ON(){let s=_.useRef(0);return LA(!0,"keydown",e=>{e.key==="Tab"&&(s.current=e.shiftKey?1:0)},!0),s}function UA(s){if(!s)return new Set;if(typeof s=="function")return new Set(s());let e=new Set;for(let t of s.current)kl(t.current)&&e.add(t.current);return e}let MN="div";var du=(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))(du||{});function PN(s,e){let t=_.useRef(null),i=Xa(t,e),{initialFocus:n,initialFocusFallback:r,containers:a,features:u=15,...c}=s;tp()||(u=0);let d=ob(t.current);jN(u,{ownerDocument:d});let f=$N(u,{ownerDocument:d,container:t,initialFocus:n,initialFocusFallback:r});HN(u,{ownerDocument:d,container:t,containers:a,previousActiveElement:f});let p=ON(),y=gs(N=>{if(!Su(t.current))return;let R=t.current;(H=>H())(()=>{Lo(p.current,{[dh.Forwards]:()=>{xh(R,Eo.First,{skipElements:[N.relatedTarget,r]})},[dh.Backwards]:()=>{xh(R,Eo.Last,{skipElements:[N.relatedTarget,r]})}})})}),v=Wh(!!(u&2),"focus-trap#tab-lock"),b=Z0(),S=_.useRef(!1),E={ref:i,onKeyDown(N){N.key=="Tab"&&(S.current=!0,b.requestAnimationFrame(()=>{S.current=!1}))},onBlur(N){if(!(u&4))return;let R=UA(a);Su(t.current)&&R.add(t.current);let H=N.relatedTarget;Al(H)&&H.dataset.headlessuiFocusGuard!=="true"&&(jA(R,H)||(S.current?xh(t.current,Lo(p.current,{[dh.Forwards]:()=>Eo.Next,[dh.Backwards]:()=>Eo.Previous})|Eo.WrapAround,{relativeTo:N.target}):Al(N.target)&&ko(N.target)))}},L=ea();return Qt.createElement(Qt.Fragment,null,v&&Qt.createElement(ix,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:d0.Focusable}),L({ourProps:E,theirProps:c,defaultTag:MN,name:"FocusTrap"}),v&&Qt.createElement(ix,{as:"button",type:"button","data-headlessui-focus-guard":!0,onFocus:y,features:d0.Focusable}))}let BN=br(PN),FN=Object.assign(BN,{features:du});function UN(s=!0){let e=_.useRef(El.slice());return lb(([t],[i])=>{i===!0&&t===!1&&Q0(()=>{e.current.splice(0)}),i===!1&&t===!0&&(e.current=El.slice())},[s,El,e]),gs(()=>{var t;return(t=e.current.find(i=>i!=null&&i.isConnected))!=null?t:null})}function jN(s,{ownerDocument:e}){let t=!!(s&8),i=UN(t);lb(()=>{t||l5(e?.body)&&ko(i())},[t]),IA(()=>{t&&ko(i())})}function $N(s,{ownerDocument:e,container:t,initialFocus:i,initialFocusFallback:n}){let r=_.useRef(null),a=Wh(!!(s&1),"focus-trap#initial-focus"),u=ub();return lb(()=>{if(s===0)return;if(!a){n!=null&&n.current&&ko(n.current);return}let c=t.current;c&&Q0(()=>{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)ko(i.current);else{if(s&16){if(xh(c,Eo.First|Eo.AutoFocus)!==nx.Error)return}else if(xh(c,Eo.First)!==nx.Error)return;if(n!=null&&n.current&&(ko(n.current),e?.activeElement===n.current))return;console.warn("There are no focusable elements inside the ")}r.current=e?.activeElement})},[n,a,s]),r}function HN(s,{ownerDocument:e,container:t,containers:i,previousActiveElement:n}){let r=ub(),a=!!(s&4);RA(e?.defaultView,"focus",u=>{if(!a||!r.current)return;let c=UA(i);Su(t.current)&&c.add(t.current);let d=n.current;if(!d)return;let f=u.target;Su(f)?jA(c,f)?(n.current=f,ko(f)):(u.preventDefault(),u.stopPropagation(),ko(d)):ko(n.current)},!0)}function jA(s,e){for(let t of s)if(t.contains(e))return!0;return!1}function $A(s){var e;return!!(s.enter||s.enterFrom||s.enterTo||s.leave||s.leaveFrom||s.leaveTo)||!yh((e=s.as)!=null?e:zA)||Qt.Children.count(s.children)===1}let ip=_.createContext(null);ip.displayName="TransitionContext";var zN=(s=>(s.Visible="visible",s.Hidden="hidden",s))(zN||{});function GN(){let s=_.useContext(ip);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}function VN(){let s=_.useContext(sp);if(s===null)throw new Error("A is used but it is missing a parent or .");return s}let sp=_.createContext(null);sp.displayName="NestingContext";function np(s){return"children"in s?np(s.children):s.current.filter(({el:e})=>e.current!==null).filter(({state:e})=>e==="visible").length>0}function HA(s,e){let t=Cu(s),i=_.useRef([]),n=ub(),r=Z0(),a=gs((v,b=wl.Hidden)=>{let S=i.current.findIndex(({el:E})=>E===v);S!==-1&&(Lo(b,{[wl.Unmount](){i.current.splice(S,1)},[wl.Hidden](){i.current[S].state="hidden"}}),r.microTask(()=>{var E;!np(i)&&n.current&&((E=t.current)==null||E.call(t))}))}),u=gs(v=>{let b=i.current.find(({el:S})=>S===v);return b?b.state!=="visible"&&(b.state="visible"):i.current.push({el:v,state:"visible"}),()=>a(v,wl.Unmount)}),c=_.useRef([]),d=_.useRef(Promise.resolve()),f=_.useRef({enter:[],leave:[]}),p=gs((v,b,S)=>{c.current.splice(0),e&&(e.chains.current[b]=e.chains.current[b].filter(([E])=>E!==v)),e?.chains.current[b].push([v,new Promise(E=>{c.current.push(E)})]),e?.chains.current[b].push([v,new Promise(E=>{Promise.all(f.current[b].map(([L,N])=>N)).then(()=>E())})]),b==="enter"?d.current=d.current.then(()=>e?.wait.current).then(()=>S(b)):S(b)}),y=gs((v,b,S)=>{Promise.all(f.current[b].splice(0).map(([E,L])=>L)).then(()=>{var E;(E=c.current.shift())==null||E()}).then(()=>S(b))});return _.useMemo(()=>({children:i,register:u,unregister:a,onStart:p,onStop:y,wait:d,chains:f}),[u,a,i,p,y,f,d])}let zA=_.Fragment,GA=c0.RenderStrategy;function qN(s,e){var t,i;let{transition:n=!0,beforeEnter:r,afterEnter:a,beforeLeave:u,afterLeave:c,enter:d,enterFrom:f,enterTo:p,entered:y,leave:v,leaveFrom:b,leaveTo:S,...E}=s,[L,N]=_.useState(null),R=_.useRef(null),H=$A(s),F=Xa(...H?[R,e,N]:e===null?[]:[e]),$=(t=E.unmount)==null||t?wl.Unmount:wl.Hidden,{show:M,appear:W,initial:D}=GN(),[I,Q]=_.useState(M?"visible":"hidden"),K=VN(),{register:q,unregister:le}=K;vr(()=>q(R),[q,R]),vr(()=>{if($===wl.Hidden&&R.current){if(M&&I!=="visible"){Q("visible");return}return Lo(I,{hidden:()=>le(R),visible:()=>q(R)})}},[I,R,q,le,M,$]);let te=tp();vr(()=>{if(H&&te&&I==="visible"&&R.current===null)throw new Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[R,I,te,H]);let V=D&&!W,G=W&&M&&D,J=_.useRef(!1),ie=HA(()=>{J.current||(Q("hidden"),le(R))},K),oe=gs(Ve=>{J.current=!0;let Ze=Ve?"enter":"leave";ie.onStart(R,Ze,Je=>{Je==="enter"?r?.():Je==="leave"&&u?.()})}),j=gs(Ve=>{let Ze=Ve?"enter":"leave";J.current=!1,ie.onStop(R,Ze,Je=>{Je==="enter"?a?.():Je==="leave"&&c?.()}),Ze==="leave"&&!np(ie)&&(Q("hidden"),le(R))});_.useEffect(()=>{H&&n||(oe(M),j(M))},[M,H,n]);let X=!(!n||!H||!te||V),[,se]=fN(X,L,M,{start:oe,end:j}),fe=lu({ref:F,className:((i=tx(E.className,G&&d,G&&f,se.enter&&d,se.enter&&se.closed&&f,se.enter&&!se.closed&&p,se.leave&&v,se.leave&&!se.closed&&b,se.leave&&se.closed&&S,!se.transition&&M&&y))==null?void 0:i.trim())||void 0,...hN(se)}),pe=0;I==="visible"&&(pe|=ha.Open),I==="hidden"&&(pe|=ha.Closed),M&&I==="hidden"&&(pe|=ha.Opening),!M&&I==="visible"&&(pe|=ha.Closing);let de=ea();return Qt.createElement(sp.Provider,{value:ie},Qt.createElement(vN,{value:pe},de({ourProps:fe,theirProps:E,defaultTag:zA,features:GA,visible:I==="visible",name:"Transition.Child"})))}function KN(s,e){let{show:t,appear:i=!1,unmount:n=!0,...r}=s,a=_.useRef(null),u=$A(s),c=Xa(...u?[a,e]:e===null?[]:[e]);tp();let d=ep();if(t===void 0&&d!==null&&(t=(d&ha.Open)===ha.Open),t===void 0)throw new Error("A is used but it is missing a `show={true | false}` prop.");let[f,p]=_.useState(t?"visible":"hidden"),y=HA(()=>{t||p("hidden")}),[v,b]=_.useState(!0),S=_.useRef([t]);vr(()=>{v!==!1&&S.current[S.current.length-1]!==t&&(S.current.push(t),b(!1))},[S,t]);let E=_.useMemo(()=>({show:t,appear:i,initial:v}),[t,i,v]);vr(()=>{t?p("visible"):!np(y)&&a.current!==null&&p("hidden")},[t,y]);let L={unmount:n},N=gs(()=>{var F;v&&b(!1),(F=s.beforeEnter)==null||F.call(s)}),R=gs(()=>{var F;v&&b(!1),(F=s.beforeLeave)==null||F.call(s)}),H=ea();return Qt.createElement(sp.Provider,{value:y},Qt.createElement(ip.Provider,{value:E},H({ourProps:{...L,as:_.Fragment,children:Qt.createElement(VA,{ref:c,...L,...r,beforeEnter:N,beforeLeave:R})},theirProps:{},defaultTag:_.Fragment,features:GA,visible:f==="visible",name:"Transition"})))}function WN(s,e){let t=_.useContext(ip)!==null,i=ep()!==null;return Qt.createElement(Qt.Fragment,null,!t&&i?Qt.createElement(ax,{ref:e,...s}):Qt.createElement(VA,{ref:e,...s}))}let ax=br(KN),VA=br(qN),cb=br(WN),bh=Object.assign(ax,{Child:cb,Root:ax});var YN=(s=>(s[s.Open=0]="Open",s[s.Closed=1]="Closed",s))(YN||{}),XN=(s=>(s[s.SetTitleId=0]="SetTitleId",s))(XN||{});let QN={0(s,e){return s.titleId===e.id?s:{...s,titleId:e.id}}},db=_.createContext(null);db.displayName="DialogContext";function rp(s){let e=_.useContext(db);if(e===null){let t=new Error(`<${s} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,rp),t}return e}function ZN(s,e){return Lo(e.type,QN,s,e)}let q_=br(function(s,e){let t=_.useId(),{id:i=`headlessui-dialog-${t}`,open:n,onClose:r,initialFocus:a,role:u="dialog",autoFocus:c=!0,__demoMode:d=!1,unmount:f=!1,...p}=s,y=_.useRef(!1);u=(function(){return u==="dialog"||u==="alertdialog"?u:(y.current||(y.current=!0,console.warn(`Invalid role [${u}] passed to . Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`)),"dialog")})();let v=ep();n===void 0&&v!==null&&(n=(v&ha.Open)===ha.Open);let b=_.useRef(null),S=Xa(b,e),E=ob(b.current),L=n?0:1,[N,R]=_.useReducer(ZN,{titleId:null,descriptionId:null,panelRef:_.createRef()}),H=gs(()=>r(!1)),F=gs(se=>R({type:0,id:se})),$=tp()?L===0:!1,[M,W]=kN(),D={get current(){var se;return(se=N.panelRef.current)!=null?se:b.current}},I=FA(),{resolveContainers:Q}=IN({mainTreeNode:I,portals:M,defaultContainers:[D]}),K=v!==null?(v&ha.Closing)===ha.Closing:!1;z5(d||K?!1:$,{allowed:gs(()=>{var se,fe;return[(fe=(se=b.current)==null?void 0:se.closest("[data-headlessui-portal]"))!=null?fe:null]}),disallowed:gs(()=>{var se;return[(se=I?.closest("body > *:not(#headlessui-portal-root)"))!=null?se:null]})});let q=AA.get(null);vr(()=>{if($)return q.actions.push(i),()=>q.actions.pop(i)},[q,i,$]);let le=kA(q,_.useCallback(se=>q.selectors.isTop(se,i),[q,i]));tN(le,Q,se=>{se.preventDefault(),H()}),LN(le,E?.defaultView,se=>{se.preventDefault(),se.stopPropagation(),document.activeElement&&"blur"in document.activeElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur(),H()}),lN(d||K?!1:$,E,Q),G5($,b,H);let[te,V]=_5(),G=_.useMemo(()=>[{dialogState:L,close:H,setTitleId:F,unmount:f},N],[L,H,F,f,N]),J=Kh({open:L===0}),ie={ref:S,id:i,role:u,tabIndex:-1,"aria-modal":d?void 0:L===0?!0:void 0,"aria-labelledby":N.titleId,"aria-describedby":te,unmount:f},oe=!RN(),j=du.None;$&&!d&&(j|=du.RestoreFocus,j|=du.TabLock,c&&(j|=du.AutoFocus),oe&&(j|=du.InitialFocus));let X=ea();return Qt.createElement(xN,null,Qt.createElement(G_,{force:!0},Qt.createElement(DN,null,Qt.createElement(db.Provider,{value:G},Qt.createElement(PA,{target:b},Qt.createElement(G_,{force:!1},Qt.createElement(V,{slot:J},Qt.createElement(W,null,Qt.createElement(FN,{initialFocus:a,initialFocusFallback:b,containers:Q,features:j},Qt.createElement(D5,{value:H},X({ourProps:ie,theirProps:p,slot:J,defaultTag:JN,features:eO,visible:L===0,name:"Dialog"})))))))))))}),JN="div",eO=c0.RenderStrategy|c0.Static;function tO(s,e){let{transition:t=!1,open:i,...n}=s,r=ep(),a=s.hasOwnProperty("open")||r!==null,u=s.hasOwnProperty("onClose");if(!a&&!u)throw new Error("You have to provide an `open` and an `onClose` prop to the `Dialog` component.");if(!a)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?Qt.createElement(V_,null,Qt.createElement(bh,{show:i,transition:t,unmount:n.unmount},Qt.createElement(q_,{ref:e,...n}))):Qt.createElement(V_,null,Qt.createElement(q_,{ref:e,open:i,...n}))}let iO="div";function sO(s,e){let t=_.useId(),{id:i=`headlessui-dialog-panel-${t}`,transition:n=!1,...r}=s,[{dialogState:a,unmount:u},c]=rp("Dialog.Panel"),d=Xa(e,c.panelRef),f=Kh({open:a===0}),p=gs(E=>{E.stopPropagation()}),y={ref:d,id:i,onClick:p},v=n?cb:_.Fragment,b=n?{unmount:u}:{},S=ea();return Qt.createElement(v,{...b},S({ourProps:y,theirProps:r,slot:f,defaultTag:iO,name:"Dialog.Panel"}))}let nO="div";function rO(s,e){let{transition:t=!1,...i}=s,[{dialogState:n,unmount:r}]=rp("Dialog.Backdrop"),a=Kh({open:n===0}),u={ref:e,"aria-hidden":!0},c=t?cb:_.Fragment,d=t?{unmount:r}:{},f=ea();return Qt.createElement(c,{...d},f({ourProps:u,theirProps:i,slot:a,defaultTag:nO,name:"Dialog.Backdrop"}))}let aO="h2";function oO(s,e){let t=_.useId(),{id:i=`headlessui-dialog-title-${t}`,...n}=s,[{dialogState:r,setTitleId:a}]=rp("Dialog.Title"),u=Xa(e);_.useEffect(()=>(a(i),()=>a(null)),[i,a]);let c=Kh({open:r===0}),d={ref:u,id:i};return ea()({ourProps:d,theirProps:n,slot:c,defaultTag:aO,name:"Dialog.Title"})}let lO=br(tO),uO=br(sO);br(rO);let cO=br(oO),xc=Object.assign(lO,{Panel:uO,Title:cO,Description:k5});function dO({open:s,onClose:e,onApply:t,initialCookies:i}){const[n,r]=_.useState(""),[a,u]=_.useState(""),[c,d]=_.useState([]),f=_.useRef(!1);_.useEffect(()=>{s&&!f.current&&(r(""),u(""),d(i??[])),f.current=s},[s,i]);function p(){const b=n.trim(),S=a.trim();!b||!S||(d(E=>[...E.filter(N=>N.name!==b),{name:b,value:S}]),r(""),u(""))}function y(b){d(S=>S.filter(E=>E.name!==b))}function v(){t(c),e()}return g.jsxs(xc,{open:s,onClose:e,className:"relative z-50",children:[g.jsx("div",{className:"fixed inset-0 bg-black/40","aria-hidden":"true"}),g.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:g.jsxs(xc.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:[g.jsx(xc.Title,{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Zusätzliche Cookies"}),g.jsxs("div",{className:"mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2",children:[g.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"}),g.jsx("input",{value:a,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"})]}),g.jsx("div",{className:"mt-2",children:g.jsx(oi,{size:"sm",variant:"secondary",onClick:p,disabled:!n.trim()||!a.trim(),children:"Hinzufügen"})}),g.jsx("div",{className:"mt-4",children:c.length===0?g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Noch keine Cookies hinzugefügt."}):g.jsxs("table",{className:"min-w-full text-sm border divide-y dark:divide-white/10",children:[g.jsx("thead",{className:"bg-gray-50 dark:bg-gray-700/50",children:g.jsxs("tr",{children:[g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Name"}),g.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Wert"}),g.jsx("th",{className:"px-3 py-2"})]})}),g.jsx("tbody",{className:"divide-y dark:divide-white/10",children:c.map(b=>g.jsxs("tr",{children:[g.jsx("td",{className:"px-3 py-2 font-mono",children:b.name}),g.jsx("td",{className:"px-3 py-2 truncate max-w-[240px]",children:b.value}),g.jsx("td",{className:"px-3 py-2 text-right",children:g.jsx("button",{onClick:()=>y(b.name),className:"text-xs text-red-600 hover:underline dark:text-red-400",children:"Entfernen"})})]},b.name))})]})}),g.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[g.jsx(oi,{variant:"secondary",onClick:e,children:"Abbrechen"}),g.jsx(oi,{variant:"primary",onClick:v,children:"Übernehmen"})]})]})})]})}function hO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 fO=_.forwardRef(hO);function ox({tabs:s,value:e,onChange:t,className:i,ariaLabel:n="Ansicht auswählen",variant:r="underline",hideCountUntilMd:a=!1}){if(!s?.length)return null;const u=s.find(y=>y.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=y=>wi(y?"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",a?"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=(y,v)=>v.count===void 0?null:g.jsx("span",{className:d(y),children:v.count}),p=()=>{switch(r){case"underline":case"underlineIcons":return g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex space-x-8",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!b&&t(y.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"&&y.icon?g.jsx(y.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,g.jsx("span",{children:y.label}),f(v,y)]},y.id)})})});case"pills":case"pillsGray":case"pillsBrand":{const y=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 g.jsx("nav",{"aria-label":n,className:"flex space-x-4",children:s.map(b=>{const S=b.id===u.id,E=!!b.disabled;return g.jsxs("button",{type:"button",onClick:()=>!E&&t(b.id),disabled:E,"aria-current":S?"page":void 0,className:wi(S?y:v,"inline-flex items-center rounded-md px-3 py-2 text-sm font-medium",E&&"cursor-not-allowed opacity-50 hover:text-inherit"),children:[g.jsx("span",{children:b.label}),b.count!==void 0?g.jsx("span",{className:wi(S?"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 g.jsx("div",{className:"border-b border-gray-200 dark:border-white/10",children:g.jsx("nav",{"aria-label":n,className:"-mb-px flex",children:s.map(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("button",{type:"button",onClick:()=>!b&&t(y.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:y.label},y.id)})})});case"barUnderline":return g.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((y,v)=>{const b=y.id===u.id,S=!!y.disabled;return g.jsxs("button",{type:"button",onClick:()=>!S&&t(y.id),disabled:S,"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",S&&"cursor-not-allowed opacity-50 hover:bg-transparent hover:text-gray-500 dark:hover:text-gray-400"),children:[g.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center justify-center",children:[g.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",title:y.label,children:y.label}),y.count!==void 0?g.jsx("span",{className:"ml-2 shrink-0 tabular-nums min-w-[2.25rem] rounded-full bg-white/70 px-2 py-0.5 text-center text-xs font-medium text-gray-900 dark:bg-white/10 dark:text-white",children:y.count}):null]}),g.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")})]},y.id)})});case"simple":return g.jsx("nav",{className:"flex border-b border-gray-200 py-4 dark:border-white/10","aria-label":n,children:g.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(y=>{const v=y.id===u.id,b=!!y.disabled;return g.jsx("li",{children:g.jsx("button",{type:"button",onClick:()=>!b&&t(y.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:y.label})},y.id)})})});default:return null}};return g.jsxs("div",{className:i,children:[g.jsxs("div",{className:"grid grid-cols-1 sm:hidden",children:[g.jsx("select",{value:u.id,onChange:y=>t(y.target.value),"aria-label":n,className:c,children:s.map(y=>g.jsx("option",{value:y.id,children:y.label},y.id))}),g.jsx(fO,{"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"})]}),g.jsx("div",{className:"hidden sm:block",children:p()})]})}function fa({header:s,footer:e,grayBody:t=!1,grayFooter:i=!1,edgeToEdgeMobile:n=!1,well:r=!1,noBodyPadding:a=!1,className:u,bodyClassName:c,children:d}){const f=r;return g.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&&g.jsx("div",{className:"shrink-0 px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-white/10",children:s}),g.jsx("div",{className:wi("min-h-0",a?"p-0":"px-4 py-5 sm:p-6",t&&"bg-gray-50 dark:bg-gray-800",c),children:d}),e&&g.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 lx({checked:s,onChange:e,id:t,name:i,disabled:n,required:r,ariaLabel:a,ariaLabelledby:u,ariaDescribedby:c,size:d="default",variant:f="simple",className:p}){const y=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"?g.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:[g.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")}),g.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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]}):g.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"?g.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:[g.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:g.jsx("svg",{fill:"none",viewBox:"0 0 12 12",className:"size-3 text-gray-400 dark:text-gray-600",children:g.jsx("path",{d:"M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"})})}),g.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:g.jsx("svg",{fill:"currentColor",viewBox:"0 0 12 12",className:"size-3 text-indigo-600 dark:text-indigo-500",children:g.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"})})})]}):g.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")}),g.jsx("input",{id:t,name:i,type:"checkbox",checked:s,onChange:y,disabled:n,required:r,"aria-label":a,"aria-labelledby":u,"aria-describedby":c,className:v})]})}function bo({label:s,description:e,labelPosition:t="left",id:i,className:n,...r}){const a=_.useId(),u=i??`sw-${a}`,c=`${u}-label`,d=`${u}-desc`;return t==="right"?g.jsxs("div",{className:wi("flex items-center justify-between gap-3",n),children:[g.jsx(lx,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0}),g.jsxs("div",{className:"text-sm",children:[g.jsx("label",{id:c,htmlFor:u,className:"font-medium text-gray-900 dark:text-white",children:s})," ",e?g.jsx("span",{id:d,className:"text-gray-500 dark:text-gray-400",children:e}):null]})]}):g.jsxs("div",{className:wi("flex items-center justify-between",n),children:[g.jsxs("span",{className:"flex grow flex-col",children:[g.jsx("label",{id:c,htmlFor:u,className:"text-sm/6 font-medium text-gray-900 dark:text-white",children:s}),e?g.jsx("span",{id:d,className:"text-sm text-gray-500 dark:text-gray-400",children:e}):null]}),g.jsx(lx,{...r,id:u,ariaLabelledby:c,ariaDescribedby:e?d:void 0})]})}const Mc=new Map;let K_=!1;function mO(){K_||(K_=!0,document.addEventListener("visibilitychange",()=>{if(document.hidden)for(const s of Mc.values())s.es&&(s.es.close(),s.es=null,s.dispatchers.clear());else for(const s of Mc.values())s.refs>0&&!s.es&&qA(s)}))}function qA(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 a of t)a(r)};s.dispatchers.set(e,i),s.es.addEventListener(e,i)}s.es.onerror=()=>{}}}function pO(s){s.es&&(s.es.close(),s.es=null,s.dispatchers.clear())}function gO(s){let e=Mc.get(s);return e||(e={url:s,es:null,refs:0,listeners:new Map,dispatchers:new Map},Mc.set(s,e)),e}function ap(s,e,t){mO();const i=gO(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=a=>{let u=null;try{u=JSON.parse(String(a.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 qA(i);return()=>{const r=Mc.get(s);if(!r)return;const a=r.listeners.get(e);a&&(a.delete(t),a.size===0&&r.listeners.delete(e)),r.refs=Math.max(0,r.refs-1),r.refs===0&&(pO(r),Mc.delete(s))}}async function yO(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 vO({onFinished:s,onStart:e,onProgress:t,onDone:i,onCancelled:n,onError:r}){const[a,u]=_.useState(null),[c,d]=_.useState(!1),[f,p]=_.useState(null),y=_.useRef(null),v=_.useRef(!1),b=_.useRef(!1),S=_.useRef(!1),E=_.useRef(!1),L=_.useRef(""),N=_.useRef(t),R=_.useRef(r);_.useEffect(()=>{N.current=t},[t]),_.useEffect(()=>{R.current=r},[r]);async function H(){if(!S.current){S.current=!0;try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}finally{S.current=!1}}}function F(){if(y.current)return y.current;const D=new AbortController;y.current=D;const I=()=>{b.current=!0,H()};return D.signal.addEventListener("abort",I,{once:!0}),D}function $(D){v.current||(v.current=!0,e?.(D))}_.useEffect(()=>{const D=E.current,I=!!a?.running;if(E.current=I,D&&!I){const Q=String(a?.error??"").trim();y.current=null,v.current=!1,b.current||Q==="abgebrochen"?(b.current=!1,n?.()):Q||i?.(),s?.()}},[a?.running,a?.error,s,i,n]),_.useEffect(()=>{const D=ap("/api/tasks/assets/stream","state",I=>{if(u(I),I?.running){const K=F();$(K),N.current?.({done:I?.done??0,total:I?.total??0})}const Q=String(I?.error??"").trim();Q&&Q!==L.current&&(L.current=Q,R.current?.(Q))});return()=>D()},[]);async function M(){if(a?.running)return;p(null),d(!0),b.current=!1,L.current="";const D=F();try{const I=await yO("/api/tasks/generate-assets",{method:"POST"});u(I),$(D),I?.running&&t?.({done:I?.done??0,total:I?.total??0})}catch(I){y.current=null,v.current=!1;const Q=I?.message??String(I);p(Q),r?.(Q)}finally{d(!1)}}const W=!!a?.running;return g.jsxs("div",{className:"flex items-center justify-between gap-4",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Assets-Generator"}),g.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Erzeugt fehlende Assets (thumb/preview/meta). Fortschritt & Abbrechen oben in der Taskliste."}),f?g.jsx("div",{className:"mt-2 text-xs text-red-700 dark:text-red-200",children:f}):null]}),g.jsx("div",{className:"shrink-0",children:g.jsx(oi,{variant:"primary",onClick:M,disabled:c||W,children:c?"Starte…":"Start"})})]})}function xO(s,e){const t=Number(s??0),i=Number(e??0);return!i||i<=0?0:Math.max(0,Math.min(100,Math.round(t/i*100)))}function bO({tasks:s,onCancel:e}){const t=(s||[]).filter(i=>i.status!=="idle");return g.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:[g.jsx("div",{className:"flex items-start justify-between gap-3",children:g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Hintergrundaufgaben"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Laufende Hintergrundaufgaben (z.B. Assets/Previews)."})]})}),g.jsxs("div",{className:"mt-3 space-y-3",children:[t.length===0?g.jsx("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 text-sm text-gray-600 dark:border-white/10 dark:bg-white/5 dark:text-gray-300",children:"Keine laufenden Aufgaben."}):null,t.map(i=>{const n=xO(i.done,i.total),r=i.status==="running",a=r&&(i.total??0)>0,u=(i.title??"").trim(),c=(i.text??"").trim();return g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5 transition-opacity duration-500 "+(i.fading?"opacity-0":"opacity-100"),children:[g.jsxs("div",{className:"flex items-center gap-3",children:[g.jsx("div",{className:"shrink-0",children:r&&i.cancellable&&e?g.jsx("button",{type:"button",onClick:()=>e?.(i.id),className:`inline-flex h-7 w-7 items-center justify-center rounded-md\r text-red-700 hover:bg-red-50 hover:text-red-900\r dark:text-red-300 dark:hover:bg-red-500/10 dark:hover:text-red-200`,title:"Abbrechen","aria-label":"Task abbrechen",children:"✕"}):i.status==="done"?g.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-green-700 dark:text-green-300",title:"Fertig","aria-label":"Fertig",children:"✓"}):g.jsx("span",{className:"inline-block h-7 w-7"})}),g.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[g.jsxs("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:[u||"Aufgabe",c?g.jsxs("span",{className:"font-normal text-gray-600 dark:text-gray-300",children:[" · ",c]}):null]}),i.status==="done"?g.jsx("span",{className:"shrink-0 inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-[11px] font-semibold text-green-800 ring-1 ring-inset ring-green-200 dark:bg-green-500/20 dark:text-green-200 dark:ring-green-400/30",children:"fertig"}):i.status==="cancelled"?g.jsx("span",{className:"shrink-0 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/10 dark:text-gray-200 dark:ring-white/10",children:"abgebrochen"}):i.status==="error"?g.jsx("span",{className:"shrink-0 inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-semibold text-red-800 ring-1 ring-inset ring-red-200 dark:bg-red-500/20 dark:text-red-200 dark:ring-red-400/30",children:"fehler"}):null,g.jsx("div",{className:"flex-1"}),a?g.jsxs("div",{className:"shrink-0 flex items-center gap-3 text-xs text-gray-600 dark:text-gray-300",children:[g.jsxs("span",{className:"tabular-nums",children:[i.done??0,"/",i.total??0]}),g.jsxs("span",{className:"tabular-nums",children:[n,"%"]}),g.jsx("div",{className:"hidden sm:block h-2 w-40 overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:g.jsx("div",{className:"h-full bg-indigo-500",style:{width:`${n}%`}})})]}):null]})]}),i.status==="error"&&i.err?g.jsx("div",{className:"mt-2 text-xs text-red-700 dark:text-red-200",children:i.err}):null]},i.id)})]})]})}const en={recordDir:"records",doneDir:"records/done",ffmpegPath:"",autoAddToDownloadList:!0,useChaturbateApi:!1,useMyFreeCamsWatcher:!1,autoDeleteSmallDownloads:!0,autoDeleteSmallDownloadsBelowMB:200,blurPreviews:!1,teaserPlayback:"hover",teaserAudio:!1,lowDiskPauseBelowGB:5,enableNotifications:!0};function TO({onAssetsGenerated:s}){const[e,t]=_.useState(en),[i,n]=_.useState(!1),[r,a]=_.useState(!1),[u,c]=_.useState(null),[d,f]=_.useState(null),[p,y]=_.useState(null),[v,b]=_.useState(null),S=_.useRef(null),[E,L]=_.useState({id:"generate-assets",status:"idle",title:"Assets generieren",text:"",cancellable:!0,fading:!1}),[N,R]=_.useState({id:"cleanup",status:"idle",title:"Aufräumen",text:"",cancellable:!1,fading:!1}),H=Number(e.lowDiskPauseBelowGB??en.lowDiskPauseBelowGB??5),F=v?.pauseGB??H,$=v?.resumeGB??H+3;_.useEffect(()=>{let K=!0;return fetch("/api/settings",{cache:"no-store"}).then(async q=>{if(!q.ok)throw new Error(await q.text());return q.json()}).then(q=>{K&&t({recordDir:(q.recordDir||en.recordDir).toString(),doneDir:(q.doneDir||en.doneDir).toString(),ffmpegPath:String(q.ffmpegPath??en.ffmpegPath??""),autoAddToDownloadList:q.autoAddToDownloadList??en.autoAddToDownloadList,autoStartAddedDownloads:q.autoStartAddedDownloads??en.autoStartAddedDownloads,useChaturbateApi:q.useChaturbateApi??en.useChaturbateApi,useMyFreeCamsWatcher:q.useMyFreeCamsWatcher??en.useMyFreeCamsWatcher,autoDeleteSmallDownloads:q.autoDeleteSmallDownloads??en.autoDeleteSmallDownloads,autoDeleteSmallDownloadsBelowMB:q.autoDeleteSmallDownloadsBelowMB??en.autoDeleteSmallDownloadsBelowMB,blurPreviews:q.blurPreviews??en.blurPreviews,teaserPlayback:q.teaserPlayback??en.teaserPlayback,teaserAudio:q.teaserAudio??en.teaserAudio,lowDiskPauseBelowGB:q.lowDiskPauseBelowGB??en.lowDiskPauseBelowGB,enableNotifications:q.enableNotifications??en.enableNotifications})}).catch(()=>{}),()=>{K=!1}},[]),_.useEffect(()=>{let K=!0;const q=async()=>{try{const te=await fetch("/api/status/disk",{cache:"no-store"});if(!te.ok)return;const V=await te.json();K&&b(V)}catch{}};q();const le=window.setInterval(q,5e3);return()=>{K=!1,window.clearInterval(le)}},[]);async function M(K){y(null),f(null),c(K);try{window.focus();const q=await fetch(`/api/settings/browse?target=${K}`,{cache:"no-store"});if(q.status===204)return;if(!q.ok){const V=await q.text().catch(()=>"");throw new Error(V||`HTTP ${q.status}`)}const te=((await q.json()).path??"").trim();if(!te)return;t(V=>K==="record"?{...V,recordDir:te}:K==="done"?{...V,doneDir:te}:{...V,ffmpegPath:te})}catch(q){y(q?.message??String(q))}finally{c(null)}}async function W(){y(null),f(null);const K=e.recordDir.trim(),q=e.doneDir.trim(),le=(e.ffmpegPath??"").trim();if(!K||!q){y("Bitte Aufnahme-Ordner und Ziel-Ordner angeben.");return}const te=!!e.autoAddToDownloadList,V=te?!!e.autoStartAddedDownloads:!1,G=!!e.useChaturbateApi,J=!!e.useMyFreeCamsWatcher,ie=!!e.autoDeleteSmallDownloads,oe=Math.max(0,Math.min(1e5,Math.floor(Number(e.autoDeleteSmallDownloadsBelowMB??en.autoDeleteSmallDownloadsBelowMB)))),j=!!e.blurPreviews,X=e.teaserPlayback==="still"||e.teaserPlayback==="all"||e.teaserPlayback==="hover"?e.teaserPlayback:en.teaserPlayback,se=!!e.teaserAudio,fe=Math.max(1,Math.floor(Number(e.lowDiskPauseBelowGB??en.lowDiskPauseBelowGB))),pe=!!e.enableNotifications;n(!0);try{const de=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recordDir:K,doneDir:q,ffmpegPath:le,autoAddToDownloadList:te,autoStartAddedDownloads:V,useChaturbateApi:G,useMyFreeCamsWatcher:J,autoDeleteSmallDownloads:ie,autoDeleteSmallDownloadsBelowMB:oe,blurPreviews:j,teaserPlayback:X,teaserAudio:se,lowDiskPauseBelowGB:fe,enableNotifications:pe})});if(!de.ok){const Ve=await de.text().catch(()=>"");throw new Error(Ve||`HTTP ${de.status}`)}f("✅ Gespeichert."),window.dispatchEvent(new CustomEvent("recorder-settings-updated"))}catch(de){y(de?.message??String(de))}finally{n(!1)}}function D(K,q=3500,le=500){window.setTimeout(()=>{K(te=>({...te,fading:!0})),window.setTimeout(()=>{K(te=>({...te,status:"idle",text:"",err:void 0,done:0,total:0,fading:!1}))},le)},q)}async function I(){y(null),f(null);const K=Number(e.autoDeleteSmallDownloadsBelowMB??en.autoDeleteSmallDownloadsBelowMB??0),q=(e.doneDir||en.doneDir).trim();if(!q){y("doneDir ist leer.");return}if(!K||K<=0){y("Mindestgröße ist 0 – es würde nichts gelöscht.");return}if(window.confirm(`Aufräumen: • Löscht Dateien in "${q}" < ${K} MB (Ordner "keep" wird übersprungen) • Entfernt verwaiste Previews/Thumbs/Generated-Assets ohne passende Datei Fortfahren?`)){a(!0),R(te=>({...te,status:"running",title:"Aufräumen",text:"Räume auf…",err:void 0,done:0,total:1,fading:!1}));try{const te=await fetch("/api/settings/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store"});if(!te.ok){const j=await te.text().catch(()=>"");throw new Error(j||`HTTP ${te.status}`)}const V=await te.json(),G=Number(V.scannedFiles??0),J=Number(V.orphanIdsRemoved??0),ie=Number(V.generatedOrphansRemoved??0),oe=J+ie;R(j=>({...j,status:"done",done:1,total:1,title:"Aufräumen",text:`geprüft: ${G} · Orphans: ${oe}`})),D(R)}catch(te){const V=te?.message??String(te);y(V),R(G=>({...G,status:"error",text:"Fehler beim Aufräumen.",err:V})),D(R)}finally{a(!1)}}}async function Q(){const K=S.current;if(S.current=null,L(q=>({...q,status:"cancelled",text:"Abgebrochen."})),K){K.abort();return}try{await fetch("/api/tasks/generate-assets",{method:"DELETE",cache:"no-store"})}catch{}}return g.jsx(fa,{header:g.jsxs("div",{className:"flex items-center justify-between gap-4",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"Einstellungen"}),g.jsx("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:"Recorder-Konfiguration, Automatisierung und Tasks."})]}),g.jsx(oi,{variant:"primary",onClick:W,disabled:i,children:"Speichern"})]}),grayBody:!0,children:g.jsxs("div",{className:"space-y-4",children:[g.jsx(bO,{tasks:[E,N],onCancel:K=>{K==="generate-assets"&&Q()}}),p&&g.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&&g.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}),g.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:[g.jsx("div",{className:"flex items-start justify-between gap-4",children:g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Aufgaben"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Hintergrundaufgaben wie z.B. Asset/Preview-Generierung."})]})}),g.jsx("div",{className:"mt-3 space-y-3",children:g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 flex-1",children:g.jsx(vO,{onFinished:s,onStart:K=>{S.current=K,L(q=>({...q,status:"running",text:"",done:0,total:0,err:void 0,fading:!1}))},onProgress:K=>{L(q=>({...q,status:"running",text:"",done:K.done,total:K.total}))},onDone:()=>{S.current=null,L(K=>({...K,status:"done"})),D(L)},onCancelled:()=>{S.current=null,L(K=>({...K,status:"cancelled",text:"Abgebrochen."})),D(L)},onError:K=>{S.current=null,L(q=>({...q,status:"error",text:"Fehler beim Generieren.",err:K})),D(L)}})}),g.jsx("div",{className:"shrink-0 flex items-center gap-2",children:g.jsx(oi,{variant:"secondary",onClick:I,disabled:i||r||!e.autoDeleteSmallDownloads,className:"h-9 px-3",title:"Löscht Dateien im doneDir kleiner als die Mindestgröße (keep wird übersprungen)",children:r?"…":"Aufräumen"})})]})})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Pfad-Einstellungen"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aufnahme- und Zielverzeichnisse sowie optionaler ffmpeg-Pfad."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Aufnahme-Ordner"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.recordDir,onChange:K=>t(q=>({...q,recordDir:K.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`}),g.jsx(oi,{variant:"secondary",onClick:()=>M("record"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"Fertige Downloads nach"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.doneDir,onChange:K=>t(q=>({...q,doneDir:K.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`}),g.jsx(oi,{variant:"secondary",onClick:()=>M("done"),disabled:i||u!==null,children:"Durchsuchen..."})]})]}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsx("label",{className:"text-sm font-medium text-gray-900 dark:text-gray-200 sm:col-span-3",children:"ffmpeg.exe"}),g.jsxs("div",{className:"sm:col-span-9 flex gap-2",children:[g.jsx("input",{value:e.ffmpegPath??"",onChange:K=>t(q=>({...q,ffmpegPath:K.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`}),g.jsx(oi,{variant:"secondary",onClick:()=>M("ffmpeg"),disabled:i||u!==null,children:"Durchsuchen..."})]})]})]})]}),g.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:[g.jsxs("div",{className:"mb-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Automatisierung & Anzeige"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Verhalten beim Hinzufügen/Starten sowie Anzeigeoptionen."})]}),g.jsxs("div",{className:"space-y-3",children:[g.jsx(bo,{checked:!!e.autoAddToDownloadList,onChange:K=>t(q=>({...q,autoAddToDownloadList:K,autoStartAddedDownloads:K?q.autoStartAddedDownloads:!1})),label:"Automatisch zur Downloadliste hinzufügen",description:"Neue Links/Modelle werden automatisch in die Downloadliste übernommen."}),g.jsx(bo,{checked:!!e.autoStartAddedDownloads,onChange:K=>t(q=>({...q,autoStartAddedDownloads:K})),disabled:!e.autoAddToDownloadList,label:"Hinzugefügte Downloads automatisch starten",description:"Wenn ein Download hinzugefügt wurde, startet er direkt (sofern möglich)."}),g.jsx(bo,{checked:!!e.useChaturbateApi,onChange:K=>t(q=>({...q,useChaturbateApi:K})),label:"Chaturbate API",description:"Wenn aktiv, pollt das Backend alle paar Sekunden die Online-Rooms API und cached die aktuell online Models."}),g.jsx(bo,{checked:!!e.useMyFreeCamsWatcher,onChange:K=>t(q=>({...q,useMyFreeCamsWatcher:K})),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."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx(bo,{checked:!!e.autoDeleteSmallDownloads,onChange:K=>t(q=>({...q,autoDeleteSmallDownloads:K,autoDeleteSmallDownloadsBelowMB:q.autoDeleteSmallDownloadsBelowMB??50})),label:"Kleine Downloads automatisch löschen",description:"Löscht fertige Downloads automatisch, wenn die Datei kleiner als die eingestellte Mindestgröße ist."}),g.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:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Mindestgröße"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Alles darunter wird gelöscht."})]}),g.jsx("div",{className:"sm:col-span-8",children:g.jsxs("div",{className:"flex items-center justify-end gap-2",children:[g.jsx("input",{type:"number",min:0,step:1,value:e.autoDeleteSmallDownloadsBelowMB??50,onChange:K=>t(q=>({...q,autoDeleteSmallDownloadsBelowMB:Number(K.target.value||0)})),className:`h-9 w-32 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`}),g.jsx("span",{className:"shrink-0 text-xs text-gray-600 dark:text-gray-300",children:"MB"})]})})]})]}),g.jsx(bo,{checked:!!e.blurPreviews,onChange:K=>t(q=>({...q,blurPreviews:K})),label:"Vorschaubilder blurren",description:"Weichzeichnet Vorschaubilder/Teaser (praktisch auf mobilen Geräten oder im öffentlichen Umfeld)."}),g.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-12 sm:items-center",children:[g.jsxs("div",{className:"sm:col-span-4",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-200",children:"Teaser abspielen"}),g.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."})]}),g.jsxs("div",{className:"sm:col-span-8",children:[g.jsx("label",{className:"sr-only",htmlFor:"teaserPlayback",children:"Teaser abspielen"}),g.jsxs("select",{id:"teaserPlayback",value:e.teaserPlayback??"hover",onChange:K=>t(q=>({...q,teaserPlayback:K.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:[g.jsx("option",{value:"still",children:"Standbild"}),g.jsx("option",{value:"hover",children:"Bei Hover (Standard)"}),g.jsx("option",{value:"all",children:"Alle"})]})]})]}),g.jsx(bo,{checked:!!e.teaserAudio,onChange:K=>t(q=>({...q,teaserAudio:K})),label:"Teaser mit Ton",description:"Wenn aktiv, werden Vorschau/Teaser nicht stumm geschaltet."}),g.jsx(bo,{checked:!!e.enableNotifications,onChange:K=>t(q=>({...q,enableNotifications:K})),label:"Benachrichtigungen",description:"Wenn aktiv, zeigt das Frontend Toasts (z.B. wenn watched Models online/live gehen oder wenn ein queued Model wieder public wird)."}),g.jsxs("div",{className:"rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Speicherplatz-Notbremse"}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:"Aktiviert automatisch Stop + Autostart-Block bei wenig freiem Speicher (Resume bei +3 GB)."})]}),g.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium "+(v?.emergency?"bg-red-100 text-red-800 dark:bg-red-500/20 dark:text-red-200":"bg-green-100 text-green-800 dark:bg-green-500/20 dark:text-green-200"),title:v?.emergency?"Notfallbremse greift gerade":"OK",children:v?.emergency?"AKTIV":"OK"})]}),g.jsxs("div",{className:"mt-3 text-sm text-gray-900 dark:text-gray-200",children:[g.jsxs("div",{children:[g.jsx("span",{className:"font-medium",children:"Schwelle:"})," ","Pause unter ",g.jsx("span",{className:"tabular-nums",children:F})," GB"," · ","Resume ab"," ",g.jsx("span",{className:"tabular-nums",children:$})," ","GB"]}),g.jsx("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:v?`Frei: ${v.freeBytesHuman}${v.recordPath?` (Pfad: ${v.recordPath})`:""}`:"Status wird geladen…"}),v?.emergency&&g.jsx("div",{className:"mt-2 text-xs text-red-700 dark:text-red-200",children:"Notfallbremse greift: laufende Downloads werden gestoppt und Autostart bleibt gesperrt, bis wieder genug frei ist."})]})]})]})]})]})})}function Iy(...s){return s.filter(Boolean).join(" ")}const SO={sm:{btn:"px-2.5 py-1.5 text-sm",icon:"size-5",iconOnly:"h-9 w-9"},md:{btn:"px-3 py-2 text-sm",icon:"size-5",iconOnly:"h-10 w-10"}};function _O({items:s,value:e,onChange:t,size:i="md",className:n,ariaLabel:r="Optionen"}){const a=SO[i];return g.jsx("span",{className:Iy("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,y=!u.label&&!!u.icon;return g.jsxs("button",{type:"button",disabled:u.disabled,onClick:()=>t(u.id),"aria-pressed":d,className:Iy("relative inline-flex items-center justify-center font-semibold leading-none 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",y?`p-0 ${a.iconOnly}`:a.btn),title:typeof u.label=="string"?u.label:u.srLabel,children:[y&&u.srLabel?g.jsx("span",{className:"sr-only",children:u.srLabel}):null,u.icon?g.jsx("span",{className:Iy("shrink-0",y?"":"-ml-0.5",d?"text-indigo-600 dark:text-indigo-200":"text-gray-400 dark:text-gray-500"),children:u.icon}):null,u.label?g.jsx("span",{className:u.icon?"ml-1.5":"",children:u.label}):null]},u.id)})})}function EO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 wO=_.forwardRef(EO);function AO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"}))}const W_=_.forwardRef(AO);function kO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"}))}const CO=_.forwardRef(kO);function DO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Tm=_.forwardRef(DO);function LO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 RO=_.forwardRef(LO);function IO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 NO=_.forwardRef(IO);function OO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 ux=_.forwardRef(OO);function MO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Sm=_.forwardRef(MO);function PO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 BO=_.forwardRef(PO);function FO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}))}const Y_=_.forwardRef(FO);function UO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 jO=_.forwardRef(UO);function $O({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 HO=_.forwardRef($O);function zO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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"}),_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}))}const f0=_.forwardRef(zO);function GO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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.5h1.5C5.496 19.5 6 18.996 6 18.375m-3.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-1.5A1.125 1.125 0 0 1 18 18.375M20.625 4.5H3.375m17.25 0c.621 0 1.125.504 1.125 1.125M20.625 4.5h-1.5C18.504 4.5 18 5.004 18 5.625m3.75 0v1.5c0 .621-.504 1.125-1.125 1.125M3.375 4.5c-.621 0-1.125.504-1.125 1.125M3.375 4.5h1.5C5.496 4.5 6 5.004 6 5.625m-3.75 0v1.5c0 .621.504 1.125 1.125 1.125m0 0h1.5m-1.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125m1.5-3.75C5.496 8.25 6 7.746 6 7.125v-1.5M4.875 8.25C5.496 8.25 6 8.754 6 9.375v1.5m0-5.25v5.25m0-5.25C6 5.004 6.504 4.5 7.125 4.5h9.75c.621 0 1.125.504 1.125 1.125m1.125 2.625h1.5m-1.5 0A1.125 1.125 0 0 1 18 7.125v-1.5m1.125 2.625c-.621 0-1.125.504-1.125 1.125v1.5m2.625-2.625c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125M18 5.625v5.25M7.125 12h9.75m-9.75 0A1.125 1.125 0 0 1 6 10.875M7.125 12C6.504 12 6 12.504 6 13.125m0-2.25C6 11.496 5.496 12 4.875 12M18 10.875c0 .621-.504 1.125-1.125 1.125M18 10.875c0 .621.504 1.125 1.125 1.125m-2.25 0c.621 0 1.125.504 1.125 1.125m-12 5.25v-5.25m0 5.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125m-12 0v-1.5c0-.621-.504-1.125-1.125-1.125M18 18.375v-5.25m0 5.25v-1.5c0-.621.504-1.125 1.125-1.125M18 13.125v1.5c0 .621.504 1.125 1.125 1.125M18 13.125c0-.621.504-1.125 1.125-1.125M6 13.125v1.5c0 .621-.504 1.125-1.125 1.125M6 13.125C6 12.504 5.496 12 4.875 12m-1.5 0h1.5m-1.5 0c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125M19.125 12h1.5m0 0c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125m-17.25 0h1.5m14.25 0h1.5"}))}const VO=_.forwardRef(GO);function qO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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"}),_.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 X_=_.forwardRef(qO);function KO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Th=_.forwardRef(KO);function WO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 YO=_.forwardRef(WO);function XO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 QO=_.forwardRef(XO);function ZO({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 JO=_.forwardRef(ZO);function eM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 tM=_.forwardRef(eM);function iM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Q_=_.forwardRef(iM);function sM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"}),_.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 nM=_.forwardRef(sM);function rM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Z_=_.forwardRef(rM);function aM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 oM=_.forwardRef(aM);function lM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Ny=_.forwardRef(lM);function uM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 cM=_.forwardRef(uM);function dM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 m0=_.forwardRef(dM);function hM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 fM=_.forwardRef(hM);function mM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 cx=_.forwardRef(mM);function pM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 J_=_.forwardRef(pM);function gM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 yM=_.forwardRef(gM);function vM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18 18 6M6 6l12 12"}))}const p0=_.forwardRef(vM);function xM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{fillRule:"evenodd",d:"M19.916 4.626a.75.75 0 0 1 .208 1.04l-9 13.5a.75.75 0 0 1-1.154.114l-6-6a.75.75 0 0 1 1.06-1.06l5.353 5.353 8.493-12.74a.75.75 0 0 1 1.04-.207Z",clipRule:"evenodd"}))}const bM=_.forwardRef(xM);function TM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.createElement("path",{d:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"}),_.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 _u=_.forwardRef(TM);function SM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 dx=_.forwardRef(SM);function _M({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 EM=_.forwardRef(_M);function wM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Eu=_.forwardRef(wM);function AM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 kM=_.forwardRef(AM);function CM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 DM=_.forwardRef(CM);function LM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 RM=_.forwardRef(LM);function IM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 Pc=_.forwardRef(IM);function Oy(...s){return s.filter(Boolean).join(" ")}function NM(){if(typeof document>"u")return null;const s="__swipecard_hot_fx_layer__";let e=document.getElementById(s);return e||(e=document.createElement("div"),e.id=s,e.style.position="fixed",e.style.inset="0",e.style.pointerEvents="none",e.style.zIndex="2147483647",e.style.contain="layout style paint",document.body.appendChild(e)),e}const OM=_.forwardRef(function({children:e,enabled:t=!0,disabled:i=!1,onTap:n,onSwipeLeft:r,onSwipeRight:a,className:u,leftAction:c={label:g.jsxs("span",{className:"inline-flex items-center gap-2 font-semibold",children:[g.jsx(ux,{className:"h-6 w-6"}),g.jsx("span",{className:"hidden sm:inline",children:"Behalten"})]}),className:"bg-emerald-500/20 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-300"},rightAction:d={label:g.jsxs("span",{className:"inline-flex flex-col items-center gap-1 font-semibold leading-tight",children:[g.jsx(cx,{className:"h-6 w-6","aria-hidden":"true"}),g.jsx("span",{children:"Löschen"})]}),className:"bg-red-500/20 text-red-800 dark:bg-red-500/15 dark:text-red-300"},thresholdPx:f=140,thresholdRatio:p=.28,ignoreFromBottomPx:y=72,ignoreSelector:v="[data-swipe-ignore]",snapMs:b=180,commitMs:S=180,tapIgnoreSelector:E="button,a,input,textarea,select,video[controls],video[controls] *,[data-tap-ignore]",onDoubleTap:L,hotTargetSelector:N="[data-hot-target]",doubleTapMs:R=360,doubleTapMaxMovePx:H=48},F){const $=_.useRef(null),M=_.useRef(!1),W=_.useRef(0),D=_.useRef(null),I=_.useRef(0),Q=_.useRef(null),K=_.useRef(null),q=_.useRef(null),le=_.useRef({id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1,noSwipe:!1}),[te,V]=_.useState(0),[G,J]=_.useState(null),[ie,oe]=_.useState(0),j=_.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),W.current=0,$.current&&($.current.style.touchAction="pan-y"),oe(b),V(0),J(null),window.setTimeout(()=>oe(0),b)},[b]),X=_.useCallback(async(de,Ve)=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),$.current&&($.current.style.touchAction="pan-y");const Je=$.current?.offsetWidth||360;oe(S),J(de==="right"?"right":"left");const Pe=de==="right"?Je+40:-(Je+40);W.current=Pe,V(Pe);let Fe=!0;if(Ve)try{Fe=de==="right"?await a():await r()}catch{Fe=!1}return Fe===!1?(oe(b),J(null),V(0),window.setTimeout(()=>oe(0),b),!1):!0},[S,r,a,b]),se=_.useCallback(()=>{K.current!=null&&(window.clearTimeout(K.current),K.current=null)},[]),fe=_.useCallback(()=>{D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),W.current=0,oe(0),V(0),J(null);try{const de=$.current;de&&(de.style.touchAction="pan-y")}catch{}},[]),pe=_.useCallback((de,Ve)=>{const Ze=Q.current,Je=$.current;if(!Ze||!Je)return;const Pe=NM();if(!Pe)return;let Fe=typeof de=="number"?de:window.innerWidth/2,qe=typeof Ve=="number"?Ve:window.innerHeight/2;const dt=N?Q.current?.querySelector(N)??Je.querySelector(N):null;let Ge=Fe,At=qe;if(dt){const Pt=dt.getBoundingClientRect();Ge=Pt.left+Pt.width/2,At=Pt.top+Pt.height/2}const lt=Ge-Fe,bt=At-qe,nt=document.createElement("div");nt.style.position="absolute",nt.style.left=`${Fe}px`,nt.style.top=`${qe}px`,nt.style.transform="translate(-50%, -50%)",nt.style.pointerEvents="none",nt.style.willChange="transform, opacity",nt.style.zIndex="2147483647",nt.style.lineHeight="1",nt.style.userSelect="none",nt.style.filter="drop-shadow(0 10px 16px rgba(0,0,0,0.22))";const wt=document.createElement("div");wt.style.width="30px",wt.style.height="30px",wt.style.color="#f59e0b",wt.style.display="block",nt.appendChild(wt),Pe.appendChild(nt);const ht=pA.createRoot(wt);ht.render(g.jsx(dx,{className:"w-full h-full","aria-hidden":"true"})),nt.getBoundingClientRect();const Et=200,ye=500,mt=400,st=Et+ye+mt,Xe=Et/st,xt=(Et+ye)/st,ft=nt.animate([{transform:"translate(-50%, -50%) scale(0.15)",opacity:0,offset:0},{transform:"translate(-50%, -50%) scale(1.25)",opacity:1,offset:Xe*.55},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:Xe},{transform:"translate(-50%, -50%) scale(1.00)",opacity:1,offset:xt},{transform:`translate(calc(-50% + ${lt}px), calc(-50% + ${bt}px)) scale(0.85)`,opacity:.95,offset:xt+(1-xt)*.75},{transform:`translate(calc(-50% + ${lt}px), calc(-50% + ${bt}px)) scale(0.55)`,opacity:0,offset:1}],{duration:st,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)",fill:"forwards"});dt&&window.setTimeout(()=>{try{dt.animate([{transform:"translateZ(0) scale(1)",filter:"brightness(1)"},{transform:"translateZ(0) scale(1.10)",filter:"brightness(1.25)",offset:.35},{transform:"translateZ(0) scale(1)",filter:"brightness(1)"}],{duration:260,easing:"cubic-bezier(0.2, 0.9, 0.2, 1)"})}catch{}},Et+ye+Math.round(mt*.75)),ft.onfinish=()=>{try{ht.unmount()}catch{}nt.remove()}},[N]);return _.useEffect(()=>()=>{K.current!=null&&window.clearTimeout(K.current)},[]),_.useImperativeHandle(F,()=>({swipeLeft:de=>X("left",de?.runAction??!0),swipeRight:de=>X("right",de?.runAction??!0),reset:()=>j()}),[X,j]),g.jsxs("div",{ref:Q,className:Oy("relative isolate overflow-hidden rounded-lg",u),children:[g.jsxs("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-lg",children:[g.jsx("div",{className:Oy("absolute inset-0 transition-opacity duration-200 ease-out",te===0?"opacity-0":"opacity-100",te>0?c.className:d.className)}),g.jsx("div",{className:"absolute inset-0 flex items-center",style:{opacity:te===0?0:1,justifyContent:te>0?"flex-start":"flex-end",paddingLeft:te>0?16:0,paddingRight:te>0?0:16},children:g.jsx("div",{style:{transform:G?"scale(1.05)":"scale(1)",transition:"transform 180ms ease, opacity 180ms ease",opacity:G?1:.9},children:te>0?c.label:d.label})})]}),g.jsx("div",{ref:$,className:"relative",style:{transform:te!==0?`translate3d(${te}px,0,0)`:void 0,transition:ie?`transform ${ie}ms ease`:void 0,touchAction:"pan-y",willChange:te!==0?"transform":void 0,boxShadow:te!==0?"0 10px 24px rgba(0,0,0,0.18)":void 0,borderRadius:te!==0?"12px":void 0},onPointerDown:de=>{if(!t||i)return;const Ve=de.target;let Ze=!!(E&&Ve?.closest?.(E));if(v&&Ve?.closest?.(v))return;let Je=!1;const Pe=de.currentTarget,qe=Array.from(Pe.querySelectorAll("video")).find(bt=>bt.controls);if(qe){const bt=qe.getBoundingClientRect();if(de.clientX>=bt.left&&de.clientX<=bt.right&&de.clientY>=bt.top&&de.clientY<=bt.bottom)if(bt.bottom-de.clientY<=72)Je=!0,Ze=!0;else{const ye=de.clientX-bt.left,mt=bt.right-de.clientX;ye<=64||mt<=64||(Je=!0,Ze=!0)}}const Ge=de.currentTarget.getBoundingClientRect().bottom-de.clientY;y&&Ge<=y&&(Je=!0),le.current={id:de.pointerId,x:de.clientX,y:de.clientY,dragging:!1,captured:!1,tapIgnored:Ze,noSwipe:Je};const lt=$.current?.offsetWidth||360;I.current=Math.min(f,lt*p),W.current=0},onPointerMove:de=>{if(!t||i||le.current.id!==de.pointerId||le.current.noSwipe)return;const Ve=de.clientX-le.current.x,Ze=de.clientY-le.current.y;if(!le.current.dragging){if(Math.abs(Ze)>Math.abs(Ve)&&Math.abs(Ze)>8){le.current.id=null;return}if(Math.abs(Ve)<12)return;le.current.dragging=!0,de.currentTarget.style.touchAction="none",oe(0);try{de.currentTarget.setPointerCapture(de.pointerId),le.current.captured=!0}catch{le.current.captured=!1}}const Je=(dt,Ge)=>{const At=Ge*.9,lt=Math.abs(dt);if(lt<=At)return dt;const bt=lt-At,nt=At+bt*.25;return Math.sign(dt)*nt},Pe=$.current?.offsetWidth||360;W.current=Je(Ve,Pe),D.current==null&&(D.current=requestAnimationFrame(()=>{D.current=null,V(W.current)}));const Fe=I.current,qe=Ve>Fe?"right":Ve<-Fe?"left":null;J(dt=>{if(dt===qe)return dt;if(qe)try{navigator.vibrate?.(10)}catch{}return qe})},onPointerUp:de=>{if(!t||i||le.current.id!==de.pointerId)return;const Ve=I.current||Math.min(f,($.current?.offsetWidth||360)*p),Ze=le.current.dragging,Je=le.current.captured,Pe=le.current.tapIgnored;if(le.current.id=null,le.current.dragging=!1,le.current.captured=!1,Je)try{de.currentTarget.releasePointerCapture(de.pointerId)}catch{}if(de.currentTarget.style.touchAction="pan-y",!Ze){const qe=Date.now(),dt=q.current,Ge=dt&&Math.hypot(de.clientX-dt.x,de.clientY-dt.y)<=H;if(!!L&&dt&&qe-dt.t<=R&&Ge){if(q.current=null,se(),M.current)return;M.current=!0;try{pe(de.clientX,de.clientY)}catch{}requestAnimationFrame(()=>{(async()=>{try{await L?.()}finally{M.current=!1}})()});return}if(Pe){q.current={t:qe,x:de.clientX,y:de.clientY},se(),K.current=window.setTimeout(()=>{K.current=null,q.current=null},L?R:0);return}fe(),q.current={t:qe,x:de.clientX,y:de.clientY},se(),K.current=window.setTimeout(()=>{K.current=null,q.current=null,n?.()},L?R:0);return}const Fe=W.current;D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),Fe>Ve?X("right",!0):Fe<-Ve?X("left",!0):j(),W.current=0},onPointerCancel:de=>{if(!(!t||i)){if(le.current.captured&&le.current.id!=null)try{de.currentTarget.releasePointerCapture(le.current.id)}catch{}le.current={id:null,x:0,y:0,dragging:!1,captured:!1,tapIgnored:!1,noSwipe:!1},D.current!=null&&(cancelAnimationFrame(D.current),D.current=null),W.current=0;try{de.currentTarget.style.touchAction="pan-y"}catch{}j()}},children:g.jsxs("div",{className:"relative",children:[g.jsx("div",{className:"relative z-10",children:e}),g.jsx("div",{className:Oy("absolute inset-0 z-20 pointer-events-none transition-opacity duration-150 rounded-lg",G==="right"&&"bg-emerald-500/20 opacity-100",G==="left"&&"bg-red-500/20 opacity-100",G===null&&"opacity-0")})]})})]})});function KA({children:s,content:e}){const t=_.useRef(null),i=_.useRef(null),[n,r]=_.useState(!1),[a,u]=_.useState(null),c=_.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)},y=()=>{f()},v=()=>{d(),r(!1)},b=()=>{const E=t.current,L=i.current;if(!E||!L)return;const N=8,R=8,H=E.getBoundingClientRect(),F=L.getBoundingClientRect();let $=H.bottom+N;if($+F.height>window.innerHeight-R){const D=H.top-F.height-N;D>=R?$=D:$=Math.max(R,window.innerHeight-F.height-R)}let W=H.left;W+F.width>window.innerWidth-R&&(W=window.innerWidth-F.width-R),W=Math.max(R,W),u({left:W,top:$})};_.useLayoutEffect(()=>{if(!n)return;const E=requestAnimationFrame(()=>b());return()=>cancelAnimationFrame(E)},[n]),_.useEffect(()=>{if(!n)return;const E=()=>requestAnimationFrame(()=>b());return window.addEventListener("resize",E),window.addEventListener("scroll",E,!0),()=>{window.removeEventListener("resize",E),window.removeEventListener("scroll",E,!0)}},[n]),_.useEffect(()=>()=>d(),[]);const S=()=>typeof e=="function"?e(n,{close:v}):e;return g.jsxs(g.Fragment,{children:[g.jsx("div",{ref:t,className:"inline-flex",onMouseEnter:p,onMouseLeave:y,children:s}),n&&Oc.createPortal(g.jsx("div",{ref:i,className:"fixed z-50",style:{left:a?.left??-9999,top:a?.top??-9999,visibility:a?"visible":"hidden"},onMouseEnter:p,onMouseLeave:y,children:g.jsx(fa,{className:"shadow-lg ring-1 ring-black/10 dark:ring-white/10 max-w-[calc(100vw-16px)]",noBodyPadding:!0,children:S()})}),document.body)]})}const g0=!0,MM=!1;function y0(s,e){if(!s)return;const t=e?.muted??g0;s.muted=t,s.defaultMuted=t,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline","")}function hb({job:s,getFileName:e,durationSeconds:t,onDuration:i,onResolution:n,animated:r=!1,animatedMode:a="frames",animatedTrigger:u="always",autoTickMs:c=15e3,thumbStepSec:d,thumbSpread:f,thumbSamples:p,clipSeconds:y=1,variant:v="thumb",className:b,showPopover:S=!0,blur:E=!1,inlineVideo:L=!1,inlineNonce:N=0,inlineControls:R=!1,inlineLoop:H=!0,assetNonce:F=0,muted:$=g0,popoverMuted:M=g0,noGenerateTeaser:W}){const D=e(s.output||""),I=E?"blur-md":"",Q=_.useMemo(()=>{const je=s?.meta;if(!je)return null;if(typeof je=="string")try{return JSON.parse(je)}catch{return null}return je},[s]),[K,q]=_.useState(null),le=Q??K,[te,V]=_.useState(0),G=_.useMemo(()=>{let je=le?.previewClips;if(typeof je=="string")try{je=JSON.parse(je)}catch{je=null}!Array.isArray(je)&&Array.isArray(le?.preview?.clips)&&(je=le.preview.clips);const gt=je;if(!Array.isArray(gt)||gt.length===0)return null;let Ct=0;const Vt=[];for(const Bt of gt){const mi=Number(Bt?.startSeconds),Ut=Number(Bt?.durationSeconds);if(!Number.isFinite(mi)||mi<0||!Number.isFinite(Ut)||Ut<=0)continue;const zi=Ct,Si=Ct+Ut;Vt.push({start:mi,dur:Ut,cumStart:zi,cumEnd:Si}),Ct=Si}return Vt.length?Vt:null},[le]),J=_.useMemo(()=>G?G.map(je=>`${je.start.toFixed(3)}:${je.dur.toFixed(3)}`).join("|"):"",[G]),ie=(typeof Q?.videoWidth=="number"&&Number.isFinite(Q.videoWidth)&&Q.videoWidth>0?Q.videoWidth:void 0)??(typeof s.videoWidth=="number"&&Number.isFinite(s.videoWidth)&&s.videoWidth>0?s.videoWidth:void 0),oe=(typeof Q?.videoHeight=="number"&&Number.isFinite(Q.videoHeight)&&Q.videoHeight>0?Q.videoHeight:void 0)??(typeof s.videoHeight=="number"&&Number.isFinite(s.videoHeight)&&s.videoHeight>0?s.videoHeight:void 0),j=(typeof Q?.fileSize=="number"&&Number.isFinite(Q.fileSize)&&Q.fileSize>0?Q.fileSize:void 0)??(typeof s.sizeBytes=="number"&&Number.isFinite(s.sizeBytes)&&s.sizeBytes>0?s.sizeBytes:void 0),X=(typeof Q?.fps=="number"&&Number.isFinite(Q.fps)&&Q.fps>0?Q.fps:void 0)??(typeof s.fps=="number"&&Number.isFinite(s.fps)&&s.fps>0?s.fps:void 0),se=(typeof le?.durationSeconds=="number"&&Number.isFinite(le.durationSeconds)&&le.durationSeconds>0?le.durationSeconds:void 0)??(typeof s.durationSeconds=="number"&&Number.isFinite(s.durationSeconds)&&s.durationSeconds>0?s.durationSeconds:void 0)??(typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0),fe=typeof se=="number"&&Number.isFinite(se)&&se>0?se>1440*60?se/1e3:se:void 0,pe=typeof fe=="number"&&Number.isFinite(fe)&&fe>0,de=typeof ie=="number"&&typeof oe=="number"&&Number.isFinite(ie)&&Number.isFinite(oe)&&ie>0&&oe>0,Ve={muted:$,playsInline:!0,preload:"metadata"},[Ze,Je]=_.useState(!0),[Pe,Fe]=_.useState(!0),[qe,dt]=_.useState(!1),[Ge,At]=_.useState(!1),[lt,bt]=_.useState(!0),nt=_.useRef(null),[wt,ht]=_.useState(!1),[,Et]=_.useState(!1),[ye,mt]=_.useState(0),[st,Xe]=_.useState(!1),xt=L===!0||L==="always"?"always":L==="hover"?"hover":"never",ft=xt==="hover"||r&&(a==="clips"||a==="teaser")&&u==="hover",Pt=je=>je.startsWith("HOT ")?je.slice(4):je,qt=_.useMemo(()=>{const je=e(s.output||"");if(!je)return"";const gt=je.replace(/\.[^.]+$/,"");return Pt(gt).trim()},[s.output,e]);_.useEffect(()=>{if(!qt||!r||a!=="teaser"||!(wt||ft&&st))return;const je=Q?.previewClips;if(Array.isArray(je)||typeof je=="string"&&je.length>0||Array.isArray(Q?.preview?.clips))return;let Ct=!1;const Vt=new AbortController,Bt=async mi=>{try{const Ut=await fetch(mi,{signal:Vt.signal,cache:"no-store",credentials:"include"});return Ut.ok?await Ut.json():null}catch{return null}};return(async()=>{const mi=await Bt(`/api/record/done/meta?id=${encodeURIComponent(qt)}`),Ut=D?await Bt(`/api/record/done/meta?file=${encodeURIComponent(D)}`):null,zi=mi??Ut;!Ct&&zi&&q(zi)})(),()=>{Ct=!0,Vt.abort()}},[qt,D,r,a,Q,wt,ft,st]);const It=_.useMemo(()=>D?`/api/record/video?file=${encodeURIComponent(D)}`:"",[D]),ni=v==="fill"?"w-full h-full":"w-20 h-16",Gt=_.useRef(null),yi=_.useRef(null),Zt=_.useRef(null),Jt=_.useRef({inline:null,teaser:null,clips:null}),di=(je,gt)=>{gt&&Jt.current[je]!==gt&&(Jt.current[je]=gt,V(Ct=>Ct+1))},[Zi,Di]=_.useState(0),[,Mi]=_.useState(0),Ki=je=>je<0?0:je>1?1:je,As=(je,gt,Ct=1,Vt=!1)=>{if(!je)return{ratio:0,globalSec:0,vvDur:0};const Bt=Number(je.duration);if(!(Number.isFinite(Bt)&&Bt>0))return{ratio:0,globalSec:0,vvDur:0};const Ut=Number(je.currentTime);if(!Number.isFinite(Ut)||Ut<0)return{ratio:0,globalSec:0,vvDur:Bt};let zi=0;const Si=G;if(Vt&&Array.isArray(Si)&&Si.length>0){const Ys=Si[Si.length-1];if(Ut>=Ys.cumEnd)zi=typeof gt=="number"&&Number.isFinite(gt)&>>0?gt:Ys.start+Ys.dur;else{let En=0,as=Si.length-1,Cs=Si[0];for(;En<=as;){const Wi=En+as>>1,Yi=Si[Wi];if(Ut=Yi.cumEnd)En=Wi+1;else{Cs=Yi;break}}const Mn=Math.max(0,Ut-Cs.cumStart),hs=Math.floor(Mn/Ct)*Ct;zi=Cs.start+Math.min(hs,Cs.dur)}}else zi=Math.floor(Ut/Ct)*Ct;const Ss=Math.max(0,Math.min(zi,Bt));return{ratio:Ki(Ss/Bt),globalSec:Ss,vvDur:Bt}},xe=je=>{if(je){try{je.pause()}catch{}try{je.removeAttribute("src"),je.src="",je.load()}catch{}}};_.useEffect(()=>{At(!1),bt(!0)},[qt,F,W]),_.useEffect(()=>{const je=gt=>{const Ct=String(gt?.detail?.file??"");!Ct||Ct!==D||(xe(Gt.current),xe(yi.current),xe(Zt.current))};return window.addEventListener("player:release",je),window.addEventListener("player:close",je),()=>{window.removeEventListener("player:release",je),window.removeEventListener("player:close",je)}},[D]),_.useEffect(()=>{const je=nt.current;if(!je)return;const gt=new IntersectionObserver(Ct=>{const Vt=!!Ct[0]?.isIntersecting;ht(Vt),Vt&&Et(!0)},{threshold:.01,rootMargin:"120px 0px"});return gt.observe(je),()=>gt.disconnect()},[]),_.useEffect(()=>{if(!r||a!=="frames"||!wt||document.hidden)return;const je=window.setInterval(()=>mt(gt=>gt+1),c);return()=>window.clearInterval(je)},[r,a,wt,c]);const B=_.useMemo(()=>{if(!r||a!=="frames"||!pe)return null;const je=fe,gt=Math.max(.25,d??3);if(f){const Bt=Math.max(4,Math.min(p??16,Math.floor(je))),mi=ye%Bt,Ut=Math.max(.1,je-gt),zi=Math.min(.25,Ut*.02),Si=mi/Bt*Ut+zi;return Math.min(je-.05,Math.max(.05,Si))}const Ct=Math.max(je-.1,gt),Vt=ye*gt%Ct;return Math.min(je-.05,Math.max(.05,Vt))},[r,a,pe,fe,ye,d,f,p]),Z=F??0,re=_.useMemo(()=>qt?B==null?`/api/record/preview?id=${encodeURIComponent(qt)}&v=${Z}`:`/api/record/preview?id=${encodeURIComponent(qt)}&t=${B}&v=${Z}`:"",[qt,B,Z]),Te=_.useMemo(()=>{if(!qt)return"";const je=W?"&noGenerate=1":"";return`/api/generated/teaser?id=${encodeURIComponent(qt)}${je}&v=${Z}`},[qt,Z,W]);_.useEffect(()=>{let je=!1;i&&pe&&(i(s,Number(fe)),je=!0),n&&de&&(n(s,Number(ie),Number(oe)),je=!0),je&&dt(!0)},[s,i,n,pe,de,fe,ie,oe]);const Ke=je=>{dt(!0);const gt=je.currentTarget;if(i&&!pe){const Ct=Number(gt.duration);Number.isFinite(Ct)&&Ct>0&&i(s,Ct)}if(n&&!de){const Ct=Number(gt.videoWidth),Vt=Number(gt.videoHeight);Number.isFinite(Ct)&&Number.isFinite(Vt)&&Ct>0&&Vt>0&&n(s,Ct,Vt)}};if(_.useEffect(()=>{Je(!0),Fe(!0),Jt.current.inline=null,Jt.current.teaser=null,Jt.current.clips=null},[qt,F]),!It)return g.jsx("div",{className:[ni,"rounded bg-gray-100 dark:bg-white/5"].join(" ")});const vt=xt!=="never"&&wt&&Pe&&(xt==="always"||xt==="hover"&&st),Tt=r&&wt&&!document.hidden&&Pe&&!vt&&(u==="always"||st)&&(a==="teaser"&<&&!!Te||a==="clips"&&pe),Li=pe?fe:void 0,bi=wt||ft&&st,ji=vt?Gt:!vt&&Tt&&a==="teaser"?yi:!vt&&Tt&&a==="clips"?Zt:null,ai=!!ji&&wt&&typeof Li=="number"&&Number.isFinite(Li)&&Li>0,Fi=vt?"inline":Tt&&a==="teaser"?"teaser":"clips",li=r&&a==="frames"&&pe&&typeof B=="number"&&Number.isFinite(B)&&B>=0,$s=li?Ki(B/fe):0,$i=ai?Zi:li?$s:0,Hi=ai||li,ii=_.useMemo(()=>{if(!pe)return null;const je=fe;if(!(je>0))return null;let Ct=le?.previewClips;if(typeof Ct=="string")try{Ct=JSON.parse(Ct)}catch{Ct=null}if(!Array.isArray(Ct)||Ct.length===0)return null;const Vt=Ct.map(Bt=>({start:Number(Bt?.startSeconds),dur:Number(Bt?.durationSeconds)})).filter(Bt=>Number.isFinite(Bt.start)&&Bt.start>=0&&Number.isFinite(Bt.dur)&&Bt.dur>0);return Vt.length?Vt.map(Bt=>{const mi=Ki(Bt.start/je),Ut=Ki(Bt.dur/je);return{left:mi,width:Ut,start:Bt.start,dur:Bt.dur}}):null},[le,pe,fe]),Ht=_.useMemo(()=>{if(!r)return[];if(a!=="clips")return[];if(!pe)return[];const je=fe,gt=Math.max(.25,y),Ct=Math.max(8,Math.min(p??18,Math.floor(je))),Vt=Math.max(.1,je-gt),Bt=Math.min(.25,Vt*.02),mi=[];for(let Ut=0;UtHt.map(je=>je.toFixed(2)).join(","),[Ht]),Ui=_.useRef(0),rs=_.useRef(0);_.useEffect(()=>{const je=yi.current;if(!je)return;if(!(Tt&&a==="teaser")){try{je.pause()}catch{}return}y0(je,{muted:$});const Ct=je.play?.();Ct&&typeof Ct.catch=="function"&&Ct.catch(()=>{})},[Tt,a,Te,$]),_.useEffect(()=>{if(!ai){Di(0),Mi(0);return}const je=ji?.current??null;if(!je){Di(0),Mi(0);return}let gt=!1,Ct=null;const Vt=()=>{if(gt||!je.isConnected)return;const Ut=Fi==="teaser"&&Array.isArray(G)&&G.length>0,zi=As(je,Li,1,Ut);Di(zi.ratio),Mi(zi.globalSec)};Vt(),Ct=window.setInterval(Vt,1e3);const Bt=()=>Vt(),mi=()=>Vt();return je.addEventListener("loadedmetadata",Bt),je.addEventListener("durationchange",Bt),je.addEventListener("timeupdate",mi),()=>{gt=!0,Ct!=null&&window.clearInterval(Ct),je.removeEventListener("loadedmetadata",Bt),je.removeEventListener("durationchange",Bt),je.removeEventListener("timeupdate",mi)}},[ai,ji,Li,J,Fi,G,te]),_.useEffect(()=>{vt&&y0(Gt.current,{muted:$})},[vt,$]),_.useEffect(()=>{const je=Zt.current;if(!je)return;if(!(Tt&&a==="clips")){Tt||je.pause();return}if(!Ht.length)return;Ui.current=Ui.current%Ht.length,rs.current=Ht[Ui.current];const gt=()=>{try{je.currentTime=rs.current}catch{}const Bt=je.play();Bt&&typeof Bt.catch=="function"&&Bt.catch(()=>{})},Ct=()=>gt(),Vt=()=>{if(Ht.length&&je.currentTime-rs.current>=y){Ui.current=(Ui.current+1)%Ht.length,rs.current=Ht[Ui.current];try{je.currentTime=rs.current+.01}catch{}}};return je.addEventListener("loadedmetadata",Ct),je.addEventListener("timeupdate",Vt),je.readyState>=1&>(),()=>{je.removeEventListener("loadedmetadata",Ct),je.removeEventListener("timeupdate",Vt),je.pause()}},[Tt,a,Kt,y,Ht]);const mn=wt&&(i||n)&&!qe&&!vt&&(i&&!pe||n&&!de),_n=g.jsxs("div",{ref:nt,className:["group rounded bg-gray-100 dark:bg-white/5 overflow-hidden relative isolate",ni,b??""].join(" "),onMouseEnter:ft?()=>Xe(!0):void 0,onMouseLeave:ft?()=>Xe(!1):void 0,onFocus:ft?()=>Xe(!0):void 0,onBlur:ft?()=>Xe(!1):void 0,"data-duration":pe?String(fe):void 0,"data-res":de?`${ie}x${oe}`:void 0,"data-size":typeof j=="number"?String(j):void 0,"data-fps":typeof X=="number"?String(X):void 0,children:[bi&&re&&Ze?g.jsx("img",{src:re,loading:"lazy",decoding:"async",alt:D,className:["absolute inset-0 w-full h-full object-cover",I].filter(Boolean).join(" "),onError:()=>Je(!1)}):g.jsx("div",{className:"absolute inset-0 bg-black/10 dark:bg-white/10"}),vt?_.createElement("video",{...Ve,ref:je=>{Gt.current=je,di("inline",je)},key:`inline-${qt}-${N}`,src:It,className:["absolute inset-0 w-full h-full object-cover",I,R?"pointer-events-auto":"pointer-events-none"].filter(Boolean).join(" "),autoPlay:!0,muted:$,controls:R,loop:H,poster:bi&&re||void 0,onLoadedMetadata:Ke,onError:()=>Fe(!1)}):null,!vt&&Tt&&a==="teaser"?g.jsx("video",{ref:je=>{yi.current=je,di("teaser",je)},src:Te,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",I,Ge?"opacity-100":"opacity-0","transition-opacity duration-150"].filter(Boolean).join(" "),muted:$,playsInline:!0,autoPlay:!0,loop:!0,preload:"metadata",poster:bi&&re||void 0,onLoadedData:()=>At(!0),onPlaying:()=>At(!0),onError:()=>{bt(!1),At(!1)}},`teaser-mp4-${qt}`):null,!vt&&Tt&&a==="clips"?g.jsx("video",{ref:je=>{Zt.current=je,di("clips",je)},src:It,className:["absolute inset-0 w-full h-full object-cover pointer-events-none",I].filter(Boolean).join(" "),muted:$,playsInline:!0,preload:"metadata",poster:bi&&re||void 0,onError:()=>Fe(!1)},`clips-${qt}-${Kt}`):null,Hi?g.jsxs("div",{"aria-hidden":"true",className:["absolute left-0 right-0 bottom-0 z-10 pointer-events-none","h-0.5 group-hover:h-1.5","transition-[height] duration-150 ease-out","rounded-none group-hover:rounded-full","bg-black/35 dark:bg-white/10","overflow-hidden group-hover:overflow-visible"].join(" "),children:[Fi==="teaser"&&ii?g.jsx("div",{className:"absolute inset-0",children:ii.map((je,gt)=>g.jsx("div",{className:"absolute top-0 bottom-0 bg-white/15 dark:bg-white/20",style:{left:`${je.left*100}%`,width:`${je.width*100}%`}},`seg-${gt}-${je.left.toFixed(6)}-${je.width.toFixed(6)}`))}):null,g.jsx("div",{className:"absolute inset-0 origin-left transition-transform duration-150 ease-out",style:{transform:`scaleX(${Ki($i)})`,background:"rgba(99,102,241,0.95)"}}),g.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity duration-150",style:{left:`calc(${Ki($i)*100}% - 4px)`},children:g.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-white/90 shadow-[0_0_0_2px_rgba(0,0,0,0.25),0_0_10px_rgba(168,85,247,0.55)]"})})]}):null,mn?g.jsx("video",{src:It,preload:"metadata",muted:$,playsInline:!0,className:"hidden",onLoadedMetadata:Ke}):null]});return S?g.jsx(KA,{content:je=>je&&g.jsx("div",{className:"w-[420px]",children:g.jsx("div",{className:"aspect-video",children:g.jsx("video",{src:It,className:["w-full h-full bg-black",I].filter(Boolean).join(" "),muted:M,playsInline:!0,preload:"metadata",controls:!0,autoPlay:!0,loop:!0,onClick:gt=>gt.stopPropagation(),onMouseDown:gt=>gt.stopPropagation()})})}),children:_n}):_n}function ki(...s){return s.filter(Boolean).join(" ")}const PM=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",BM=s=>s.startsWith("HOT ")?s.slice(4):s,FM=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function UM(s){const t=BM(PM(s||"")).replace(/\.[^.]+$/,""),i=t.match(FM);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function za({job:s,variant:e="overlay",collapseToMenu:t=!1,inlineCount:i,busy:n=!1,compact:r=!1,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onToggleFavorite:f,onToggleLike:p,onToggleHot:y,onKeep:v,onDelete:b,onToggleWatch:S,onAddToDownloads:E,order:L,className:N}){const R=e==="overlay"?r?"p-1.5":"p-2":"p-1.5",H=r?"size-4":"size-5",F="h-full w-full",$=e==="table"?`inline-flex items-center justify-center rounded-md ${R} 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 ${R} 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`,M=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"},W=L??["watch","favorite","like","hot","keep","delete","details"],D=xe=>W.includes(xe),I=String(s?.sourceUrl??"").trim(),Q=UM(s.output||""),K=Q?`Mehr zu ${Q} anzeigen`:"Mehr anzeigen",q=D("favorite"),le=D("like"),te=D("hot"),V=D("watch"),G=D("keep"),J=D("delete"),ie=D("details")&&!!Q,oe=D("add"),[j,X]=_.useState("idle"),se=_.useRef(null);_.useEffect(()=>()=>{se.current&&window.clearTimeout(se.current)},[]);const fe=()=>{X("ok"),se.current&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>X("idle"),800)},pe=async()=>{if(n||j==="busy"||!E&&!!!I)return!1;X("busy");try{let B=!0;return E?B=await E(s)!==!1:I?(window.dispatchEvent(new CustomEvent("downloads:add-url",{detail:{url:I}})),B=!0):B=!1,B?fe():X("idle"),B}catch{return X("idle"),!1}},[de,Ve]=_.useState(0),[Ze,Je]=_.useState(4),Pe=xe=>B=>{B.preventDefault(),B.stopPropagation(),!(n||!xe)&&Promise.resolve(xe(s)).catch(()=>{})},Fe=ie?g.jsxs("button",{type:"button",className:ki($),title:K,"aria-label":K,disabled:n,onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),!n&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:Q}}))},children:[g.jsx("span",{className:ki("inline-flex items-center justify-center",H),children:g.jsx(Q_,{className:ki(F,M.off)})}),g.jsx("span",{className:"sr-only",children:K})]}):null,qe=oe?g.jsxs("button",{type:"button",className:ki($),title:I?"URL zu Downloads hinzufügen":"Keine URL vorhanden","aria-label":"Zu Downloads hinzufügen",disabled:n||j==="busy"||!E&&!I,onClick:async xe=>{xe.preventDefault(),xe.stopPropagation(),await pe()},children:[g.jsx("span",{className:ki("inline-flex items-center justify-center",H),children:j==="ok"?g.jsx(bM,{className:ki(F,"text-emerald-600 dark:text-emerald-300")}):g.jsx(W_,{className:ki(F,M.off)})}),g.jsx("span",{className:"sr-only",children:"Zu Downloads"})]}):null,dt=q?g.jsx("button",{type:"button",className:$,title:u?"Favorit entfernen":"Als Favorit markieren","aria-label":u?"Favorit entfernen":"Als Favorit markieren","aria-pressed":u,disabled:n||!f,onClick:Pe(f),children:g.jsxs("span",{className:ki("relative inline-block",H),children:[g.jsx(m0,{className:ki("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",F,M.off)}),g.jsx(Pc,{className:ki("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",F,M.favOn)})]})}):null,Ge=le?g.jsx("button",{type:"button",className:$,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||!p,onClick:Pe(p),children:g.jsxs("span",{className:ki("relative inline-block",H),children:[g.jsx(Th,{className:ki("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",F,M.off)}),g.jsx(Eu,{className:ki("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",F,M.likeOn)})]})}):null,At=te?g.jsx("button",{type:"button","data-hot-target":!0,className:$,title:a?"HOT entfernen":"Als HOT markieren","aria-label":a?"HOT entfernen":"Als HOT markieren","aria-pressed":a,disabled:n||!y,onClick:Pe(y),children:g.jsxs("span",{className:ki("relative inline-block",H),children:[g.jsx(X_,{className:ki("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",F,M.off)}),g.jsx(dx,{className:ki("absolute inset-0 transition-all duration-200 ease-out",a?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",F,M.hotOn)})]})}):null,lt=V?g.jsx("button",{type:"button",className:$,title:d?"Watched entfernen":"Als Watched markieren","aria-label":d?"Watched entfernen":"Als Watched markieren","aria-pressed":d,disabled:n||!S,onClick:Pe(S),children:g.jsxs("span",{className:ki("relative inline-block",H),children:[g.jsx(f0,{className:ki("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0",F,M.off)}),g.jsx(_u,{className:ki("absolute inset-0 transition-all duration-200 ease-out",d?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12",F,M.watchOn)})]})}):null,bt=G?g.jsx("button",{type:"button",className:$,title:"Behalten (nach keep verschieben)","aria-label":"Behalten",disabled:n||!v,onClick:Pe(v),children:g.jsx("span",{className:ki("inline-flex items-center justify-center",H),children:g.jsx(ux,{className:ki(F,M.keep)})})}):null,nt=J?g.jsx("button",{type:"button",className:$,title:"Löschen","aria-label":"Löschen",disabled:n||!b,onClick:Pe(b),children:g.jsx("span",{className:ki("inline-flex items-center justify-center",H),children:g.jsx(cx,{className:ki(F,M.del)})})}):null,wt={details:Fe,add:qe,favorite:dt,like:Ge,watch:lt,hot:At,keep:bt,delete:nt},ht=t&&e==="overlay",Et=W.filter(xe=>!!wt[xe]),ye=ht&&typeof i!="number",Xe=(r?16:20)+(e==="overlay"?r?6:8:6)*2,xt=r?2:3,ft=_.useMemo(()=>{if(!ye)return i??xt;const xe=de||0;if(xe<=0)return Math.min(Et.length,xt);for(let B=Et.length;B>=0;B--)if(B*Xe+Xe+(B>0?B*Ze:0)<=xe)return B;return 0},[ye,i,xt,de,Et.length,Xe,Ze]),Pt=ht?Et.slice(0,ft):Et,qt=ht?Et.slice(ft):[],[It,ni]=_.useState(!1),Gt=_.useRef(null);_.useLayoutEffect(()=>{const xe=Gt.current;if(!xe||typeof window>"u")return;const B=()=>{const re=Gt.current;if(!re)return;const Te=Math.floor(re.getBoundingClientRect().width||0);Te>0&&Ve(Te);const Ke=window.getComputedStyle(re),vt=Ke.columnGap||Ke.gap||"0",Tt=parseFloat(vt);Number.isFinite(Tt)&&Tt>=0&&Je(Tt)};B();const Z=new ResizeObserver(()=>B());return Z.observe(xe),window.addEventListener("resize",B),()=>{window.removeEventListener("resize",B),Z.disconnect()}},[]);const yi=_.useRef(null),Zt=_.useRef(null),Jt=208,di=4,Zi=8,[Di,Mi]=_.useState(null);_.useEffect(()=>{if(!It)return;const xe=Z=>{Z.key==="Escape"&&ni(!1)},B=Z=>{const re=Gt.current,Te=Zt.current,Ke=Z.target;re&&re.contains(Ke)||Te&&Te.contains(Ke)||ni(!1)};return window.addEventListener("keydown",xe),window.addEventListener("mousedown",B),()=>{window.removeEventListener("keydown",xe),window.removeEventListener("mousedown",B)}},[It]),_.useLayoutEffect(()=>{if(!It){Mi(null);return}const xe=()=>{const B=yi.current;if(!B)return;const Z=B.getBoundingClientRect(),re=window.innerWidth,Te=window.innerHeight;let Ke=Z.right-Jt;Ke=Math.max(Zi,Math.min(Ke,re-Jt-Zi));let vt=Z.bottom+di;vt=Math.max(Zi,Math.min(vt,Te-Zi));const Tt=Math.max(120,Te-vt-Zi);Mi({top:vt,left:Ke,maxH:Tt})};return xe(),window.addEventListener("resize",xe),window.addEventListener("scroll",xe,!0),()=>{window.removeEventListener("resize",xe),window.removeEventListener("scroll",xe,!0)}},[It]);const Ki=()=>{Q&&window.dispatchEvent(new CustomEvent("open-model-details",{detail:{modelKey:Q}}))},As=xe=>xe==="details"?g.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:B=>{B.preventDefault(),B.stopPropagation(),ni(!1),Ki()},children:[g.jsx(Q_,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:"Details"})]},"details"):xe==="add"?g.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||!E&&!I,onClick:async B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await pe()},children:[g.jsx(W_,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:"Zu Downloads"})]},"add"):xe==="favorite"?g.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||!f,onClick:async B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await f?.(s)},children:[u?g.jsx(Pc,{className:ki("size-4",M.favOn)}):g.jsx(m0,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:u?"Favorit entfernen":"Als Favorit markieren"})]},"favorite"):xe==="like"?g.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 B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await p?.(s)},children:[c?g.jsx(Eu,{className:ki("size-4",M.favOn)}):g.jsx(Th,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:c?"Gefällt mir entfernen":"Gefällt mir"})]},"like"):xe==="watch"?g.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||!S,onClick:async B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await S?.(s)},children:[d?g.jsx(_u,{className:ki("size-4",M.favOn)}):g.jsx(f0,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:d?"Watched entfernen":"Watched"})]},"watch"):xe==="hot"?g.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||!y,onClick:async B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await y?.(s)},children:[a?g.jsx(dx,{className:ki("size-4",M.favOn)}):g.jsx(X_,{className:ki("size-4",M.off)}),g.jsx("span",{className:"truncate",children:a?"HOT entfernen":"Als HOT markieren"})]},"hot"):xe==="keep"?g.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 B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await v?.(s)},children:[g.jsx(ux,{className:ki("size-4",M.keep)}),g.jsx("span",{className:"truncate",children:"Behalten"})]},"keep"):xe==="delete"?g.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||!b,onClick:async B=>{B.preventDefault(),B.stopPropagation(),ni(!1),await b?.(s)},children:[g.jsx(cx,{className:ki("size-4",M.del)}),g.jsx("span",{className:"truncate",children:"Löschen"})]},"delete"):null;return g.jsxs("div",{ref:Gt,className:ki("relative flex items-center flex-nowrap",N??"gap-2"),children:[Pt.map(xe=>{const B=wt[xe];return B?g.jsx(_.Fragment,{children:B},xe):null}),ht&&qt.length>0?g.jsxs("div",{className:"relative",children:[g.jsx("button",{ref:yi,type:"button",className:$,"aria-label":"Mehr",title:"Mehr","aria-haspopup":"menu","aria-expanded":It,disabled:n,onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),!n&&ni(B=>!B)},children:g.jsx("span",{className:ki("inline-flex items-center justify-center",H),children:g.jsx(jO,{className:ki(F,M.off)})})}),It&&Di&&typeof document<"u"?Oc.createPortal(g.jsx("div",{ref:Zt,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:Di.top,left:Di.left,width:Jt,maxHeight:Di.maxH},onClick:xe=>xe.stopPropagation(),children:qt.map(As)}),document.body):null]}):null]})}function Ga({tag:s,children:e,title:t,active:i,onClick:n,maxWidthClassName:r="max-w-[11rem]",className:a,stopPropagation:u=!0}){const c=s??(typeof e=="string"||typeof e=="number"?String(e):""),d=wi("inline-flex shrink-0 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"),y=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":"",a),v=S=>S.stopPropagation(),b=u?{onPointerDown:v,onMouseDown:v}:{};return n?g.jsx("button",{type:"button",className:y,title:t??c,"aria-pressed":!!i,...b,onClick:S=>{u&&(S.preventDefault(),S.stopPropagation()),c&&n(c)},children:e??s}):g.jsx("span",{className:y,title:t??c,...b,onClick:u?v:void 0,children:e??s})}function fb({rowKey:s,tags:e,activeTagSet:t,lower:i,onToggleTagFilter:n,maxVisible:r,maxWidthClassName:a,gapPx:u=6,className:c}){const[d,f]=_.useState(!1),p=_.useRef(null),y=_.useRef(null),v=_.useRef(null);_.useEffect(()=>f(!1),[s]),_.useEffect(()=>{if(!d)return;const $=M=>{M.key==="Escape"&&f(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[d]);const b=_.useMemo(()=>typeof r=="number"&&r>0?r:Number.POSITIVE_INFINITY,[r]),[S,E]=_.useState(()=>{const $=Math.min(e.length,b);return Math.min($,6)}),L=_.useCallback(()=>{const $=p.current,M=y.current;if(!$||!M)return;const W=Math.floor($.getBoundingClientRect().width);if(W<=0)return;const D=Math.min(e.length,b);if(D<=0){E(0);return}const Q=Array.from(M.children).map(V=>V.offsetWidth).slice(0,D),K=v.current?.offsetWidth??0,q=2,le=V=>{let G=0,J=0;for(let ie=0;ie0?u:0);if(G+oe<=V-q)G+=oe,J++;else break}return J};let te=le(W);if(te0?K+u:0,G=Math.max(0,W-V);te=le(G),te=Math.max(0,te)}E(Math.max(0,Math.min(te,D)))},[e,b,u]);_.useLayoutEffect(()=>{L()},[L,e.join("\0"),a,b]),_.useEffect(()=>{const $=p.current;if(!$)return;const M=new ResizeObserver(()=>L());return M.observe($),()=>M.disconnect()},[L]);const N=Math.min(e.length,b),R=e.slice(0,Math.min(S,N)),H=$=>$.stopPropagation(),F=e.length-R.length;return g.jsxs(g.Fragment,{children:[d?null:g.jsxs("div",{ref:p,className:["mt-2 h-6 flex items-center gap-1.5",c].filter(Boolean).join(" "),onClick:H,onMouseDown:H,onPointerDown:H,children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx("div",{className:"flex flex-nowrap items-center gap-1.5",children:R.length>0?R.map($=>g.jsx(Ga,{tag:$,active:t.has(i($)),onClick:n,maxWidthClassName:a},$)):g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"})})}),F>0?g.jsxs("button",{type:"button",className:["inline-flex shrink-0 items-center truncate rounded-md px-2 py-0.5 text-xs","cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500","bg-gray-100 text-gray-700 hover:bg-gray-200/70","dark:bg-white/10 dark:text-gray-200 dark:hover:bg-white/20"].join(" "),onClick:$=>{$.preventDefault(),$.stopPropagation(),f(!0)},title:"Alle Tags anzeigen","aria-haspopup":"dialog","aria-expanded":!1,children:["+",F]}):null]}),d?g.jsxs("div",{className:["absolute inset-0 z-30","bg-white/60 dark:bg-gray-950","px-3 py-3","pointer-events-auto"].join(" "),onClick:H,onMouseDown:H,onPointerDown:H,role:"dialog","aria-label":"Tags",children:[g.jsx("button",{type:"button",className:`\r absolute right-2 top-2 z-10\r rounded-md bg-gray-100/80 px-2 py-1 text-xs font-semibold text-gray-700\r hover:bg-gray-200/80\r dark:bg-white/10 dark:text-gray-200 dark:hover:bg-white/20\r `,onClick:()=>f(!1),"aria-label":"Schließen",title:"Schließen",children:"✕"}),g.jsx("div",{className:"h-full overflow-auto pr-1",children:g.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.map($=>g.jsx(Ga,{tag:$,active:t.has(i($)),onClick:n,maxWidthClassName:a},$))})})]}):null,g.jsxs("div",{className:"absolute -left-[9999px] -top-[9999px] opacity-0 pointer-events-none",children:[g.jsx("div",{ref:y,className:"flex flex-nowrap items-center gap-1.5",children:e.slice(0,N).map($=>g.jsx(Ga,{tag:$,active:t.has(i($)),onClick:n,maxWidthClassName:a},$))}),g.jsx("button",{ref:v,type:"button",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",children:"+99"})]})]})}const WA=/^HOT[ \u00A0]+/i,YA=s=>String(s||"").replaceAll(" "," "),bc=s=>WA.test(YA(s)),Co=s=>YA(s).replace(WA,"");function mb(s){if(!s)return"";const e=Math.round(Number(s.w)),t=Math.round(Number(s.h));if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return"";const i=Math.min(e,t),n=Math.max(12,Math.round(i*.02)),r=a=>Math.abs(i-a)<=n;return r(4320)?"8K":r(2160)||i>=2e3?"4K":r(1440)?"1440p":r(1080)?"1080p":r(720)?"720p":r(480)?"480p":r(360)?"360p":r(240)?"240p":`${i}p`}const jM=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n};function $M({rows:s,isSmall:e,isLoading:t,teaserPlayback:i,teaserAudio:n,hoverTeaserKey:r,blurPreviews:a,teaserKey:u,inlinePlay:c,setInlinePlay:d,deletingKeys:f,keepingKeys:p,removingKeys:y,swipeRefs:v,assetNonce:b,keyFor:S,baseName:E,modelNameFromOutput:L,runtimeOf:N,sizeBytesOf:R,formatBytes:H,lower:F,onHoverPreviewKeyChange:$,onOpenPlayer:M,openPlayer:W,startInline:D,tryAutoplayInline:I,registerTeaserHost:Q,deleteVideo:K,keepVideo:q,modelsByKey:le,activeTagSet:te,onToggleTagFilter:V,onToggleHot:G,onToggleFavorite:J,onToggleLike:ie,onToggleWatch:oe}){const j=_.useCallback(se=>{const fe=(typeof se.meta?.videoWidth=="number"&&Number.isFinite(se.meta.videoWidth)?se.meta.videoWidth:0)||(typeof se.videoWidth=="number"&&Number.isFinite(se.videoWidth)?se.videoWidth:0),pe=(typeof se.meta?.videoHeight=="number"&&Number.isFinite(se.meta.videoHeight)?se.meta.videoHeight:0)||(typeof se.videoHeight=="number"&&Number.isFinite(se.videoHeight)?se.videoHeight:0);return fe>0&&pe>0?{w:fe,h:pe}:null},[]),X="rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium backdrop-blur-[2px]";return g.jsxs("div",{className:"relative",children:[g.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:s.map(se=>{const fe=S(se),pe=c?.key===fe,Ve=!(!!n&&(pe||r===fe)),Ze=pe?c?.nonce??0:0,Je=f.has(fe)||p.has(fe)||y.has(fe),Pe=L(se.output),Fe=E(se.output||""),qe=bc(Fe),dt=le[F(Pe)],Ge=!!dt?.favorite,At=dt?.liked===!0,lt=!!dt?.watching,bt=jM(dt?.tags),nt=N(se),wt=H(R(se)),ht=j(se),Et=mb(ht),ye=`inline-prev-${encodeURIComponent(fe)}`,mt=["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",!e&&"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",Je&&"pointer-events-none opacity-70",f.has(fe)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",p.has(fe)&&"ring-1 ring-emerald-300 bg-emerald-50/60 dark:bg-emerald-500/10 dark:ring-emerald-500/30",y.has(fe)&&"opacity-0 translate-y-2 scale-[0.98]"].filter(Boolean).join(" "),st=g.jsx("div",{role:"button",tabIndex:0,className:mt,onClick:e?void 0:()=>W(se),onKeyDown:Xe=>{(Xe.key==="Enter"||Xe.key===" ")&&M(se)},children:g.jsxs(fa,{noBodyPadding:!0,className:"overflow-hidden bg-transparent",children:[g.jsxs("div",{id:ye,ref:Q(fe),className:"relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",onMouseEnter:e?void 0:()=>$?.(fe),onMouseLeave:e?void 0:()=>$?.(null),onClick:Xe=>{Xe.preventDefault(),Xe.stopPropagation(),!e&&D(fe)},children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(hb,{job:se,getFileName:E,className:"h-full w-full",showPopover:!1,blur:e||pe?!1:a,animated:i==="all"?!0:i==="hover"?u===fe:!1,animatedMode:"teaser",animatedTrigger:"always",inlineVideo:pe?"always":!1,inlineNonce:Ze,inlineControls:pe,inlineLoop:!1,muted:Ve,popoverMuted:Ve,assetNonce:b??0})}),g.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:Xe=>Xe.stopPropagation(),children:g.jsx(za,{job:se,variant:"overlay",busy:Je,collapseToMenu:!0,isHot:qe,isFavorite:Ge,isLiked:At,isWatching:lt,onToggleWatch:oe,onToggleFavorite:J,onToggleLike:ie,onToggleHot:G,onKeep:q,onDelete:K,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"w-full justify-end gap-1"})}),!e&&c?.key===fe?g.jsx("button",{type:"button",className:"absolute left-2 top-10 z-10 rounded-md bg-black/45 px-2 py-1 text-xs font-semibold text-white hover:bg-black/60",onClick:Xe=>{Xe.preventDefault(),Xe.stopPropagation(),d(xt=>({key:fe,nonce:xt?.key===fe?xt.nonce+1:1}))},title:"Von vorne starten","aria-label":"Von vorne starten",children:"↻"}):null,g.jsx("div",{className:` pointer-events-none absolute inset-x-0 bottom-0 px-2 pb-2 pt-8 text-white `,children:g.jsx("div",{className:"flex items-center justify-end gap-2",children:g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[g.jsx("span",{className:X,children:nt}),Et?g.jsx("span",{className:X,title:ht?`${ht.w}×${ht.h}`:"Auflösung",children:Et}):null,g.jsx("span",{className:X,children:wt})]})})})]}),g.jsxs("div",{className:"relative min-h-[92px] overflow-hidden px-4 py-3 border-t border-black/5 dark:border-white/10 bg-white dark:bg-gray-900",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:Pe}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0",children:[qe?g.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,g.jsx("span",{className:"min-w-0 truncate text-xs text-gray-500 dark:text-gray-400",children:Co(Fe)||"—"})]})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 pt-0.5",children:[lt?g.jsx(_u,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,At?g.jsx(Eu,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Ge?g.jsx(Pc,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsx("div",{className:"mt-2",onClick:Xe=>Xe.stopPropagation(),onMouseDown:Xe=>Xe.stopPropagation(),children:g.jsx(fb,{rowKey:fe,tags:bt,activeTagSet:te,lower:F,onToggleTagFilter:V})})]})]})});return e?g.jsx(OM,{ref:Xe=>{Xe?v.current.set(fe,Xe):v.current.delete(fe)},enabled:!0,disabled:Je,ignoreFromBottomPx:110,doubleTapMs:360,doubleTapMaxMovePx:48,onDoubleTap:async()=>{qe||await G?.(se)},onTap:()=>{const Xe=`inline-prev-${encodeURIComponent(fe)}`;D(fe),requestAnimationFrame(()=>{I(Xe)||requestAnimationFrame(()=>I(Xe))})},onSwipeLeft:()=>K(se),onSwipeRight:()=>q(se),children:st},fe):g.jsx(_.Fragment,{children:st},fe)})}),t&&s.length===0?g.jsx("div",{className:"absolute inset-0 z-20 grid place-items-center rounded-lg bg-white/50 backdrop-blur-[2px] dark:bg-gray-950/40",children:g.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-gray-200 bg-white/80 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/70",children:[g.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-transparent dark:border-white/20 dark:border-t-transparent"}),g.jsx("div",{className:"text-sm font-medium text-gray-800 dark:text-gray-100",children:"Lade…"})]})}):null]})}function HM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 zM=_.forwardRef(HM);function GM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 VM=_.forwardRef(GM);function qM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 KM=_.forwardRef(qM);function WM({title:s,titleId:e,...t},i){return _.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?_.createElement("title",{id:e},s):null,_.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 YM=_.forwardRef(WM);function cr(...s){return s.filter(Boolean).join(" ")}function e2(s){return s==="center"?"text-center":s==="right"?"text-right":"text-left"}function XM(s){return s==="center"?"justify-center":s==="right"?"justify-end":"justify-start"}function t2(s,e){const t=s===0,i=s===e-1;return t||i?"pl-2 pr-2":"px-2"}function i2(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 Sh({columns:s,rows:e,getRowKey:t,title:i,description:n,actions:r,fullWidth:a=!1,card:u=!0,striped:c=!1,stickyHeader:d=!1,compact:f=!1,isLoading:p=!1,emptyLabel:y="Keine Daten vorhanden.",className:v,rowClassName:b,onRowClick:S,onRowContextMenu:E,sort:L,onSortChange:N,defaultSort:R=null}){const H=f?"py-2":"py-4",F=f?"py-3":"py-3.5",$=L!==void 0,[M,W]=_.useState(R),D=$?L:M,I=_.useCallback(K=>{$||W(K),N?.(K)},[$,N]),Q=_.useMemo(()=>{if(!D)return e;const K=s.find(te=>te.key===D.key);if(!K)return e;const q=D.direction==="asc"?1:-1,le=e.map((te,V)=>({r:te,i:V}));return le.sort((te,V)=>{let G=0;if(K.sortFn)G=K.sortFn(te.r,V.r);else{const J=K.sortValue?K.sortValue(te.r):te.r?.[K.key],ie=K.sortValue?K.sortValue(V.r):V.r?.[K.key],oe=i2(J),j=i2(ie);oe.isNull&&!j.isNull?G=1:!oe.isNull&&j.isNull?G=-1:oe.kind==="number"&&j.kind==="number"?G=oe.valuej.value?1:0:G=String(oe.value).localeCompare(String(j.value),void 0,{numeric:!0})}return G===0?te.i-V.i:G*q}),le.map(te=>te.r)},[e,s,D]);return g.jsxs("div",{className:cr(a?"":"px-4 sm:px-6 lg:px-8",v),children:[(i||n||r)&&g.jsxs("div",{className:"sm:flex sm:items-center",children:[g.jsxs("div",{className:"sm:flex-auto",children:[i&&g.jsx("h1",{className:"text-base font-semibold text-gray-900 dark:text-white",children:i}),n&&g.jsx("p",{className:"mt-2 text-sm text-gray-700 dark:text-gray-300",children:n})]}),r&&g.jsx("div",{className:"mt-4 sm:mt-0 sm:ml-16 sm:flex-none",children:r})]}),g.jsx("div",{className:cr(i||n||r?"mt-8":""),children:g.jsx("div",{className:"flow-root",children:g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:cr("inline-block min-w-full align-middle",a?"":"sm:px-6 lg:px-8"),children:g.jsx("div",{className:cr(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:g.jsxs("table",{className:"relative min-w-full divide-y divide-gray-200 dark:divide-white/10",children:[g.jsx("thead",{className:cr(u&&"bg-gray-50/90 dark:bg-gray-800/70",d&&"sticky top-0 z-10 backdrop-blur-sm shadow-sm"),children:g.jsx("tr",{children:s.map((K,q)=>{const le=t2(q,s.length),te=!!D&&D.key===K.key,V=te?D.direction:void 0,G=K.sortable&&!K.srOnlyHeader?te?V==="asc"?"ascending":"descending":"none":void 0,J=()=>{if(!(!K.sortable||K.srOnlyHeader))return I(te?V==="asc"?{key:K.key,direction:"desc"}:null:{key:K.key,direction:"asc"})};return g.jsx("th",{scope:"col","aria-sort":G,className:cr(F,le,"text-xs font-semibold tracking-wide text-gray-700 dark:text-gray-200 whitespace-nowrap",e2(K.align),K.widthClassName,K.headerClassName),children:K.srOnlyHeader?g.jsx("span",{className:"sr-only",children:K.header}):K.sortable?g.jsxs("button",{type:"button",onClick:J,className:cr("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",XM(K.align)),children:[g.jsx("span",{children:K.header}),g.jsx("span",{className:cr("flex-none rounded-sm text-gray-400 dark:text-gray-500",te?"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-white":"invisible group-hover:visible group-focus-visible:visible"),children:g.jsx(zM,{"aria-hidden":"true",className:cr("size-5 transition-transform",te&&V==="asc"&&"rotate-180")})})]}):K.header},K.key)})})}),g.jsx("tbody",{className:cr("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?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:cr(H,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:"Lädt…"})}):Q.length===0?g.jsx("tr",{children:g.jsx("td",{colSpan:s.length,className:cr(H,"px-2 text-sm text-gray-500 dark:text-gray-400"),children:y})}):Q.map((K,q)=>{const le=t?t(K,q):String(q);return g.jsx("tr",{className:cr(c&&"even:bg-gray-50 dark:even:bg-gray-800/50",S&&"cursor-pointer",S&&"hover:bg-gray-50 dark:hover:bg-white/5 transition-colors",b?.(K,q)),onClick:()=>S?.(K),onContextMenu:E?te=>{te.preventDefault(),E(K,te)}:void 0,children:s.map((te,V)=>{const G=t2(V,s.length),J=te.cell?.(K,q)??te.accessor?.(K)??K?.[te.key];return g.jsx("td",{className:cr(H,G,"text-sm whitespace-nowrap",e2(te.align),te.className,te.key===s[0]?.key?"font-medium text-gray-900 dark:text-white":"text-gray-500 dark:text-gray-400"),children:J},te.key)})},le)})})]})})})})})})]})}function QM({rows:s,isLoading:e,keyFor:t,baseName:i,lower:n,modelNameFromOutput:r,runtimeOf:a,sizeBytesOf:u,formatBytes:c,resolutions:d,durations:f,canHover:p,teaserAudio:y,hoverTeaserKey:v,setHoverTeaserKey:b,teaserPlayback:S="hover",teaserKey:E,registerTeaserHost:L,handleDuration:N,handleResolution:R,blurPreviews:H,assetNonce:F,deletingKeys:$,keepingKeys:M,removingKeys:W,modelsByKey:D,activeTagSet:I,onToggleTagFilter:Q,onOpenPlayer:K,onSortModeChange:q,page:le,onPageChange:te,onToggleHot:V,onToggleFavorite:G,onToggleLike:J,onToggleWatch:ie,deleteVideo:oe,keepVideo:j}){const[X,se]=_.useState(null),fe=_.useCallback(Pe=>{const Fe=Pe?.durationSeconds;if(typeof Fe=="number"&&Number.isFinite(Fe)&&Fe>0)return Fe;const qe=Date.parse(String(Pe?.startedAt||"")),dt=Date.parse(String(Pe?.endedAt||""));if(Number.isFinite(qe)&&Number.isFinite(dt)&&dt>qe){const Ge=(dt-qe)/1e3;if(Ge>=1&&Ge<=1440*60)return Ge}return Number.POSITIVE_INFINITY},[]),pe=_.useCallback(Pe=>{const Fe=String(Pe??"").trim();if(!Fe)return[];const qe=Fe.split(/[\n,;|]+/g).map(At=>At.trim()).filter(Boolean),dt=new Set,Ge=[];for(const At of qe){const lt=At.toLowerCase();dt.has(lt)||(dt.add(lt),Ge.push(At))}return Ge.sort((At,lt)=>At.localeCompare(lt,void 0,{sensitivity:"base"})),Ge},[]),de=_.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[140px]",cell:Pe=>{const Fe=t(Pe),dt=!(!!y&&v===Fe);return g.jsx("div",{ref:L(Fe),className:"py-1",onClick:Ge=>Ge.stopPropagation(),onMouseDown:Ge=>Ge.stopPropagation(),onMouseEnter:()=>{p&&b(Fe)},onMouseLeave:()=>{p&&b(null)},children:g.jsx(hb,{job:Pe,getFileName:i,durationSeconds:f[Fe],muted:dt,popoverMuted:dt,onDuration:N,onResolution:R,className:"w-28 h-16 rounded-md ring-1 ring-black/5 dark:ring-white/10",showPopover:!1,blur:H,animated:S==="all"?!0:S==="hover"?E===Fe:!1,animatedMode:"teaser",animatedTrigger:"always",assetNonce:F})})}},{key:"Model",header:"Model",sortable:!0,sortValue:Pe=>{const Fe=i(Pe.output||""),qe=bc(Fe),dt=r(Pe.output),Ge=Co(Fe);return`${dt} ${qe?"HOT":""} ${Ge}`.trim()},cell:Pe=>{const Fe=i(Pe.output||""),qe=bc(Fe),dt=Co(Fe),Ge=r(Pe.output),At=n(r(Pe.output)),lt=pe(D[At]?.tags);return g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:Ge}),g.jsxs("div",{className:"mt-0.5 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"truncate",title:dt,children:dt||"—"}),(()=>{const bt=t(Pe),nt=d[bt]??null,wt=mb(nt);return wt?g.jsx("span",{className:`shrink-0 rounded-md bg-gray-100 px-1.5 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`,title:nt?`${nt.w}×${nt.h}`:"Auflösung",children:wt}):null})(),qe?g.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]}),lt.length>0?g.jsx("div",{className:"mt-1",onClick:bt=>bt.stopPropagation(),onMouseDown:bt=>bt.stopPropagation(),children:g.jsx(fb,{rowKey:t(Pe),tags:lt,activeTagSet:I,lower:n,onToggleTagFilter:Q,maxWidthClassName:"max-w-[11rem]"})}):null]})]})}},{key:"completedAt",header:"Fertiggestellt am",sortable:!0,widthClassName:"w-[150px]",sortValue:Pe=>{const Fe=Date.parse(String(Pe.endedAt||""));return Number.isFinite(Fe)?Fe:Number.NEGATIVE_INFINITY},cell:Pe=>{const Fe=Date.parse(String(Pe.endedAt||""));if(!Number.isFinite(Fe))return g.jsx("span",{className:"text-xs text-gray-400",children:"—"});const qe=new Date(Fe),dt=qe.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),Ge=qe.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"});return g.jsxs("time",{dateTime:qe.toISOString(),title:`${dt} ${Ge}`,className:"tabular-nums whitespace-nowrap text-sm text-gray-900 dark:text-white",children:[g.jsx("span",{className:"font-medium",children:dt}),g.jsx("span",{className:"mx-1 text-gray-400 dark:text-gray-600",children:"·"}),g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:Ge})]})}},{key:"runtime",header:"Dauer",align:"right",sortable:!0,sortValue:Pe=>fe(Pe),cell:Pe=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:a(Pe)})},{key:"size",header:"Größe",align:"right",sortable:!0,sortValue:Pe=>{const Fe=u(Pe);return typeof Fe=="number"?Fe:Number.NEGATIVE_INFINITY},cell:Pe=>g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:c(u(Pe))})},{key:"actions",header:"Aktionen",align:"right",srOnlyHeader:!0,cell:Pe=>{const Fe=t(Pe),qe=$.has(Fe)||M.has(Fe)||W.has(Fe),dt=i(Pe.output||""),Ge=bc(dt),At=n(r(Pe.output)),lt=D[At],bt=!!lt?.favorite,nt=lt?.liked===!0,wt=!!lt?.watching;return g.jsx(za,{job:Pe,variant:"table",busy:qe,isHot:Ge,isFavorite:bt,isLiked:nt,isWatching:wt,onToggleWatch:ie,onToggleFavorite:G,onToggleLike:J,onToggleHot:V,onKeep:j,onDelete:oe,order:["watch","favorite","like","hot","details","add","keep","delete"],className:"flex items-center justify-end gap-1"})}}],[t,i,f,y,v,L,p,b,N,R,H,S,E,F,n,r,D,I,Q,d,$,M,W,ie,G,J,V,j,oe,u,c,a,pe,fe]),Ve=_.useCallback(Pe=>{if(!Pe)return"completed_desc";const Fe=Pe,qe=String(Fe.key??Fe.columnKey??Fe.id??""),dt=String(Fe.dir??Fe.direction??Fe.order??"").toLowerCase(),Ge=dt==="asc"||dt==="1"||dt==="true";return qe==="completedAt"?Ge?"completed_asc":"completed_desc":qe==="runtime"?Ge?"duration_asc":"duration_desc":qe==="size"?Ge?"size_asc":"size_desc":qe==="Model"||qe==="video"?Ge?"file_asc":"file_desc":Ge?"completed_asc":"completed_desc"},[]),Ze=_.useCallback(Pe=>{se(Pe),q(Ve(Pe)),le!==1&&te(1)},[q,Ve,le,te]),Je=_.useCallback(Pe=>{const Fe=t(Pe);return["transition-all duration-300",($.has(Fe)||W.has(Fe))&&"bg-red-50/60 dark:bg-red-500/10 pointer-events-none",$.has(Fe)&&"animate-pulse",(M.has(Fe)||W.has(Fe))&&"pointer-events-none",M.has(Fe)&&"bg-emerald-50/60 dark:bg-emerald-500/10 animate-pulse",W.has(Fe)&&"opacity-0"].filter(Boolean).join(" ")},[t,$,M,W]);return g.jsxs("div",{className:"relative",children:[g.jsx(Sh,{rows:s,columns:de,getRowKey:Pe=>t(Pe),striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,sort:X,onSortChange:Ze,onRowClick:K,rowClassName:Je}),e&&s.length===0?g.jsx("div",{className:"absolute inset-0 z-20 grid place-items-center rounded-lg bg-white/50 backdrop-blur-[2px] dark:bg-gray-950/40",children:g.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-gray-200 bg-white/80 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/70",children:[g.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-transparent dark:border-white/20 dark:border-t-transparent"}),g.jsx("div",{className:"text-sm font-medium text-gray-800 dark:text-gray-100",children:"Lade…"})]})}):null]})}function ZM({rows:s,isLoading:e,blurPreviews:t,durations:i,teaserPlayback:n,teaserAudio:r,hoverTeaserKey:a,teaserKey:u,handleDuration:c,keyFor:d,baseName:f,modelNameFromOutput:p,runtimeOf:y,sizeBytesOf:v,formatBytes:b,deletingKeys:S,keepingKeys:E,removingKeys:L,deletedKeys:N,registerTeaserHost:R,onHoverPreviewKeyChange:H,onOpenPlayer:F,deleteVideo:$,keepVideo:M,onToggleHot:W,lower:D,modelsByKey:I,activeTagSet:Q,onToggleTagFilter:K,onToggleFavorite:q,onToggleLike:le,onToggleWatch:te}){const V=n==="hover"||n==="all",G=_.useCallback(oe=>j=>{if(!V){R(oe)(null);return}R(oe)(j)},[R,V]),J=oe=>{const j=String(oe??"").trim();if(!j)return[];const X=j.split(/[\n,;|]+/g).map(pe=>pe.trim()).filter(Boolean),se=new Set,fe=[];for(const pe of X){const de=pe.toLowerCase();se.has(de)||(se.add(de),fe.push(pe))}return fe},ie=_.useCallback(oe=>{const j=(typeof oe.meta?.videoWidth=="number"&&Number.isFinite(oe.meta.videoWidth)?oe.meta.videoWidth:0)||(typeof oe.videoWidth=="number"&&Number.isFinite(oe.videoWidth)?oe.videoWidth:0),X=(typeof oe.meta?.videoHeight=="number"&&Number.isFinite(oe.meta.videoHeight)?oe.meta.videoHeight:0)||(typeof oe.videoHeight=="number"&&Number.isFinite(oe.videoHeight)?oe.videoHeight:0);return j>0&&X>0?{w:j,h:X}:null},[]);return g.jsxs("div",{className:"relative",children:[g.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4",children:s.map(oe=>{const j=d(oe),se=!(!!r&&a===j),fe=p(oe.output),pe=D(fe),de=I[pe],Ve=!!de?.favorite,Ze=de?.liked===!0,Je=!!de?.watching,Pe=J(de?.tags),Fe=f(oe.output||""),qe=bc(Fe),dt=Co(Fe),Ge=y(oe),At=b(v(oe)),lt=ie(oe),bt=mb(lt),nt=S.has(j)||E.has(j)||L.has(j),wt=N.has(j);return g.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",nt&&"pointer-events-none opacity-70",S.has(j)&&"ring-1 ring-red-300 bg-red-50/60 dark:bg-red-500/10 dark:ring-red-500/30",L.has(j)&&"opacity-0 translate-y-2 scale-[0.98]",wt&&"hidden"].filter(Boolean).join(" "),onClick:()=>F(oe),onKeyDown:ht=>{(ht.key==="Enter"||ht.key===" ")&&F(oe)},children:[g.jsxs("div",{className:"group relative aspect-video rounded-t-lg bg-black/5 dark:bg-white/5",ref:G(j),onMouseEnter:()=>H?.(j),onMouseLeave:()=>H?.(null),children:[g.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-t-lg",children:[g.jsx("div",{className:"absolute inset-0",children:g.jsx(hb,{job:oe,getFileName:ht=>Co(f(ht)),durationSeconds:i[j]??oe?.durationSeconds,onDuration:c,variant:"fill",showPopover:!1,blur:t,animated:n==="all"?!0:n==="hover"?u===j:!1,animatedMode:"teaser",animatedTrigger:"always",clipSeconds:1,thumbSamples:18,muted:se,popoverMuted:se})}),g.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 p-2 text-white",children:g.jsx("div",{className:"flex items-end justify-end gap-2",children:g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:Ge}),bt?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",title:lt?`${lt.w}×${lt.h}`:"Auflösung",children:bt}):null,g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 text-xs font-medium",children:At})]})})})]}),g.jsx("div",{className:"absolute inset-x-2 top-2 z-10 flex justify-end",onClick:ht=>ht.stopPropagation(),children:g.jsx(za,{job:oe,variant:"overlay",busy:nt,collapseToMenu:!0,isHot:qe,isFavorite:Ve,isLiked:Ze,isWatching:Je,onToggleWatch:te,onToggleFavorite:q,onToggleLike:le,onToggleHot:W,onKeep:M,onDelete:$,order:["watch","favorite","like","hot","keep","delete","details","add"],className:"w-full justify-end gap-1"})})]}),g.jsxs("div",{className:"relative min-h-[92px] overflow-hidden px-4 py-3 rounded-b-lg border-t border-gray-200/60 dark:border-white/10 bg-white dark:bg-gray-900",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsx("div",{className:"min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white",children:fe}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[Je?g.jsx(_u,{className:"size-4 text-sky-600 dark:text-sky-300"}):null,Ze?g.jsx(Eu,{className:"size-4 text-rose-600 dark:text-rose-300"}):null,Ve?g.jsx(Pc,{className:"size-4 text-amber-600 dark:text-amber-300"}):null]})]}),g.jsxs("div",{className:"mt-0.5 flex items-center gap-2 min-w-0 text-xs text-gray-500 dark:text-gray-400",children:[g.jsx("span",{className:"truncate",children:Co(dt)||"—"}),qe?g.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]}),g.jsx("div",{className:"mt-2",onClick:ht=>ht.stopPropagation(),onMouseDown:ht=>ht.stopPropagation(),children:g.jsx(fb,{rowKey:j,tags:Pe,activeTagSet:Q,lower:D,onToggleTagFilter:K})})]})]},j)})}),e&&s.length===0?g.jsx("div",{className:"absolute inset-0 z-20 grid place-items-center rounded-lg bg-white/50 backdrop-blur-[2px] dark:bg-gray-950/40",children:g.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-gray-200 bg-white/80 px-3 py-2 shadow-sm dark:border-white/10 dark:bg-gray-900/70",children:[g.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-transparent dark:border-white/20 dark:border-t-transparent"}),g.jsx("div",{className:"text-sm font-medium text-gray-800 dark:text-gray-100",children:"Lade…"})]})}):null]})}function s2(s,e,t){return Math.max(e,Math.min(t,s))}function My(s,e){const t=[];for(let i=s;i<=e;i++)t.push(i);return t}function JM(s,e,t,i){if(s<=1)return[1];const n=1,r=s,a=My(n,Math.min(t,r)),u=My(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(...a),c>t+1?f.push("ellipsis"):t+1t&&f.push(r-t),f.push(...u);const p=new Set;return f.filter(y=>{const v=String(y);return p.has(v)?!1:(p.add(v),!0)})}function e3({active:s,disabled:e,rounded:t,onClick:i,children:n,title:r}){const a=t==="l"?"rounded-l-md":t==="r"?"rounded-r-md":"";return g.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",a,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 XA({page:s,pageSize:e,totalItems:t,onPageChange:i,siblingCount:n=1,boundaryCount:r=1,showSummary:a=!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))),y=s2(s||1,1,p);if(p<=1)return null;const v=t===0?0:(y-1)*e+1,b=Math.min(y*e,t),S=JM(p,y,r,n),E=L=>i(s2(L,1,p));return g.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:[g.jsxs("div",{className:"flex flex-1 justify-between sm:hidden",children:[g.jsx("button",{type:"button",onClick:()=>E(y-1),disabled:y<=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}),g.jsx("button",{type:"button",onClick:()=>E(y+1),disabled:y>=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})]}),g.jsxs("div",{className:"hidden sm:flex sm:flex-1 sm:items-center sm:justify-between",children:[g.jsx("div",{children:a?g.jsxs("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:["Showing ",g.jsx("span",{className:"font-medium",children:v})," to"," ",g.jsx("span",{className:"font-medium",children:b})," of"," ",g.jsx("span",{className:"font-medium",children:t})," results"]}):null}),g.jsx("div",{children:g.jsxs("nav",{"aria-label":c,className:"isolate inline-flex -space-x-px rounded-md shadow-xs dark:shadow-none",children:[g.jsxs("button",{type:"button",onClick:()=>E(y-1),disabled:y<=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:[g.jsx("span",{className:"sr-only",children:d}),g.jsx(VM,{"aria-hidden":"true",className:"size-5"})]}),S.map((L,N)=>L==="ellipsis"?g.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-${N}`):g.jsx(e3,{active:L===y,onClick:()=>E(L),rounded:"none",children:L},L)),g.jsxs("button",{type:"button",onClick:()=>E(y+1),disabled:y>=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:[g.jsx("span",{className:"sr-only",children:f}),g.jsx(KM,{"aria-hidden":"true",className:"size-5"})]})]})})]})]})}const QA=_.createContext(null);function t3(s){switch(s){case"success":return{Icon:BO,cls:"text-emerald-500"};case"error":return{Icon:yM,cls:"text-rose-500"};case"warning":return{Icon:HO,cls:"text-amber-500"};default:return{Icon:QO,cls:"text-sky-500"}}}function i3(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 s3(s){switch(s){case"success":return"Erfolg";case"error":return"Fehler";case"warning":return"Hinweis";default:return"Info"}}function n3(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function r3({children:s,maxToasts:e=3,defaultDurationMs:t=3500,position:i="bottom-right"}){const[n,r]=_.useState([]),[a,u]=_.useState(!0),c=_.useCallback(async()=>{try{const E=await fetch("/api/settings",{cache:"no-store"});if(!E.ok)return;const L=await E.json();u(!!(L?.enableNotifications??!0))}catch{}},[]);_.useEffect(()=>{c();const E=()=>c();return window.addEventListener("recorder-settings-updated",E),()=>window.removeEventListener("recorder-settings-updated",E)},[c]),_.useEffect(()=>{a||r(E=>E.filter(L=>L.type==="error"))},[a]);const d=_.useCallback(E=>{r(L=>L.filter(N=>N.id!==E))},[]),f=_.useCallback(()=>r([]),[]),p=_.useCallback(E=>{if(!a&&E.type!=="error")return"";const L=n3(),N=E.durationMs??t;return r(R=>[{...E,id:L,durationMs:N},...R].slice(0,Math.max(1,e))),N&&N>0&&window.setTimeout(()=>d(L),N),L},[t,e,d,a]),y=_.useMemo(()=>({push:p,remove:d,clear:f}),[p,d,f]),v=i==="top-right"||i==="top-left"?"items-start sm:items-start sm:justify-start":"items-end sm:items-end sm:justify-end",b=i.endsWith("left")?"sm:items-start":"sm:items-end",S=i.startsWith("top")?"top-0 bottom-auto":"bottom-0 top-auto";return g.jsxs(QA.Provider,{value:y,children:[s,g.jsx("div",{"aria-live":"assertive",className:["pointer-events-none fixed z-[80] inset-x-0",S].join(" "),children:g.jsx("div",{className:["flex w-full px-4 py-6 sm:p-6",v].join(" "),children:g.jsx("div",{className:["flex w-full flex-col space-y-3",b].join(" "),children:n.map(E=>{const{Icon:L,cls:N}=t3(E.type),R=(E.title||"").trim()||s3(E.type),H=(E.message||"").trim(),F=(E.imageUrl||"").trim(),$=(E.imageAlt||R).trim();return g.jsx(bh,{appear:!0,show:!0,children:g.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",i3(E.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:g.jsx("div",{className:"p-4",children:g.jsxs("div",{className:"flex items-start gap-3",children:[F?g.jsx("div",{className:"shrink-0",children:g.jsx("img",{src:F,alt:$,loading:"lazy",referrerPolicy:"no-referrer",className:["h-12 w-12 rounded-lg object-cover","ring-1 ring-black/10 dark:ring-white/10"].join(" ")})}):g.jsx("div",{className:"shrink-0",children:g.jsx(L,{className:["size-6",N].join(" "),"aria-hidden":"true"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:R}),H?g.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300 break-words",children:H}):null]}),g.jsxs("button",{type:"button",onClick:()=>d(E.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:[g.jsx("span",{className:"sr-only",children:"Close"}),g.jsx(YM,{"aria-hidden":"true",className:"size-5"})]})]})})})},E.id)})})})})]})}function a3(){const s=_.useContext(QA);if(!s)throw new Error("useToast must be used within ");return s}function ZA(){const{push:s,remove:e,clear:t}=a3(),i=n=>(r,a,u)=>s({type:n,title:r,message:a,...u});return{push:s,remove:e,clear:t,success:i("success"),error:i("error"),info:i("info"),warning:i("warning")}}function o3(s){return typeof s=="number"?s:s==="xs"?12:s==="sm"?16:s==="lg"?28:20}function n2(...s){return s.filter(Boolean).join(" ")}function r2({size:s="md",className:e,label:t,srLabel:i="Lädt…",center:n=!1}){const r=o3(s);return g.jsxs("span",{className:n2("inline-flex items-center gap-2",n&&"justify-center w-full"),role:"status","aria-live":"polite",children:[g.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",className:n2("animate-spin text-gray-500",e),"aria-hidden":"true",children:[g.jsx("circle",{cx:"12",cy:"12",r:"9",fill:"none",stroke:"currentColor",strokeWidth:"3",opacity:"0.25"}),g.jsx("path",{fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",d:"M21 12a9 9 0 0 0-9-9",opacity:"0.95"})]}),t?g.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-200",children:t}):g.jsx("span",{className:"sr-only",children:i})]})}const pb=s=>(s||"").replaceAll("\\","/"),hr=s=>{const t=pb(s).split("/");return t[t.length-1]||""},Lr=s=>{const e=s?.id;return e!=null&&String(e).trim()!==""?String(e):hr(s.output||"")||String(s?.output||"")},l3=s=>{const e=pb(String(s??""));return e.includes("/.trash/")||e.endsWith("/.trash")};function a2(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 Py(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 o2(s){const[e,t]=_.useState(!1);return _.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 Jd=s=>{const e=hr(s||""),t=Co(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},Rr=s=>(s||"").trim().toLowerCase(),u3=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n},By=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 c3({jobs:s,doneJobs:e,blurPreviews:t,teaserPlayback:i,teaserAudio:n,onOpenPlayer:r,onDeleteJob:a,onToggleHot:u,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,doneTotal:p,page:y,pageSize:v,onPageChange:b,assetNonce:S,sortMode:E,onSortModeChange:L,modelsByKey:N,loadMode:R="paged"}){const H=R==="all",F=i??"hover",$=o2("(hover: hover) and (pointer: fine)"),M=ZA(),W=_.useRef(new Map),[D,I]=_.useState(null),[Q,K]=_.useState(null),q=_.useRef(null),le=_.useRef(new WeakMap),[te,V]=_.useState(()=>new Set),[G,J]=_.useState(()=>new Set),[ie,oe]=_.useState(!1),[j,X]=_.useState(null),[se,fe]=_.useState(!1),[pe,de]=_.useState({}),[Ve,Ze]=_.useState(null),[Je,Pe]=_.useState(null),[Fe,qe]=_.useState(0),dt=_.useRef(null),Ge=_.useCallback(()=>{dt.current&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>qe(Ee=>Ee+1),80)},[]),At=_.useRef({pending:0,t:0,timer:0}),lt=_.useCallback(Ee=>{!Ee||!Number.isFinite(Ee)||(At.current.pending+=Ee,!At.current.timer&&(At.current.timer=window.setTimeout(()=>{At.current.timer=0;const Ie=At.current.pending;At.current.pending=0,Ie&&window.dispatchEvent(new CustomEvent("finished-downloads:count-hint",{detail:{delta:Ie}}))},120)))},[]),bt="finishedDownloads_view",nt="finishedDownloads_includeKeep_v2",wt="finishedDownloads_mobileOptionsOpen_v1",[ht,Et]=_.useState("table"),[ye,mt]=_.useState(!1),[st,Xe]=_.useState(!1),xt=_.useRef(new Map),ft=_.useCallback(async()=>{if(!j||se)return;fe(!0);const Ee=Ie=>{V(Ue=>{const it=new Set(Ue);return it.delete(Ie),it}),J(Ue=>{const it=new Set(Ue);return it.delete(Ie),it}),Ui(Ue=>{const it=new Set(Ue);return it.delete(Ie),it}),_n(Ue=>{const it=new Set(Ue);return it.delete(Ie),it})};try{if(j.kind==="delete"){const Ie=await fetch(`/api/record/restore?token=${encodeURIComponent(j.undoToken)}`,{method:"POST"});if(!Ie.ok){const ei=await Ie.text().catch(()=>"");throw new Error(ei||`HTTP ${Ie.status}`)}const Ue=await Ie.json().catch(()=>null),it=String(Ue?.restoredFile||j.originalFile);Ee(j.originalFile),Ee(it);const St=j.from==="keep"&&!ye?0:1;lt(St),Ge(),X(null);return}if(j.kind==="keep"){const Ie=await fetch(`/api/record/unkeep?file=${encodeURIComponent(j.keptFile)}`,{method:"POST"});if(!Ie.ok){const St=await Ie.text().catch(()=>"");throw new Error(St||`HTTP ${Ie.status}`)}const Ue=await Ie.json().catch(()=>null),it=String(Ue?.newFile||j.originalFile);Ee(j.originalFile),Ee(it),lt(1),Ge(),X(null);return}if(j.kind==="hot"){const Ie=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(j.currentFile)}`,{method:"POST"});if(!Ie.ok){const ei=await Ie.text().catch(()=>"");throw new Error(ei||`HTTP ${Ie.status}`)}const Ue=await Ie.json().catch(()=>null),it=String(Ue?.oldFile||j.currentFile),St=String(Ue?.newFile||"");St&&Si(it,St),Ge(),X(null);return}}catch(Ie){M.error("Undo fehlgeschlagen",String(Ie?.message||Ie))}finally{fe(!1)}},[j,se,M,Ge]),[Pt,qt]=_.useState([]),It=_.useMemo(()=>new Set(Pt.map(Rr)),[Pt]),ni=_.useMemo(()=>{const Ee={},Ie={};for(const[Ue,it]of Object.entries(N??{})){const St=Rr(Ue),ei=u3(it?.tags);Ee[St]=ei,Ie[St]=new Set(ei.map(Rr))}return{tagsByModelKey:Ee,tagSetByModelKey:Ie}},[N]),[Gt,yi]=_.useState(""),Zt=_.useDeferredValue(Gt),Jt=_.useMemo(()=>Rr(Zt).split(/\s+/g).map(Ee=>Ee.trim()).filter(Boolean),[Zt]),di=_.useCallback(()=>yi(""),[]),Zi=_.useCallback(Ee=>{const Ie=Rr(Ee);qt(Ue=>Ue.some(St=>Rr(St)===Ie)?Ue.filter(St=>Rr(St)!==Ie):[...Ue,Ee])},[]),Di=Jt.length>0||It.size>0,Mi=Di||H,Ki=_.useCallback(async Ee=>{oe(!0);try{const Ie=await fetch(`/api/record/done?all=1&sort=${encodeURIComponent(E)}&withCount=1${ye?"&includeKeep=1":""}`,{cache:"no-store",signal:Ee});if(!Ie.ok)return;const Ue=await Ie.json().catch(()=>null),it=Array.isArray(Ue?.items)?Ue.items:[],St=Number(Ue?.count??Ue?.totalCount??it.length);Ze(it),Pe(Number.isFinite(St)?St:it.length)}finally{oe(!1)}},[E,ye]),As=_.useCallback(()=>qt([]),[]);_.useEffect(()=>{try{const Ee=localStorage.getItem("finishedDownloads_pendingTags");if(!Ee)return;const Ie=JSON.parse(Ee),Ue=Array.isArray(Ie)?Ie.map(it=>String(it||"").trim()).filter(Boolean):[];if(Ue.length===0)return;Oc.flushSync(()=>qt(Ue)),y!==1&&b(1)}catch{}finally{try{localStorage.removeItem("finishedDownloads_pendingTags")}catch{}}},[]),_.useEffect(()=>{if(!Mi)return;const Ee=new AbortController,Ie=window.setTimeout(()=>{Ki(Ee.signal).catch(()=>{})},250);return()=>{window.clearTimeout(Ie),Ee.abort()}},[Mi,Ki]),_.useEffect(()=>{if(Fe===0)return;const Ee=new AbortController;let Ie=!0;return Mi?((async()=>{try{await Ki(Ee.signal)}catch{}})(),()=>{Ie=!1,Ee.abort()}):(oe(!0),(async()=>{try{const[Ue,it]=await Promise.all([fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(E)}${ye?"&includeKeep=1":""}`,{cache:"no-store",signal:Ee.signal}),fetch(`/api/record/done/meta${ye?"?includeKeep=1":""}`,{cache:"no-store",signal:Ee.signal})]);let St=!0;if(Ue.ok){const ei=await Ue.json().catch(()=>null),Yt=Array.isArray(ei?.items)?ei.items:Array.isArray(ei)?ei:[];Ze(Yt)}if(it.ok){const ei=await it.json().catch(()=>null),Yt=Number(ei?.count??0),Ri=Number.isFinite(Yt)&&Yt>=0?Yt:0;Pe(Ri);const Ti=Math.max(1,Math.ceil(Ri/v));if(y>Ti){b(Ti),Ze(null);return}}St&&(Li.current=0)}catch{}finally{Ie&&oe(!1)}})(),()=>{Ie=!1,Ee.abort()})},[Fe,Mi,Ki,y,v,E,ye,b]),_.useEffect(()=>{Mi||(Ze(null),Pe(null))},[y,v,E,ye,Mi]),_.useEffect(()=>{if(!ye){Di||(Ze(null),Pe(null));return}if(Di)return;const Ee=new AbortController;return(async()=>{try{const Ie=await fetch(`/api/record/done?page=${y}&pageSize=${v}&sort=${encodeURIComponent(E)}&withCount=1&includeKeep=1`,{cache:"no-store",signal:Ee.signal});if(!Ie.ok)return;const Ue=await Ie.json().catch(()=>null),it=Array.isArray(Ue?.items)?Ue.items:[],St=Number(Ue?.count??Ue?.totalCount??it.length);Ze(it),Pe(Number.isFinite(St)?St:it.length)}catch{}})(),()=>Ee.abort()},[ye,Di,y,v,E]),_.useEffect(()=>{try{const Ee=localStorage.getItem(bt);Et(Ee==="table"||Ee==="cards"||Ee==="gallery"?Ee:window.matchMedia("(max-width: 639px)").matches?"cards":"table")}catch{Et("table")}},[]),_.useEffect(()=>{try{localStorage.setItem(bt,ht)}catch{}},[ht]),_.useEffect(()=>{try{const Ee=localStorage.getItem(nt);mt(Ee==="1"||Ee==="true"||Ee==="yes")}catch{mt(!1)}},[]),_.useEffect(()=>{try{localStorage.setItem(nt,ye?"1":"0")}catch{}},[ye]),_.useEffect(()=>{try{const Ee=localStorage.getItem(wt);Xe(Ee==="1"||Ee==="true"||Ee==="yes")}catch{Xe(!1)}},[]),_.useEffect(()=>{try{localStorage.setItem(wt,st?"1":"0")}catch{}},[st]);const[xe,B]=_.useState({}),Z=_.useRef({}),re=_.useRef(null),[Te,Ke]=_.useState({}),vt=_.useRef({}),Tt=_.useRef(null),Li=_.useRef(0);_.useEffect(()=>{vt.current=Te},[Te]);const bi=_.useCallback(()=>{Tt.current==null&&(Tt.current=window.setTimeout(()=>{Tt.current=null,Ke({...vt.current})},200))},[]);_.useEffect(()=>()=>{Tt.current!=null&&(window.clearTimeout(Tt.current),Tt.current=null)},[]),_.useEffect(()=>{Z.current=xe},[xe]);const ji=_.useCallback(()=>{re.current==null&&(re.current=window.setTimeout(()=>{re.current=null,B({...Z.current})},200))},[]);_.useEffect(()=>()=>{re.current!=null&&(window.clearTimeout(re.current),re.current=null)},[]);const[ai,Fi]=_.useState(null),li=!n,$s=_.useCallback(Ee=>{const Ue=document.getElementById(Ee)?.querySelector("video");if(!Ue)return!1;y0(Ue,{muted:li});const it=Ue.play?.();return it&&typeof it.catch=="function"&&it.catch(()=>{}),!0},[li]),$i=_.useCallback(Ee=>{Fi(Ie=>Ie?.key===Ee?{key:Ee,nonce:Ie.nonce+1}:{key:Ee,nonce:1})},[]),Hi=_.useCallback(Ee=>{Fi(null),r(Ee)},[r]),ii=_.useCallback((Ee,Ie)=>{J(Ue=>{const it=new Set(Ue);return Ie?it.add(Ee):it.delete(Ee),it})},[]),Ht=_.useCallback(Ee=>{V(Ie=>{const Ue=new Set(Ie);return Ue.add(Ee),Ue})},[]),[Kt,Ui]=_.useState(()=>new Set),rs=_.useCallback((Ee,Ie)=>{Ui(Ue=>{const it=new Set(Ue);return Ie?it.add(Ee):it.delete(Ee),it})},[]),[mn,_n]=_.useState(()=>new Set),je=_.useRef(new Map),gt=_.useCallback((Ee,Ie)=>{_n(Ue=>{const it=new Set(Ue);return Ie?it.add(Ee):it.delete(Ee),it})},[]),Ct=_.useCallback(Ee=>{const Ie=je.current.get(Ee);Ie!=null&&(window.clearTimeout(Ie),je.current.delete(Ee))},[]),Vt=_.useCallback(Ee=>{Ct(Ee),V(Ie=>{const Ue=new Set(Ie);return Ue.delete(Ee),Ue}),_n(Ie=>{const Ue=new Set(Ie);return Ue.delete(Ee),Ue}),J(Ie=>{const Ue=new Set(Ie);return Ue.delete(Ee),Ue}),Ui(Ie=>{const Ue=new Set(Ie);return Ue.delete(Ee),Ue})},[Ct]),Bt=_.useCallback(Ee=>{Ge(),gt(Ee,!0),Ct(Ee);const Ie=window.setTimeout(()=>{je.current.delete(Ee),Ht(Ee),gt(Ee,!1)},320);je.current.set(Ee,Ie)},[Ht,gt,Ge,Ct]),mi=_.useCallback(async(Ee,Ie)=>{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:Ee}})),Ie?.close&&window.dispatchEvent(new CustomEvent("player:close",{detail:{file:Ee}})),await new Promise(Ue=>window.setTimeout(Ue,250))},[]),Ut=_.useCallback(async Ee=>{const Ie=hr(Ee.output||""),Ue=Lr(Ee);if(!Ie)return M.error("Löschen nicht möglich","Kein Dateiname gefunden – kann nicht löschen."),!1;if(G.has(Ue))return!1;ii(Ue,!0);try{if(await mi(Ie,{close:!0}),a){const Ti=(await a(Ee))?.undoToken;return X(typeof Ti=="string"&&Ti?{kind:"delete",undoToken:Ti,originalFile:Ie}:null),Bt(Ue),lt(-1),!0}const it=await fetch(`/api/record/delete?file=${encodeURIComponent(Ie)}`,{method:"POST"});if(!it.ok){const Ri=await it.text().catch(()=>"");throw new Error(Ri||`HTTP ${it.status}`)}const St=await it.json().catch(()=>null),ei=St?.from==="keep"?"keep":"done",Yt=typeof St?.undoToken=="string"?St.undoToken:"";return X(Yt?{kind:"delete",undoToken:Yt,originalFile:Ie,from:ei}:null),Bt(Ue),lt(-1),!0}catch{return Vt(Ue),M.error("Löschen fehlgeschlagen: ",Ie),!1}finally{ii(Ue,!1)}},[G,ii,mi,a,Bt,M,X]),zi=_.useCallback(async Ee=>{const Ie=hr(Ee.output||""),Ue=Lr(Ee);if(!Ie)return M.error("Keep nicht möglich","Kein Dateiname gefunden – kann nicht behalten."),!1;if(Kt.has(Ue)||G.has(Ue))return!1;rs(Ue,!0);try{await mi(Ie,{close:!0});const it=await fetch(`/api/record/keep?file=${encodeURIComponent(Ie)}`,{method:"POST"});if(!it.ok){const Yt=await it.text().catch(()=>"");throw new Error(Yt||`HTTP ${it.status}`)}const St=await it.json().catch(()=>null),ei=typeof St?.newFile=="string"&&St.newFile?St.newFile:Ie;return X({kind:"keep",keptFile:ei,originalFile:Ie}),Bt(Ue),lt(ye?0:-1),!0}catch{return M.error("Keep fehlgeschlagen",Ie),!1}finally{rs(Ue,!1)}},[Kt,G,rs,mi,Bt,M,X]),Si=_.useCallback((Ee,Ie)=>{!Ee||!Ie||Ee===Ie||de(Ue=>{const it={...Ue};for(const[St,ei]of Object.entries(it))(St===Ee||St===Ie||ei===Ee||ei===Ie)&&delete it[St];return it[Ee]=Ie,it})},[]),Ss=_.useCallback(async Ee=>{const Ie=hr(Ee.output||"");if(!Ie){M.error("HOT nicht möglich","Kein Dateiname gefunden – kann nicht HOT togglen.");return}const Ue=Yt=>bc(Yt)?Co(Yt):`HOT ${Yt}`,it=(Yt,Ri)=>{!Yt||!Ri||Yt===Ri||Si(Yt,Ri)},St=Ie,ei=Ue(St);Si(St,ei);try{if(await mi(St,{close:!0}),u){const An=await u(Ee),Fn=typeof An?.oldFile=="string"?An.oldFile:"",Ls=typeof An?.newFile=="string"?An.newFile:"";Fn&&Ls&&it(Fn,Ls),X({kind:"hot",currentFile:Ls||ei}),(E==="file_asc"||E==="file_desc")&&Ge();return}const Yt=await fetch(`/api/record/toggle-hot?file=${encodeURIComponent(St)}`,{method:"POST"});if(!Yt.ok){const An=await Yt.text().catch(()=>"");throw new Error(An||`HTTP ${Yt.status}`)}const Ri=await Yt.json().catch(()=>null),Ti=typeof Ri?.oldFile=="string"&&Ri.oldFile?Ri.oldFile:St,Bn=typeof Ri?.newFile=="string"&&Ri.newFile?Ri.newFile:ei;Ti!==Bn&&it(Ti,Bn),X({kind:"hot",currentFile:Bn}),Ge()}catch(Yt){Si(ei,St),X(null),M.error("HOT umbenennen fehlgeschlagen",String(Yt?.message||Yt))}},[hr,M,Si,mi,u,Ge,X]),ks=_.useCallback(Ee=>{const Ie=pb(Ee.output||""),Ue=hr(Ie),it=pe[Ue];if(!it)return Ee;const St=Ie.lastIndexOf("/"),ei=St>=0?Ie.slice(0,St+1):"";return{...Ee,output:ei+it}},[pe,hr]),Ys=Ve??e,En=Je??p,Cs=_.useMemo(()=>{const Ee=new Map;for(const Ue of Ys){const it=ks(Ue);Ee.set(Lr(it),it)}for(const Ue of s){const it=ks(Ue),St=Lr(it);Ee.has(St)&&Ee.set(St,{...Ee.get(St),...it})}return Array.from(Ee.values()).filter(Ue=>te.has(Lr(Ue))||l3(Ue.output)?!1:Ue.status==="finished"||Ue.status==="failed"||Ue.status==="stopped")},[s,Ys,te,ks]),Mn=_.useRef(new Map);_.useEffect(()=>{const Ee=new Map;for(const Ie of Cs){const Ue=hr(Ie.output||"");Ue&&Ee.set(Ue,Lr(Ie))}Mn.current=Ee},[Cs]),_.useEffect(()=>{const Ee=Ie=>{const Ue=Ie.detail;if(!Ue?.file)return;const it=Mn.current.get(Ue.file)||Ue.file;if(Ue.phase==="start"){ii(it,!0),Bt(it);return}if(Ue.phase==="error"){Vt(it),xt.current.get(it)?.reset();return}if(Ue.phase==="success"){ii(it,!1),Ge();return}};return window.addEventListener("finished-downloads:delete",Ee),()=>window.removeEventListener("finished-downloads:delete",Ee)},[Bt,ii,Ge,Vt]),_.useEffect(()=>{const Ee=()=>{Ge()};return window.addEventListener("finished-downloads:reload",Ee),()=>window.removeEventListener("finished-downloads:reload",Ee)},[Ge]),_.useEffect(()=>{const Ee=Ie=>{const Ue=Ie.detail,it=String(Ue?.oldFile??"").trim(),St=String(Ue?.newFile??"").trim();!it||!St||it===St||Si(it,St)};return window.addEventListener("finished-downloads:rename",Ee),()=>window.removeEventListener("finished-downloads:rename",Ee)},[Si]);const hs=_.useMemo(()=>{const Ee=Cs.filter(Ue=>!te.has(Lr(Ue))),Ie=Jt.length?Ee.filter(Ue=>{const it=hr(Ue.output||""),St=Jd(Ue.output),ei=Rr(St),Yt=ni.tagsByModelKey[ei]??[],Ri=Rr([it,Co(it),St,Ue.id,Yt.join(" ")].join(" "));for(const Ti of Jt)if(!Ri.includes(Ti))return!1;return!0}):Ee;return It.size===0?Ie:Ie.filter(Ue=>{const it=Rr(Jd(Ue.output)),St=ni.tagSetByModelKey[it];if(!St||St.size===0)return!1;for(const ei of It)if(!St.has(ei))return!1;return!0})},[Cs,te,It,ni,Jt]),Wi=Mi?hs.length:En,Yi=_.useMemo(()=>{if(!Mi)return hs;const Ee=(y-1)*v,Ie=Ee+v;return hs.slice(Math.max(0,Ee),Math.max(0,Ie))},[Mi,hs,y,v]),_s=!Mi&&Wi===0,Zn=Di&&hs.length===0,Pn=H&&hs.length===0,Qa=ie&&(_s||Pn||Zn);_.useEffect(()=>{if(!Di)return;const Ee=Math.max(1,Math.ceil(hs.length/v));y>Ee&&b(Ee)},[Di,hs.length,y,v,b]),_.useEffect(()=>{if(!(F==="hover"&&!$&&(ht==="cards"||ht==="gallery"||ht==="table"))){I(null),q.current?.disconnect(),q.current=null;return}if(ht==="cards"&&ai?.key){I(ai.key);return}q.current?.disconnect();const Ie=new IntersectionObserver(Ue=>{let it=null,St=0;for(const ei of Ue){if(!ei.isIntersecting)continue;const Yt=le.current.get(ei.target);Yt&&ei.intersectionRatio>St&&(St=ei.intersectionRatio,it=Yt)}it&&I(ei=>ei===it?ei:it)},{threshold:[0,.15,.3,.5,.7,.9],rootMargin:"0px"});q.current=Ie;for(const[Ue,it]of W.current)le.current.set(it,Ue),Ie.observe(it);return()=>{Ie.disconnect(),q.current===Ie&&(q.current=null)}},[ht,F,$,ai?.key]);const wn=Ee=>{const Ie=Lr(Ee),Ue=xe[Ie]??Ee?.durationSeconds;if(typeof Ue=="number"&&Number.isFinite(Ue)&&Ue>0)return a2(Ue*1e3);const it=Date.parse(String(Ee.startedAt||"")),St=Date.parse(String(Ee.endedAt||""));return Number.isFinite(it)&&Number.isFinite(St)&&St>it?a2(St-it):"—"},vs=_.useCallback(Ee=>Ie=>{const Ue=W.current.get(Ee);Ue&&q.current&&q.current.unobserve(Ue),Ie?(W.current.set(Ee,Ie),le.current.set(Ie,Ee),q.current?.observe(Ie)):W.current.delete(Ee)},[]),Ji=_.useCallback((Ee,Ie)=>{if(!Number.isFinite(Ie)||Ie<=0)return;const Ue=Lr(Ee),it=Z.current[Ue];typeof it=="number"&&Math.abs(it-Ie)<.5||(Z.current={...Z.current,[Ue]:Ie},ji())},[ji]),Tr=_.useCallback((Ee,Ie,Ue)=>{if(!Number.isFinite(Ie)||!Number.isFinite(Ue)||Ie<=0||Ue<=0)return;const it=Lr(Ee),St=vt.current[it];St&&St.w===Ie&&St.h===Ue||(vt.current={...vt.current,[it]:{w:Ie,h:Ue}},bi())},[bi]),Ds=o2("(max-width: 639px)");return _.useEffect(()=>{Ds||(xt.current=new Map)},[Ds]),_.useEffect(()=>{_s&&y!==1&&b(1)},[_s,y,b]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:[g.jsxs("div",{className:"flex items-center gap-3 p-3",children:[g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Wi})]}),g.jsxs("div",{className:"sm:hidden flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.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:Wi})]}),g.jsxs("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:[ie?g.jsx(r2,{size:"lg",className:"text-indigo-500",srLabel:"Lade Downloads…"}):null,g.jsxs("div",{className:"hidden sm:flex items-center gap-2 min-w-0 flex-1",children:[g.jsx("input",{value:Gt,onChange:Ee=>yi(Ee.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] `}),(Gt||"").trim()!==""?g.jsx(oi,{size:"sm",variant:"soft",onClick:di,children:"Leeren"}):null]}),g.jsx("div",{className:"hidden sm:block",children:g.jsx(bo,{label:"Behaltene Downloads anzeigen",checked:ye,onChange:Ee=>{y!==1&&b(1),mt(Ee),Ge()}})}),ht!=="table"&&g.jsxs("div",{className:"hidden sm:block",children:[g.jsx("label",{className:"sr-only",htmlFor:"finished-sort",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort",value:E,onChange:Ee=>{const Ie=Ee.target.value;L(Ie),y!==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:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}),g.jsx(oi,{size:Ds?"sm":"md",variant:"soft",className:Ds?"h-9":"h-10",disabled:!j||se,onClick:ft,title:j?`Letzte Aktion rückgängig machen (${j.kind})`:"Keine Aktion zum Rückgängig machen",children:"Undo"}),g.jsx(_O,{value:ht,onChange:Ee=>Et(Ee),size:Ds?"sm":"md",ariaLabel:"Ansicht",items:[{id:"table",icon:g.jsx(fM,{className:Ds?"size-4":"size-5"}),label:Ds?void 0:"Tabelle",srLabel:"Tabelle"},{id:"cards",icon:g.jsx(oM,{className:Ds?"size-4":"size-5"}),label:Ds?void 0:"Cards",srLabel:"Cards"},{id:"gallery",icon:g.jsx(cM,{className:Ds?"size-4":"size-5"}),label:Ds?void 0:"Galerie",srLabel:"Galerie"}]}),g.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:()=>Xe(Ee=>!Ee),"aria-expanded":st,"aria-controls":"finished-mobile-options","aria-label":"Filter & Optionen",children:[g.jsx(wO,{className:"size-5"}),Di||ye?g.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]})]})]}),Pt.length>0?g.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:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Pt.map(Ee=>g.jsx(Ga,{tag:Ee,active:!0,onClick:Zi},Ee)),g.jsx(oi,{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:As,children:"Zurücksetzen"})]})]}):null,g.jsxs("div",{id:"finished-mobile-options",className:["sm:hidden overflow-hidden transition-[max-height,opacity] duration-200 ease-in-out",st?"max-h-[720px] opacity-100":"max-h-0 opacity-0"].join(" "),children:[g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 p-3",children:g.jsxs("div",{className:"space-y-2",children:[g.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:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("input",{value:Gt,onChange:Ee=>yi(Ee.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] `}),(Gt||"").trim()!==""?g.jsx(oi,{size:"sm",variant:"soft",onClick:di,children:"Clear"}):null]})}),g.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:g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-gray-100",children:"Keep anzeigen"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Behaltene Downloads in der Liste"})]}),g.jsx(lx,{checked:ye,onChange:Ee=>{y!==1&&b(1),mt(Ee),Ge()},ariaLabel:"Behaltene Downloads anzeigen",size:"default"})]})}),ht!=="table"?g.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:[g.jsx("div",{className:"text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:"Sortierung"}),g.jsxs("select",{id:"finished-sort-mobile",value:E,onChange:Ee=>{const Ie=Ee.target.value;L(Ie),y!==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:[g.jsx("option",{value:"completed_desc",children:"Fertiggestellt am ↓"}),g.jsx("option",{value:"completed_asc",children:"Fertiggestellt am ↑"}),g.jsx("option",{value:"file_asc",children:"Modelname A→Z"}),g.jsx("option",{value:"file_desc",children:"Modelname Z→A"}),g.jsx("option",{value:"duration_desc",children:"Dauer ↓"}),g.jsx("option",{value:"duration_asc",children:"Dauer ↑"}),g.jsx("option",{value:"size_desc",children:"Größe ↓"}),g.jsx("option",{value:"size_asc",children:"Größe ↑"})]})]}):null]})}),Pt.length>0?g.jsx("div",{className:"border-t border-gray-200/60 dark:border-white/10 px-3 py-2",children:g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:"Tag-Filter"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[Pt.map(Ee=>g.jsx(Ga,{tag:Ee,active:!0,onClick:Zi},Ee)),g.jsx(oi,{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:As,children:"Zurücksetzen"})]})]})}):null]})]})}),Qa?g.jsx(fa,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Lade Downloads…"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Bitte einen Moment."})]}),g.jsx(r2,{size:"lg",className:"text-indigo-500",srLabel:"Lade Downloads…"})]})}):_s||Pn?g.jsx(fa,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"📁"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine abgeschlossenen Downloads"}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Im Zielordner ist aktuell nichts vorhanden."})]})]})}):Zn?g.jsxs(fa,{grayBody:!0,children:[g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Treffer für die aktuellen Filter."}),Pt.length>0||(Gt||"").trim()!==""?g.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Pt.length>0?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:As,children:"Tag-Filter zurücksetzen"}):null,(Gt||"").trim()!==""?g.jsx("button",{type:"button",className:"text-sm font-medium text-gray-700 hover:underline dark:text-gray-200",onClick:di,children:"Suche zurücksetzen"}):null]}):null]}):g.jsxs(g.Fragment,{children:[ht==="cards"&&g.jsx($M,{rows:Yi,isSmall:Ds,isLoading:ie,blurPreviews:t,durations:xe,teaserKey:D,teaserPlayback:F,teaserAudio:n,hoverTeaserKey:Q,inlinePlay:ai,setInlinePlay:Fi,deletingKeys:G,keepingKeys:Kt,removingKeys:mn,swipeRefs:xt,keyFor:Lr,baseName:hr,modelNameFromOutput:Jd,runtimeOf:wn,sizeBytesOf:By,formatBytes:Py,lower:Rr,onOpenPlayer:r,openPlayer:Hi,startInline:$i,tryAutoplayInline:$s,registerTeaserHost:vs,handleDuration:Ji,deleteVideo:Ut,keepVideo:zi,releasePlayingFile:mi,modelsByKey:N,onToggleHot:Ss,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:It,onToggleTagFilter:Zi,onHoverPreviewKeyChange:K,assetNonce:S??0}),ht==="table"&&g.jsx(QM,{rows:Yi,isLoading:ie,keyFor:Lr,baseName:hr,lower:Rr,modelNameFromOutput:Jd,runtimeOf:wn,sizeBytesOf:By,formatBytes:Py,resolutions:Te,durations:xe,canHover:$,teaserAudio:n,hoverTeaserKey:Q,setHoverTeaserKey:K,teaserPlayback:F,teaserKey:D,registerTeaserHost:vs,handleDuration:Ji,handleResolution:Tr,blurPreviews:t,assetNonce:S,deletingKeys:G,keepingKeys:Kt,removingKeys:mn,modelsByKey:N,activeTagSet:It,onToggleTagFilter:Zi,onOpenPlayer:r,onSortModeChange:L,page:y,onPageChange:b,onToggleHot:Ss,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,deleteVideo:Ut,keepVideo:zi}),ht==="gallery"&&g.jsx(ZM,{rows:Yi,isLoading:ie,blurPreviews:t,durations:xe,handleDuration:Ji,teaserKey:D,teaserPlayback:F,teaserAudio:n,hoverTeaserKey:Q,keyFor:Lr,baseName:hr,modelNameFromOutput:Jd,runtimeOf:wn,sizeBytesOf:By,formatBytes:Py,deletingKeys:G,keepingKeys:Kt,removingKeys:mn,deletedKeys:te,registerTeaserHost:vs,onOpenPlayer:r,deleteVideo:Ut,keepVideo:zi,onToggleHot:Ss,lower:Rr,modelsByKey:N,onToggleFavorite:c,onToggleLike:d,onToggleWatch:f,activeTagSet:It,onToggleTagFilter:Zi,onHoverPreviewKeyChange:K}),g.jsx(XA,{page:y,pageSize:v,totalItems:Wi,onPageChange:Ee=>{Oc.flushSync(()=>{Fi(null),I(null),K(null)});for(const Ie of Yi){const Ue=hr(Ie.output||"");Ue&&(window.dispatchEvent(new CustomEvent("player:release",{detail:{file:Ue}})),window.dispatchEvent(new CustomEvent("player:close",{detail:{file:Ue}})))}window.scrollTo({top:0,behavior:"auto"}),b(Ee)},showSummary:!1,prevLabel:"Zurück",nextLabel:"Weiter",className:"mt-4"})]})]})}var Fy,l2;function op(){if(l2)return Fy;l2=1;var s;return typeof window<"u"?s=window:typeof u0<"u"?s=u0:typeof self<"u"?s=self:s={},Fy=s,Fy}var d3=op();const he=Wc(d3),h3={},f3=Object.freeze(Object.defineProperty({__proto__:null,default:h3},Symbol.toStringTag,{value:"Module"})),m3=GI(f3);var Uy,u2;function JA(){if(u2)return Uy;u2=1;var s=typeof u0<"u"?u0:typeof window<"u"?window:{},e=m3,t;return typeof document<"u"?t=document:(t=s["__GLOBAL_DOCUMENT_CACHE@4"],t||(t=s["__GLOBAL_DOCUMENT_CACHE@4"]=e)),Uy=t,Uy}var p3=JA();const yt=Wc(p3);var _m={exports:{}},jy={exports:{}},c2;function g3(){return c2||(c2=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 a=Object.prototype.toString.call(n).slice(8,-1);if(a==="Object"&&n.constructor&&(a=n.constructor.name),a==="Map"||a==="Set")return Array.from(n);if(a==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a))return t(n,r)}}function t(n,r){(r==null||r>n.length)&&(r=n.length);for(var a=0,u=new Array(r);a=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 a=r.split("="),u=a[0],c=a[1];return u.trim()==="charset"?c.trim():n},"utf-8")}return Gy=e,Gy}var p2;function T3(){if(p2)return _m.exports;p2=1;var s=op(),e=g3(),t=y3(),i=v3(),n=x3();d.httpHandler=b3(),d.requestInterceptorsStorage=new i,d.responseInterceptorsStorage=new i,d.retryManager=new n;var r=function(b){var S={};return b&&b.trim().split(` `).forEach(function(E){var L=E.indexOf(":"),N=E.slice(0,L).trim().toLowerCase(),R=E.slice(L+1).trim();typeof S[N]>"u"?S[N]=R:Array.isArray(S[N])?S[N].push(R):S[N]=[S[N],R]}),S};_m.exports=d,_m.exports.default=d,d.XMLHttpRequest=s.XMLHttpRequest||y,d.XDomainRequest="withCredentials"in new d.XMLHttpRequest?d.XMLHttpRequest:s.XDomainRequest,a(["get","put","post","patch","head","delete"],function(v){d[v==="delete"?"del":v]=function(b,S,E){return S=c(b,S,E),S.method=v.toUpperCase(),f(S)}});function a(v,b){for(var S=0;S"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},S=d.requestInterceptorsStorage.execute(v.requestType,b);v.uri=S.uri,v.headers=S.headers,v.body=S.body,v.metadata=S.metadata,v.retry=S.retry,v.timeout=S.timeout}var E=!1,L=function(J,ie,oe){E||(E=!0,v.callback(J,ie,oe))};function N(){$.readyState===4&&!d.responseInterceptorsStorage.getIsEnabled()&&setTimeout(F,0)}function R(){var G=void 0;if($.response?G=$.response:G=$.responseText||p($),le)try{G=JSON.parse(G)}catch{}return G}function H(G){if(clearTimeout(te),clearTimeout(v.retryTimeout),G instanceof Error||(G=new Error(""+(G||"Unknown XMLHttpRequest Error"))),G.statusCode=0,!W&&d.retryManager.getIsEnabled()&&v.retry&&v.retry.shouldRetry()){v.retryTimeout=setTimeout(function(){v.retry.moveToNextAttempt(),v.xhr=$,f(v)},v.retry.getCurrentFuzzedDelay());return}if(v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var J={headers:V.headers||{},body:V.body,responseUrl:$.responseURL,responseType:$.responseType},ie=d.responseInterceptorsStorage.execute(v.requestType,J);V.body=ie.body,V.headers=ie.headers}return L(G,V)}function F(){if(!W){var G;clearTimeout(te),clearTimeout(v.retryTimeout),v.useXDR&&$.status===void 0?G=200:G=$.status===1223?204:$.status;var J=V,ie=null;if(G!==0?(J={body:R(),statusCode:G,method:I,headers:{},url:D,rawRequest:$},$.getAllResponseHeaders&&(J.headers=r($.getAllResponseHeaders()))):ie=new Error("Internal XMLHttpRequest Error"),v.requestType&&d.responseInterceptorsStorage.getIsEnabled()){var oe={headers:J.headers||{},body:J.body,responseUrl:$.responseURL,responseType:$.responseType},j=d.responseInterceptorsStorage.execute(v.requestType,oe);J.body=j.body,J.headers=j.headers}return L(ie,J,J.body)}}var $=v.xhr||null;$||(v.cors||v.useXDR?$=new d.XDomainRequest:$=new d.XMLHttpRequest);var M,W,D=$.url=v.uri||v.url,I=$.method=v.method||"GET",Q=v.body||v.data,K=$.headers=v.headers||{},q=!!v.sync,le=!1,te,V={body:void 0,headers:{},statusCode:0,method:I,url:D,rawRequest:$};if("json"in v&&v.json!==!1&&(le=!0,K.accept||K.Accept||(K.Accept="application/json"),I!=="GET"&&I!=="HEAD"&&(K["content-type"]||K["Content-Type"]||(K["Content-Type"]="application/json"),Q=JSON.stringify(v.json===!0?Q:v.json))),$.onreadystatechange=N,$.onload=F,$.onerror=H,$.onprogress=function(){},$.onabort=function(){W=!0,clearTimeout(v.retryTimeout)},$.ontimeout=H,$.open(I,D,!q,v.username,v.password),q||($.withCredentials=!!v.withCredentials),!q&&v.timeout>0&&(te=setTimeout(function(){if(!W){W=!0,$.abort("timeout");var G=new Error("XMLHttpRequest timeout");G.code="ETIMEDOUT",H(G)}},v.timeout)),$.setRequestHeader)for(M in K)K.hasOwnProperty(M)&&$.setRequestHeader(M,K[M]);else if(v.headers&&!u(v.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in v&&($.responseType=v.responseType),"beforeSend"in v&&typeof v.beforeSend=="function"&&v.beforeSend($),$.send(Q||null),$}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 y(){}return _m.exports}var S3=T3();const ek=Wc(S3);var Vy={exports:{}},qy,g2;function _3(){if(g2)return qy;g2=1;var s=JA(),e=Object.create||(function(){function D(){}return function(I){if(arguments.length!==1)throw new Error("Object.create shim only accepts one parameter.");return D.prototype=I,new D}})();function t(D,I){this.name="ParsingError",this.code=D.code,this.message=I||D.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(D){function I(K,q,le,te){return(K|0)*3600+(q|0)*60+(le|0)+(te|0)/1e3}var Q=D.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return Q?Q[3]?I(Q[1],Q[2],Q[3].replace(":",""),Q[4]):Q[1]>59?I(Q[1],Q[2],0,Q[4]):I(0,Q[1],Q[2],Q[4]):null}function n(){this.values=e(null)}n.prototype={set:function(D,I){!this.get(D)&&I!==""&&(this.values[D]=I)},get:function(D,I,Q){return Q?this.has(D)?this.values[D]:I[Q]:this.has(D)?this.values[D]:I},has:function(D){return D in this.values},alt:function(D,I,Q){for(var K=0;K=0&&I<=100)?(this.set(D,I),!0):!1}};function r(D,I,Q,K){var q=K?D.split(K):[D];for(var le in q)if(typeof q[le]=="string"){var te=q[le].split(Q);if(te.length===2){var V=te[0].trim(),G=te[1].trim();I(V,G)}}}function a(D,I,Q){var K=D;function q(){var V=i(D);if(V===null)throw new t(t.Errors.BadTimeStamp,"Malformed timestamp: "+K);return D=D.replace(/^[^\sa-zA-Z-]+/,""),V}function le(V,G){var J=new n;r(V,function(ie,oe){switch(ie){case"region":for(var j=Q.length-1;j>=0;j--)if(Q[j].id===oe){J.set(ie,Q[j].region);break}break;case"vertical":J.alt(ie,oe,["rl","lr"]);break;case"line":var X=oe.split(","),se=X[0];J.integer(ie,se),J.percent(ie,se)&&J.set("snapToLines",!1),J.alt(ie,se,["auto"]),X.length===2&&J.alt("lineAlign",X[1],["start","center","end"]);break;case"position":X=oe.split(","),J.percent(ie,X[0]),X.length===2&&J.alt("positionAlign",X[1],["start","center","end"]);break;case"size":J.percent(ie,oe);break;case"align":J.alt(ie,oe,["start","center","end","left","right"]);break}},/:/,/\s/),G.region=J.get("region",null),G.vertical=J.get("vertical","");try{G.line=J.get("line","auto")}catch{}G.lineAlign=J.get("lineAlign","start"),G.snapToLines=J.get("snapToLines",!0),G.size=J.get("size",100);try{G.align=J.get("align","center")}catch{G.align=J.get("align","middle")}try{G.position=J.get("position","auto")}catch{G.position=J.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},G.align)}G.positionAlign=J.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},G.align)}function te(){D=D.replace(/^\s+/,"")}if(te(),I.startTime=q(),te(),D.substr(0,3)!=="-->")throw new t(t.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+K);D=D.substr(3),te(),I.endTime=q(),te(),le(D,I)}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 y(D,I){function Q(){if(!I)return null;function se(pe){return I=I.substr(pe.length),pe}var fe=I.match(/^([^<]*)(<[^>]*>?)?/);return se(fe[1]?fe[1]:fe[2])}function K(se){return u.innerHTML=se,se=u.textContent,u.textContent="",se}function q(se,fe){return!p[fe.localName]||p[fe.localName]===se.localName}function le(se,fe){var pe=c[se];if(!pe)return null;var de=D.document.createElement(pe),Ve=f[se];return Ve&&fe&&(de[Ve]=fe.trim()),de}for(var te=D.document.createElement("div"),V=te,G,J=[];(G=Q())!==null;){if(G[0]==="<"){if(G[1]==="/"){J.length&&J[J.length-1]===G.substr(2).replace(">","")&&(J.pop(),V=V.parentNode);continue}var ie=i(G.substr(1,G.length-2)),oe;if(ie){oe=D.document.createProcessingInstruction("timestamp",ie),V.appendChild(oe);continue}var j=G.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!j||(oe=le(j[1],j[3]),!oe)||!q(V,oe))continue;if(j[2]){var X=j[2].split(".");X.forEach(function(se){var fe=/^bg_/.test(se),pe=fe?se.slice(3):se;if(d.hasOwnProperty(pe)){var de=fe?"background-color":"color",Ve=d[pe];oe.style[de]=Ve}}),oe.className=X.join(" ")}J.push(j[1]),V.appendChild(oe),V=oe;continue}V.appendChild(D.document.createTextNode(K(G)))}return te}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(D){for(var I=0;I=Q[0]&&D<=Q[1])return!0}return!1}function S(D){var I=[],Q="",K;if(!D||!D.childNodes)return"ltr";function q(V,G){for(var J=G.childNodes.length-1;J>=0;J--)V.push(G.childNodes[J])}function le(V){if(!V||!V.length)return null;var G=V.pop(),J=G.textContent||G.innerText;if(J){var ie=J.match(/^.*(\n|\r)/);return ie?(V.length=0,ie[0]):J}if(G.tagName==="ruby")return le(V);if(G.childNodes)return q(V,G),le(V)}for(q(I,D);Q=le(I);)for(var te=0;te=0&&D.line<=100))return D.line;if(!D.track||!D.track.textTrackList||!D.track.textTrackList.mediaElement)return-1;for(var I=D.track,Q=I.textTrackList,K=0,q=0;qD.left&&this.topD.top},R.prototype.overlapsAny=function(D){for(var I=0;I=D.top&&this.bottom<=D.bottom&&this.left>=D.left&&this.right<=D.right},R.prototype.overlapsOppositeAxis=function(D,I){switch(I){case"+x":return this.leftD.right;case"+y":return this.topD.bottom}},R.prototype.intersectPercentage=function(D){var I=Math.max(0,Math.min(this.right,D.right)-Math.max(this.left,D.left)),Q=Math.max(0,Math.min(this.bottom,D.bottom)-Math.max(this.top,D.top)),K=I*Q;return K/(this.height*this.width)},R.prototype.toCSSCompatValues=function(D){return{top:this.top-D.top,bottom:D.bottom-this.bottom,left:this.left-D.left,right:D.right-this.right,height:this.height,width:this.width}},R.getSimpleBoxPosition=function(D){var I=D.div?D.div.offsetHeight:D.tagName?D.offsetHeight:0,Q=D.div?D.div.offsetWidth:D.tagName?D.offsetWidth:0,K=D.div?D.div.offsetTop:D.tagName?D.offsetTop:0;D=D.div?D.div.getBoundingClientRect():D.tagName?D.getBoundingClientRect():D;var q={left:D.left,right:D.right,top:D.top||K,height:D.height||I,bottom:D.bottom||K+(D.height||I),width:D.width||Q};return q};function H(D,I,Q,K){function q(pe,de){for(var Ve,Ze=new R(pe),Je=1,Pe=0;PeFe&&(Ve=new R(pe),Je=Fe),pe=new R(Ze)}return Ve||Ze}var le=new R(I),te=I.cue,V=E(te),G=[];if(te.snapToLines){var J;switch(te.vertical){case"":G=["+y","-y"],J="height";break;case"rl":G=["+x","-x"],J="width";break;case"lr":G=["-x","+x"],J="width";break}var ie=le.lineHeight,oe=ie*Math.round(V),j=Q[J]+ie,X=G[0];Math.abs(oe)>j&&(oe=oe<0?-1:1,oe*=Math.ceil(j/ie)*ie),V<0&&(oe+=te.vertical===""?Q.height:Q.width,G=G.reverse()),le.move(X,oe)}else{var se=le.lineHeight/Q.height*100;switch(te.lineAlign){case"center":V-=se/2;break;case"end":V-=se;break}switch(te.vertical){case"":I.applyStyles({top:I.formatStyle(V,"%")});break;case"rl":I.applyStyles({left:I.formatStyle(V,"%")});break;case"lr":I.applyStyles({right:I.formatStyle(V,"%")});break}G=["+y","-x","+x","-y"],le=new R(I)}var fe=q(le,G);I.move(fe.toCSSCompatValues(Q))}function F(){}F.StringDecoder=function(){return{decode:function(D){if(!D)return"";if(typeof D!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(D))}}},F.convertCueToDOMTree=function(D,I){return!D||!I?null:y(D,I)};var $=.05,M="sans-serif",W="1.5%";return F.processCues=function(D,I,Q){if(!D||!I||!Q)return null;for(;Q.firstChild;)Q.removeChild(Q.firstChild);var K=D.document.createElement("div");K.style.position="absolute",K.style.left="0",K.style.right="0",K.style.top="0",K.style.bottom="0",K.style.margin=W,Q.appendChild(K);function q(ie){for(var oe=0;oe")===-1){I.cue.id=te;continue}case"CUE":try{a(te,I.cue,I.regionList)}catch(ie){I.reportOrThrowError(ie),I.cue=null,I.state="BADCUE";continue}I.state="CUETEXT";continue;case"CUETEXT":var J=te.indexOf("-->")!==-1;if(!te||J&&(G=!0)){I.oncue&&I.oncue(I.cue),I.cue=null,I.state="ID";continue}I.cue.text&&(I.cue.text+=` `),I.cue.text+=te.replace(/\u2028/g,` `).replace(/u2029/g,` `);continue;case"BADCUE":te||(I.state="ID");continue}}}catch(ie){I.reportOrThrowError(ie),I.state==="CUETEXT"&&I.cue&&I.oncue&&I.oncue(I.cue),I.cue=null,I.state=I.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this},flush:function(){var D=this;try{if(D.buffer+=D.decoder.decode(),(D.cue||D.state==="HEADER")&&(D.buffer+=` `,D.parse()),D.state==="INITIAL")throw new t(t.Errors.BadSignature)}catch(I){D.reportOrThrowError(I)}return D.onflush&&D.onflush(),this}},qy=F,qy}var Ky,y2;function E3(){if(y2)return Ky;y2=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(a){if(typeof a!="string")return!1;var u=e[a.toLowerCase()];return u?a.toLowerCase():!1}function n(a){if(typeof a!="string")return!1;var u=t[a.toLowerCase()];return u?a.toLowerCase():!1}function r(a,u,c){this.hasBeenReset=!1;var d="",f=!1,p=a,y=u,v=c,b=null,S="",E=!0,L="auto",N="start",R="auto",H="auto",F=100,$="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 y},set:function(M){if(typeof M!="number")throw new TypeError("End time must be set to a number.");y=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 S},set:function(M){var W=i(M);if(W===!1)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");S=W,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return E},set:function(M){E=!!M,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return L},set:function(M){if(typeof M!="number"&&M!==s)throw new SyntaxError("Line: an invalid number or illegal string was specified.");L=M,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return N},set:function(M){var W=n(M);W?(N=W,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return R},set:function(M){if(M<0||M>100)throw new Error("Position must be between 0 and 100.");R=M,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return H},set:function(M){var W=n(M);W?(H=W,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return F},set:function(M){if(M<0||M>100)throw new Error("Size must be between 0 and 100.");F=M,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return $},set:function(M){var W=n(M);if(!W)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");$=W,this.hasBeenReset=!0}}}),this.displayState=void 0}return r.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},Ky=r,Ky}var Wy,v2;function w3(){if(v2)return Wy;v2=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,a=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 a},set:function(p){if(!t(p))throw new Error("RegionAnchorY must be between 0 and 100.");a=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 y=e(p);y===!1?console.warn("Scroll: an invalid or illegal string was specified."):f=y}}})}return Wy=i,Wy}var x2;function A3(){if(x2)return Vy.exports;x2=1;var s=op(),e=Vy.exports={WebVTT:_3(),VTTCue:E3(),VTTRegion:w3()};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(),Vy.exports}var k3=A3();const b2=Wc(k3);function sn(){return sn=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,a=0;a-1;t=this.buffer.indexOf(` `))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const L3=" ",Yy=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},R3=function(){const t="(?:"+"[^=]*"+")=(?:"+'"[^"]*"|[^,]*'+")";return new RegExp("(?:^|,)("+t+")")},Kn=function(s){const e={};if(!s)return e;const t=s.split(R3());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},S2=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 I3 extends gb{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,a)=>{const u=a(e);return u===e?r:r.concat([u])},[e]).forEach(r=>{for(let a=0;ar),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 N3=s=>s.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),hl=function(s){const e={};return Object.keys(s).forEach(function(t){e[N3(t)]=s[t]}),e},Xy=function(s){const{serverControl:e,targetDuration:t,partTargetDuration:i}=s;if(!e)return;const n="#EXT-X-SERVER-CONTROL",r="holdBack",a="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&&a&&(n.key=a),!n.timeline&&typeof p=="number"&&(n.timeline=p),this.manifest.preloadSegment=n)}),this.parseStream.on("data",function(S){let E,L;if(t.manifest.definitions){for(const N in t.manifest.definitions)if(S.uri&&(S.uri=S.uri.replace(`{$${N}}`,t.manifest.definitions[N])),S.attributes)for(const R in S.attributes)typeof S.attributes[R]=="string"&&(S.attributes[R]=S.attributes[R].replace(`{$${N}}`,t.manifest.definitions[N]))}({tag(){({version(){S.version&&(this.manifest.version=S.version)},"allow-cache"(){this.manifest.allowCache=S.allowed,"allowed"in S||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const N={};"length"in S&&(n.byterange=N,N.length=S.length,"offset"in S||(S.offset=y)),"offset"in S&&(n.byterange=N,N.offset=S.offset),y=N.offset+N.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"})),S.title&&(n.title=S.title),S.duration>0&&(n.duration=S.duration),S.duration===0&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(!S.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if(S.attributes.METHOD==="NONE"){a=null;return}if(!S.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if(S.attributes.KEYFORMAT==="com.apple.streamingkeydelivery"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:S.attributes};return}if(S.attributes.KEYFORMAT==="com.microsoft.playready"){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:S.attributes.URI};return}if(S.attributes.KEYFORMAT===f){if(["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(S.attributes.METHOD)===-1){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if(S.attributes.METHOD==="SAMPLE-AES-CENC"&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),S.attributes.URI.substring(0,23)!=="data:text/plain;base64,"){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(S.attributes.KEYID&&S.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:S.attributes.KEYFORMAT,keyId:S.attributes.KEYID.substring(2)},pssh:tk(S.attributes.URI.split(",")[1])};return}S.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),a={method:S.attributes.METHOD||"AES-128",uri:S.attributes.URI},typeof S.attributes.IV<"u"&&(a.iv=S.attributes.IV)},"media-sequence"(){if(!isFinite(S.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+S.number});return}this.manifest.mediaSequence=S.number},"discontinuity-sequence"(){if(!isFinite(S.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+S.number});return}this.manifest.discontinuitySequence=S.number,p=S.number},"playlist-type"(){if(!/VOD|EVENT/.test(S.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+S.playlist});return}this.manifest.playlistType=S.playlistType},map(){r={},S.uri&&(r.uri=S.uri),S.byterange&&(r.byterange=S.byterange),a&&(r.key=a)},"stream-inf"(){if(this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!S.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}n.attributes||(n.attributes={}),sn(n.attributes,S.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(S.attributes&&S.attributes.TYPE&&S.attributes["GROUP-ID"]&&S.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}const N=this.manifest.mediaGroups[S.attributes.TYPE];N[S.attributes["GROUP-ID"]]=N[S.attributes["GROUP-ID"]]||{},E=N[S.attributes["GROUP-ID"]],L={default:/yes/i.test(S.attributes.DEFAULT)},L.default?L.autoselect=!0:L.autoselect=/yes/i.test(S.attributes.AUTOSELECT),S.attributes.LANGUAGE&&(L.language=S.attributes.LANGUAGE),S.attributes.URI&&(L.uri=S.attributes.URI),S.attributes["INSTREAM-ID"]&&(L.instreamId=S.attributes["INSTREAM-ID"]),S.attributes.CHARACTERISTICS&&(L.characteristics=S.attributes.CHARACTERISTICS),S.attributes.FORCED&&(L.forced=/yes/i.test(S.attributes.FORCED)),E[S.attributes.NAME]=L},discontinuity(){p+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){typeof this.manifest.dateTimeString>"u"&&(this.manifest.dateTimeString=S.dateTimeString,this.manifest.dateTimeObject=S.dateTimeObject),n.dateTimeString=S.dateTimeString,n.dateTimeObject=S.dateTimeObject;const{lastProgramDateTime:N}=this;this.lastProgramDateTime=new Date(S.dateTimeString).getTime(),N===null&&this.manifest.segments.reduceRight((R,H)=>(H.programDateTime=R-H.duration*1e3,H.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(S.duration)||S.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+S.duration});return}this.manifest.targetDuration=S.duration,Xy.call(this,this.manifest)},start(){if(!S.attributes||isNaN(S.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:S.attributes["TIME-OFFSET"],precise:S.attributes.PRECISE}},"cue-out"(){n.cueOut=S.data},"cue-out-cont"(){n.cueOutCont=S.data},"cue-in"(){n.cueIn=S.data},skip(){this.manifest.skip=hl(S.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",S.attributes,["SKIPPED-SEGMENTS"])},part(){u=!0;const N=this.manifest.segments.length,R=hl(S.attributes);n.parts=n.parts||[],n.parts.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=v),v=R.byterange.offset+R.byterange.length);const H=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${H} for segment #${N}`,S.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((F,$)=>{F.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${$} lacks required attribute(s): LAST-PART`})})},"server-control"(){const N=this.manifest.serverControl=hl(S.attributes);N.hasOwnProperty("canBlockReload")||(N.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),Xy.call(this,this.manifest),N.canSkipDateranges&&!N.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 N=this.manifest.segments.length,R=hl(S.attributes),H=R.type&&R.type==="PART";n.preloadHints=n.preloadHints||[],n.preloadHints.push(R),R.byterange&&(R.byterange.hasOwnProperty("offset")||(R.byterange.offset=H?v:0,H&&(v=R.byterange.offset+R.byterange.length)));const F=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${F} for segment #${N}`,S.attributes,["TYPE","URI"]),!!R.type)for(let $=0;$$.id===R.id);this.manifest.dateRanges[F]=sn(this.manifest.dateRanges[F],R),b[R.id]=sn(b[R.id],R),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=hl(S.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",S.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const N=(R,H)=>{if(R in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${R}`});return}this.manifest.definitions[R]=H};if("QUERYPARAM"in S.attributes){if("NAME"in S.attributes||"IMPORT"in S.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}const R=this.params.get(S.attributes.QUERYPARAM);if(!R){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${S.attributes.QUERYPARAM}`});return}N(S.attributes.QUERYPARAM,decodeURIComponent(R));return}if("NAME"in S.attributes){if("IMPORT"in S.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in S.attributes)||typeof S.attributes.VALUE!="string"){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${S.attributes.NAME}`});return}N(S.attributes.NAME,S.attributes.VALUE);return}if("IMPORT"in S.attributes){if(!this.mainDefinitions[S.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${S.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}N(S.attributes.IMPORT,this.mainDefinitions[S.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:S.attributes,uri:S.uri,timeline:p}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",S.attributes,["BANDWIDTH","URI"])}}[S.tagType]||c).call(t)},uri(){n.uri=S.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),a&&(n.key=a),n.timeline=p,r&&(n.map=r),v=0,this.lastProgramDateTime!==null&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=n.duration*1e3),n={}},comment(){},custom(){S.segment?(n.custom=n.custom||{},n.custom[S.customType]=S.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[S.customType]=S.data)}})[S.type].call(t)})}requiredCompatibilityversion(e,t){(ep&&(f-=p,f-=p,f-=In(2))}return Number(f)},V3=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=In(e);for(var a=H3(e),u=new Uint8Array(new ArrayBuffer(a)),c=0;c=t.length&&d.call(t,function(f,p){var y=c[p]?c[p]&e[a+p]:e[a+p];return f===y})},K3=function(e,t,i){t.forEach(function(n){for(var r in e.mediaGroups[n])for(var a in e.mediaGroups[n][r]){var u=e.mediaGroups[n][r][a];i(u,n,r,a)}})},eh={},go={},iu={},w2;function up(){if(w2)return iu;w2=1;function s(r,a,u){if(u===void 0&&(u=Array.prototype),r&&typeof u.find=="function")return u.find.call(r,a);for(var c=0;c=0&&B=0){for(var Ke=Z.length-1;Te0},lookupPrefix:function(B){for(var Z=this;Z;){var re=Z._nsMap;if(re){for(var Te in re)if(Object.prototype.hasOwnProperty.call(re,Te)&&re[Te]===B)return Te}Z=Z.nodeType==y?Z.ownerDocument:Z.parentNode}return null},lookupNamespaceURI:function(B){for(var Z=this;Z;){var re=Z._nsMap;if(re&&Object.prototype.hasOwnProperty.call(re,B))return re[B];Z=Z.nodeType==y?Z.ownerDocument:Z.parentNode}return null},isDefaultNamespace:function(B){var Z=this.lookupPrefix(B);return Z==null}};function X(B){return B=="<"&&"<"||B==">"&&">"||B=="&"&&"&"||B=='"'&&"""||"&#"+B.charCodeAt()+";"}c(f,j),c(f,j.prototype);function se(B,Z){if(Z(B))return!0;if(B=B.firstChild)do if(se(B,Z))return!0;while(B=B.nextSibling)}function fe(){this.ownerDocument=this}function pe(B,Z,re){B&&B._inc++;var Te=re.namespaceURI;Te===t.XMLNS&&(Z._nsMap[re.prefix?re.localName:""]=re.value)}function de(B,Z,re,Te){B&&B._inc++;var Ke=re.namespaceURI;Ke===t.XMLNS&&delete Z._nsMap[re.prefix?re.localName:""]}function Ve(B,Z,re){if(B&&B._inc){B._inc++;var Te=Z.childNodes;if(re)Te[Te.length++]=re;else{for(var Ke=Z.firstChild,vt=0;Ke;)Te[vt++]=Ke,Ke=Ke.nextSibling;Te.length=vt,delete Te[Te.length]}}}function Ze(B,Z){var re=Z.previousSibling,Te=Z.nextSibling;return re?re.nextSibling=Te:B.firstChild=Te,Te?Te.previousSibling=re:B.lastChild=re,Z.parentNode=null,Z.previousSibling=null,Z.nextSibling=null,Ve(B.ownerDocument,B),Z}function Je(B){return B&&(B.nodeType===j.DOCUMENT_NODE||B.nodeType===j.DOCUMENT_FRAGMENT_NODE||B.nodeType===j.ELEMENT_NODE)}function Pe(B){return B&&(qe(B)||dt(B)||Fe(B)||B.nodeType===j.DOCUMENT_FRAGMENT_NODE||B.nodeType===j.COMMENT_NODE||B.nodeType===j.PROCESSING_INSTRUCTION_NODE)}function Fe(B){return B&&B.nodeType===j.DOCUMENT_TYPE_NODE}function qe(B){return B&&B.nodeType===j.ELEMENT_NODE}function dt(B){return B&&B.nodeType===j.TEXT_NODE}function Ge(B,Z){var re=B.childNodes||[];if(e(re,qe)||Fe(Z))return!1;var Te=e(re,Fe);return!(Z&&Te&&re.indexOf(Te)>re.indexOf(Z))}function At(B,Z){var re=B.childNodes||[];function Te(vt){return qe(vt)&&vt!==Z}if(e(re,Te))return!1;var Ke=e(re,Fe);return!(Z&&Ke&&re.indexOf(Ke)>re.indexOf(Z))}function lt(B,Z,re){if(!Je(B))throw new K(D,"Unexpected parent node type "+B.nodeType);if(re&&re.parentNode!==B)throw new K(I,"child not in parent");if(!Pe(Z)||Fe(Z)&&B.nodeType!==j.DOCUMENT_NODE)throw new K(D,"Unexpected node type "+Z.nodeType+" for parent node type "+B.nodeType)}function bt(B,Z,re){var Te=B.childNodes||[],Ke=Z.childNodes||[];if(Z.nodeType===j.DOCUMENT_FRAGMENT_NODE){var vt=Ke.filter(qe);if(vt.length>1||e(Ke,dt))throw new K(D,"More than one element or text in fragment");if(vt.length===1&&!Ge(B,re))throw new K(D,"Element in fragment can not be inserted before doctype")}if(qe(Z)&&!Ge(B,re))throw new K(D,"Only one element can be added and only after doctype");if(Fe(Z)){if(e(Te,Fe))throw new K(D,"Only one doctype is allowed");var Tt=e(Te,qe);if(re&&Te.indexOf(Tt)1||e(Ke,dt))throw new K(D,"More than one element or text in fragment");if(vt.length===1&&!At(B,re))throw new K(D,"Element in fragment can not be inserted before doctype")}if(qe(Z)&&!At(B,re))throw new K(D,"Only one element can be added and only after doctype");if(Fe(Z)){let bi=function(ji){return Fe(ji)&&ji!==re};var Li=bi;if(e(Te,bi))throw new K(D,"Only one doctype is allowed");var Tt=e(Te,qe);if(re&&Te.indexOf(Tt)0&&se(re.documentElement,function(Ke){if(Ke!==re&&Ke.nodeType===p){var vt=Ke.getAttribute("class");if(vt){var Tt=B===vt;if(!Tt){var Li=a(vt);Tt=Z.every(u(Li))}Tt&&Te.push(Ke)}}}),Te})},createElement:function(B){var Z=new ye;Z.ownerDocument=this,Z.nodeName=B,Z.tagName=B,Z.localName=B,Z.childNodes=new q;var re=Z.attributes=new V;return re._ownerElement=Z,Z},createDocumentFragment:function(){var B=new Gt;return B.ownerDocument=this,B.childNodes=new q,B},createTextNode:function(B){var Z=new Xe;return Z.ownerDocument=this,Z.appendData(B),Z},createComment:function(B){var Z=new xt;return Z.ownerDocument=this,Z.appendData(B),Z},createCDATASection:function(B){var Z=new ft;return Z.ownerDocument=this,Z.appendData(B),Z},createProcessingInstruction:function(B,Z){var re=new yi;return re.ownerDocument=this,re.tagName=re.nodeName=re.target=B,re.nodeValue=re.data=Z,re},createAttribute:function(B){var Z=new mt;return Z.ownerDocument=this,Z.name=B,Z.nodeName=B,Z.localName=B,Z.specified=!0,Z},createEntityReference:function(B){var Z=new ni;return Z.ownerDocument=this,Z.nodeName=B,Z},createElementNS:function(B,Z){var re=new ye,Te=Z.split(":"),Ke=re.attributes=new V;return re.childNodes=new q,re.ownerDocument=this,re.nodeName=Z,re.tagName=Z,re.namespaceURI=B,Te.length==2?(re.prefix=Te[0],re.localName=Te[1]):re.localName=Z,Ke._ownerElement=re,re},createAttributeNS:function(B,Z){var re=new mt,Te=Z.split(":");return re.ownerDocument=this,re.nodeName=Z,re.name=Z,re.namespaceURI=B,re.specified=!0,Te.length==2?(re.prefix=Te[0],re.localName=Te[1]):re.localName=Z,re}},d(fe,j);function ye(){this._nsMap={}}ye.prototype={nodeType:p,hasAttribute:function(B){return this.getAttributeNode(B)!=null},getAttribute:function(B){var Z=this.getAttributeNode(B);return Z&&Z.value||""},getAttributeNode:function(B){return this.attributes.getNamedItem(B)},setAttribute:function(B,Z){var re=this.ownerDocument.createAttribute(B);re.value=re.nodeValue=""+Z,this.setAttributeNode(re)},removeAttribute:function(B){var Z=this.getAttributeNode(B);Z&&this.removeAttributeNode(Z)},appendChild:function(B){return B.nodeType===F?this.insertBefore(B,null):Et(this,B)},setAttributeNode:function(B){return this.attributes.setNamedItem(B)},setAttributeNodeNS:function(B){return this.attributes.setNamedItemNS(B)},removeAttributeNode:function(B){return this.attributes.removeNamedItem(B.nodeName)},removeAttributeNS:function(B,Z){var re=this.getAttributeNodeNS(B,Z);re&&this.removeAttributeNode(re)},hasAttributeNS:function(B,Z){return this.getAttributeNodeNS(B,Z)!=null},getAttributeNS:function(B,Z){var re=this.getAttributeNodeNS(B,Z);return re&&re.value||""},setAttributeNS:function(B,Z,re){var Te=this.ownerDocument.createAttributeNS(B,Z);Te.value=Te.nodeValue=""+re,this.setAttributeNode(Te)},getAttributeNodeNS:function(B,Z){return this.attributes.getNamedItemNS(B,Z)},getElementsByTagName:function(B){return new le(this,function(Z){var re=[];return se(Z,function(Te){Te!==Z&&Te.nodeType==p&&(B==="*"||Te.tagName==B)&&re.push(Te)}),re})},getElementsByTagNameNS:function(B,Z){return new le(this,function(re){var Te=[];return se(re,function(Ke){Ke!==re&&Ke.nodeType===p&&(B==="*"||Ke.namespaceURI===B)&&(Z==="*"||Ke.localName==Z)&&Te.push(Ke)}),Te})}},fe.prototype.getElementsByTagName=ye.prototype.getElementsByTagName,fe.prototype.getElementsByTagNameNS=ye.prototype.getElementsByTagNameNS,d(ye,j);function mt(){}mt.prototype.nodeType=y,d(mt,j);function st(){}st.prototype={data:"",substringData:function(B,Z){return this.data.substring(B,B+Z)},appendData:function(B){B=this.data+B,this.nodeValue=this.data=B,this.length=B.length},insertData:function(B,Z){this.replaceData(B,0,Z)},appendChild:function(B){throw new Error(W[D])},deleteData:function(B,Z){this.replaceData(B,Z,"")},replaceData:function(B,Z,re){var Te=this.data.substring(0,B),Ke=this.data.substring(B+Z);re=Te+re+Ke,this.nodeValue=this.data=re,this.length=re.length}},d(st,j);function Xe(){}Xe.prototype={nodeName:"#text",nodeType:v,splitText:function(B){var Z=this.data,re=Z.substring(B);Z=Z.substring(0,B),this.data=this.nodeValue=Z,this.length=Z.length;var Te=this.ownerDocument.createTextNode(re);return this.parentNode&&this.parentNode.insertBefore(Te,this.nextSibling),Te}},d(Xe,st);function xt(){}xt.prototype={nodeName:"#comment",nodeType:N},d(xt,st);function ft(){}ft.prototype={nodeName:"#cdata-section",nodeType:b},d(ft,st);function Pt(){}Pt.prototype.nodeType=H,d(Pt,j);function qt(){}qt.prototype.nodeType=$,d(qt,j);function It(){}It.prototype.nodeType=E,d(It,j);function ni(){}ni.prototype.nodeType=S,d(ni,j);function Gt(){}Gt.prototype.nodeName="#document-fragment",Gt.prototype.nodeType=F,d(Gt,j);function yi(){}yi.prototype.nodeType=L,d(yi,j);function Zt(){}Zt.prototype.serializeToString=function(B,Z,re){return Jt.call(B,Z,re)},j.prototype.toString=Jt;function Jt(B,Z){var re=[],Te=this.nodeType==9&&this.documentElement||this,Ke=Te.prefix,vt=Te.namespaceURI;if(vt&&Ke==null){var Ke=Te.lookupPrefix(vt);if(Ke==null)var Tt=[{namespace:vt,prefix:null}]}return Di(this,re,B,Z,Tt),re.join("")}function di(B,Z,re){var Te=B.prefix||"",Ke=B.namespaceURI;if(!Ke||Te==="xml"&&Ke===t.XML||Ke===t.XMLNS)return!1;for(var vt=re.length;vt--;){var Tt=re[vt];if(Tt.prefix===Te)return Tt.namespace!==Ke}return!0}function Zi(B,Z,re){B.push(" ",Z,'="',re.replace(/[<>&"\t\n\r]/g,X),'"')}function Di(B,Z,re,Te,Ke){if(Ke||(Ke=[]),Te)if(B=Te(B),B){if(typeof B=="string"){Z.push(B);return}}else return;switch(B.nodeType){case p:var vt=B.attributes,Tt=vt.length,Ht=B.firstChild,Li=B.tagName;re=t.isHTML(B.namespaceURI)||re;var bi=Li;if(!re&&!B.prefix&&B.namespaceURI){for(var ji,ai=0;ai=0;Fi--){var li=Ke[Fi];if(li.prefix===""&&li.namespace===B.namespaceURI){ji=li.namespace;break}}if(ji!==B.namespaceURI)for(var Fi=Ke.length-1;Fi>=0;Fi--){var li=Ke[Fi];if(li.namespace===B.namespaceURI){li.prefix&&(bi=li.prefix+":"+Li);break}}}Z.push("<",bi);for(var $s=0;$s"),re&&/^script$/i.test(Li))for(;Ht;)Ht.data?Z.push(Ht.data):Di(Ht,Z,re,Te,Ke.slice()),Ht=Ht.nextSibling;else for(;Ht;)Di(Ht,Z,re,Te,Ke.slice()),Ht=Ht.nextSibling;Z.push("")}else Z.push("/>");return;case R:case F:for(var Ht=B.firstChild;Ht;)Di(Ht,Z,re,Te,Ke.slice()),Ht=Ht.nextSibling;return;case y:return Zi(Z,B.name,B.value);case v:return Z.push(B.data.replace(/[<&>]/g,X));case b:return Z.push("");case N:return Z.push("");case H:var Kt=B.publicId,Ui=B.systemId;if(Z.push("");else if(Ui&&Ui!=".")Z.push(" SYSTEM ",Ui,">");else{var rs=B.internalSubset;rs&&Z.push(" [",rs,"]"),Z.push(">")}return;case L:return Z.push("");case S:return Z.push("&",B.nodeName,";");default:Z.push("??",B.nodeName)}}function Mi(B,Z,re){var Te;switch(Z.nodeType){case p:Te=Z.cloneNode(!1),Te.ownerDocument=B;case F:break;case y:re=!0;break}if(Te||(Te=Z.cloneNode(!1)),Te.ownerDocument=B,Te.parentNode=null,re)for(var Ke=Z.firstChild;Ke;)Te.appendChild(Mi(B,Ke,re)),Ke=Ke.nextSibling;return Te}function Ki(B,Z,re){var Te=new Z.constructor;for(var Ke in Z)if(Object.prototype.hasOwnProperty.call(Z,Ke)){var vt=Z[Ke];typeof vt!="object"&&vt!=Te[Ke]&&(Te[Ke]=vt)}switch(Z.childNodes&&(Te.childNodes=new q),Te.ownerDocument=B,Te.nodeType){case p:var Tt=Z.attributes,Li=Te.attributes=new V,bi=Tt.length;Li._ownerElement=Te;for(var ji=0;ji",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})(Zy)),Zy}var Em={},C2;function Y3(){if(C2)return Em;C2=1;var s=up().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,a=2,u=3,c=4,d=5,f=6,p=7;function y(D,I){this.message=D,this.locator=I,Error.captureStackTrace&&Error.captureStackTrace(this,y)}y.prototype=new Error,y.prototype.name=y.name;function v(){}v.prototype={parse:function(D,I,Q){var K=this.domBuilder;K.startDocument(),H(I,I={}),b(D,I,Q,K,this.errorHandler),K.endDocument()}};function b(D,I,Q,K,q){function le(Et){if(Et>65535){Et-=65536;var ye=55296+(Et>>10),mt=56320+(Et&1023);return String.fromCharCode(ye,mt)}else return String.fromCharCode(Et)}function te(Et){var ye=Et.slice(1,-1);return Object.hasOwnProperty.call(Q,ye)?Q[ye]:ye.charAt(0)==="#"?le(parseInt(ye.substr(1).replace("x","0x"))):(q.error("entity not found:"+Et),Et)}function V(Et){if(Et>fe){var ye=D.substring(fe,Et).replace(/&#?\w+;/g,te);j&&G(fe),K.characters(ye,0,Et-fe),fe=Et}}function G(Et,ye){for(;Et>=ie&&(ye=oe.exec(D));)J=ye.index,ie=J+ye[0].length,j.lineNumber++;j.columnNumber=Et-J+1}for(var J=0,ie=0,oe=/.*(?:\r\n?|\n)|.*$/g,j=K.locator,X=[{currentNSMap:I}],se={},fe=0;;){try{var pe=D.indexOf("<",fe);if(pe<0){if(!D.substr(fe).match(/^\s*$/)){var de=K.doc,Ve=de.createTextNode(D.substr(fe));de.appendChild(Ve),K.currentElement=Ve}return}switch(pe>fe&&V(pe),D.charAt(pe+1)){case"/":var lt=D.indexOf(">",pe+3),Ze=D.substring(pe+2,lt).replace(/[ \t\n\r]+$/g,""),Je=X.pop();lt<0?(Ze=D.substring(pe+2).replace(/[\s<].*/,""),q.error("end tag name: "+Ze+" is not complete:"+Je.tagName),lt=pe+1+Ze.length):Ze.match(/\sfe?fe=lt:V(Math.max(pe,fe)+1)}}function S(D,I){return I.lineNumber=D.lineNumber,I.columnNumber=D.columnNumber,I}function E(D,I,Q,K,q,le){function te(j,X,se){Q.attributeNames.hasOwnProperty(j)&&le.fatalError("Attribute "+j+" redefined"),Q.addValue(j,X.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,q),se)}for(var V,G,J=++I,ie=n;;){var oe=D.charAt(J);switch(oe){case"=":if(ie===r)V=D.slice(I,J),ie=u;else if(ie===a)ie=u;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(ie===u||ie===r)if(ie===r&&(le.warning('attribute value must after "="'),V=D.slice(I,J)),I=J+1,J=D.indexOf(oe,I),J>0)G=D.slice(I,J),te(V,G,I-1),ie=d;else throw new Error("attribute value no end '"+oe+"' match");else if(ie==c)G=D.slice(I,J),te(V,G,I),le.warning('attribute "'+V+'" missed start quot('+oe+")!!"),I=J+1,ie=d;else throw new Error('attribute value must after "="');break;case"/":switch(ie){case n:Q.setTagName(D.slice(I,J));case d:case f:case p:ie=p,Q.closed=!0;case c:case r:break;case a:Q.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return le.error("unexpected end of input"),ie==n&&Q.setTagName(D.slice(I,J)),J;case">":switch(ie){case n:Q.setTagName(D.slice(I,J));case d:case f:case p:break;case c:case r:G=D.slice(I,J),G.slice(-1)==="/"&&(Q.closed=!0,G=G.slice(0,-1));case a:ie===a&&(G=V),ie==c?(le.warning('attribute "'+G+'" missed quot(")!'),te(V,G,I)):((!s.isHTML(K[""])||!G.match(/^(?:disabled|checked|selected)$/i))&&le.warning('attribute "'+G+'" missed value!! "'+G+'" instead!!'),te(G,G,I));break;case u:throw new Error("attribute value missed!!")}return J;case"€":oe=" ";default:if(oe<=" ")switch(ie){case n:Q.setTagName(D.slice(I,J)),ie=f;break;case r:V=D.slice(I,J),ie=a;break;case c:var G=D.slice(I,J);le.warning('attribute "'+G+'" missed quot(")!!'),te(V,G,I);case d:ie=f;break}else switch(ie){case a:Q.tagName,(!s.isHTML(K[""])||!V.match(/^(?:disabled|checked|selected)$/i))&&le.warning('attribute "'+V+'" missed value!! "'+V+'" instead2!!'),te(V,V,I),I=J,ie=r;break;case d:le.warning('attribute space is required"'+V+'"!!');case f:ie=r,I=J;break;case u:ie=c,I=J;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}J++}}function L(D,I,Q){for(var K=D.tagName,q=null,oe=D.length;oe--;){var le=D[oe],te=le.qName,V=le.value,j=te.indexOf(":");if(j>0)var G=le.prefix=te.slice(0,j),J=te.slice(j+1),ie=G==="xmlns"&&J;else J=te,G=null,ie=te==="xmlns"&&"";le.localName=J,ie!==!1&&(q==null&&(q={},H(Q,Q={})),Q[ie]=q[ie]=V,le.uri=s.XMLNS,I.startPrefixMapping(ie,V))}for(var oe=D.length;oe--;){le=D[oe];var G=le.prefix;G&&(G==="xml"&&(le.uri=s.XML),G!=="xmlns"&&(le.uri=Q[G||""]))}var j=K.indexOf(":");j>0?(G=D.prefix=K.slice(0,j),J=D.localName=K.slice(j+1)):(G=null,J=D.localName=K);var X=D.uri=Q[G||""];if(I.startElement(X,J,K,D),D.closed){if(I.endElement(X,J,K),q)for(G in q)Object.prototype.hasOwnProperty.call(q,G)&&I.endPrefixMapping(G)}else return D.currentNSMap=Q,D.localNSMap=q,!0}function N(D,I,Q,K,q){if(/^(?:script|textarea)$/i.test(Q)){var le=D.indexOf("",I),te=D.substring(I+1,le);if(/[&<]/.test(te))return/^script$/i.test(Q)?(q.characters(te,0,te.length),le):(te=te.replace(/&#?\w+;/g,K),q.characters(te,0,te.length),le)}return I+1}function R(D,I,Q,K){var q=K[Q];return q==null&&(q=D.lastIndexOf(""),q",I+4);return le>I?(Q.comment(D,I+4,le-I-4),le+3):(K.error("Unclosed comment"),-1)}else return-1;default:if(D.substr(I+3,6)=="CDATA["){var le=D.indexOf("]]>",I+9);return Q.startCDATA(),Q.characters(D,I+9,le-I-9),Q.endCDATA(),le+3}var te=W(D,I),V=te.length;if(V>1&&/!doctype/i.test(te[0][0])){var G=te[1][0],J=!1,ie=!1;V>3&&(/^public$/i.test(te[2][0])?(J=te[3][0],ie=V>4&&te[4][0]):/^system$/i.test(te[2][0])&&(ie=te[3][0]));var oe=te[V-1];return Q.startDTD(G,J,ie),Q.endDTD(),oe.index+oe[0].length}}return-1}function $(D,I,Q){var K=D.indexOf("?>",I);if(K){var q=D.substring(I,K).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return q?(q[0].length,Q.processingInstruction(q[1],q[2]),K+2):-1}return-1}function M(){this.attributeNames={}}M.prototype={setTagName:function(D){if(!i.test(D))throw new Error("invalid tagName:"+D);this.tagName=D},addValue:function(D,I,Q){if(!i.test(D))throw new Error("invalid attribute:"+D);this.attributeNames[D]=this.length,this[this.length++]={qName:D,value:I,offset:Q}},length:0,getLocalName:function(D){return this[D].localName},getLocator:function(D){return this[D].locator},getQName:function(D){return this[D].qName},getURI:function(D){return this[D].uri},getValue:function(D){return this[D].value}};function W(D,I){var Q,K=[],q=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(q.lastIndex=I,q.exec(D);Q=q.exec(D);)if(K.push(Q),Q[1])return K}return Em.XMLReader=v,Em.ParseError=y,Em}var D2;function X3(){if(D2)return th;D2=1;var s=up(),e=ok(),t=W3(),i=Y3(),n=e.DOMImplementation,r=s.NAMESPACE,a=i.ParseError,u=i.XMLReader;function c(E){return E.replace(/\r[\n\u0085]/g,` `).replace(/[\r\u0085\u2028]/g,` `)}function d(E){this.options=E||{locator:{}}}d.prototype.parseFromString=function(E,L){var N=this.options,R=new u,H=N.domBuilder||new p,F=N.errorHandler,$=N.locator,M=N.xmlns||{},W=/\/x?html?$/.test(L),D=W?t.HTML_ENTITIES:t.XML_ENTITIES;$&&H.setDocumentLocator($),R.errorHandler=f(F,H,$),R.domBuilder=N.domBuilder||H,W&&(M[""]=r.HTML),M.xml=M.xml||r.XML;var I=N.normalizeLineEndings||c;return E&&typeof E=="string"?R.parse(I(E),M,D):R.errorHandler.error("invalid doc source"),H.doc};function f(E,L,N){if(!E){if(L instanceof p)return L;E=L}var R={},H=E instanceof Function;N=N||{};function F($){var M=E[$];!M&&H&&(M=E.length==2?function(W){E($,W)}:E),R[$]=M&&function(W){M("[xmldom "+$+"] "+W+v(N))}||function(){}}return F("warning"),F("error"),F("fatalError"),R}function p(){this.cdata=!1}function y(E,L){L.lineNumber=E.lineNumber,L.columnNumber=E.columnNumber}p.prototype={startDocument:function(){this.doc=new n().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(E,L,N,R){var H=this.doc,F=H.createElementNS(E,N||L),$=R.length;S(this,F),this.currentElement=F,this.locator&&y(this.locator,F);for(var M=0;M<$;M++){var E=R.getURI(M),W=R.getValue(M),N=R.getQName(M),D=H.createAttributeNS(E,N);this.locator&&y(R.getLocator(M),D),D.value=D.nodeValue=W,F.setAttributeNode(D)}},endElement:function(E,L,N){var R=this.currentElement;R.tagName,this.currentElement=R.parentNode},startPrefixMapping:function(E,L){},endPrefixMapping:function(E){},processingInstruction:function(E,L){var N=this.doc.createProcessingInstruction(E,L);this.locator&&y(this.locator,N),S(this,N)},ignorableWhitespace:function(E,L,N){},characters:function(E,L,N){if(E=b.apply(this,arguments),E){if(this.cdata)var R=this.doc.createCDATASection(E);else var R=this.doc.createTextNode(E);this.currentElement?this.currentElement.appendChild(R):/^\s*$/.test(E)&&this.doc.appendChild(R),this.locator&&y(this.locator,R)}},skippedEntity:function(E){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(E){(this.locator=E)&&(E.lineNumber=0)},comment:function(E,L,N){E=b.apply(this,arguments);var R=this.doc.createComment(E);this.locator&&y(this.locator,R),S(this,R)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(E,L,N){var R=this.doc.implementation;if(R&&R.createDocumentType){var H=R.createDocumentType(E,L,N);this.locator&&y(this.locator,H),S(this,H),this.doc.doctype=H}},warning:function(E){console.warn("[xmldom warning] "+E,v(this.locator))},error:function(E){console.error("[xmldom error] "+E,v(this.locator))},fatalError:function(E){throw new a(E,this.locator)}};function v(E){if(E)return` @`+(E.systemId||"")+"#[line:"+E.lineNumber+",col:"+E.columnNumber+"]"}function b(E,L,N){return typeof E=="string"?E.substr(L,N):E.length>=L+N||L?new java.lang.String(E,L,N)+"":E}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(E){p.prototype[E]=function(){return null}});function S(E,L){E.currentElement?E.currentElement.appendChild(L):E.doc.appendChild(L)}return th.__DOMHandler=p,th.normalizeLineEndings=c,th.DOMParser=d,th}var L2;function Q3(){if(L2)return eh;L2=1;var s=ok();return eh.DOMImplementation=s.DOMImplementation,eh.XMLSerializer=s.XMLSerializer,eh.DOMParser=X3().DOMParser,eh}var Z3=Q3();const R2=s=>!!s&&typeof s=="object",Tn=(...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]):R2(e[i])&&R2(t[i])?e[i]=Tn(e[i],t[i]):e[i]=t[i]}),e),{}),lk=s=>Object.keys(s).map(e=>s[e]),J3=(s,e)=>{const t=[];for(let i=s;is.reduce((e,t)=>e.concat(t),[]),uk=s=>{if(!s.length)return[];const e=[];for(let t=0;ts.reduce((t,i,n)=>(i[e]&&t.push(n),t),[]),tP=(s,e)=>lk(s.reduce((t,i)=>(i.forEach(n=>{t[e(n)]=n}),t),{}));var Uc={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 Nh=({baseUrl:s="",source:e="",range:t="",indexRange:i=""})=>{const n={uri:e,resolvedUri:lp(s||"",e)};if(t||i){const a=(t||i).split("-");let u=he.BigInt?he.BigInt(a[0]):parseInt(a[0],10),c=he.BigInt?he.BigInt(a[1]):parseInt(a[1],10);u{let e;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=he.BigInt(s.offset)+he.BigInt(s.length)-he.BigInt(1):e=s.offset+s.length-1,`${s.offset}-${e}`},I2=s=>(s&&typeof s!="number"&&(s=parseInt(s,10)),isNaN(s)?null:s),sP={static(s){const{duration:e,timescale:t=1,sourceDuration:i,periodDuration:n}=s,r=I2(s.endNumber),a=e/t;return typeof r=="number"?{start:0,end:r}:typeof n=="number"?{start:0,end:n/a}:{start:0,end:i/a}},dynamic(s){const{NOW:e,clientOffset:t,availabilityStartTime:i,timescale:n=1,duration:r,periodStart:a=0,minimumUpdatePeriod:u=0,timeShiftBufferDepth:c=1/0}=s,d=I2(s.endNumber),f=(e+t)/1e3,p=i+a,v=f+u-p,b=Math.ceil(v*n/r),S=Math.floor((f-p-c)*n/r),E=Math.floor((f-p)*n/r);return{start:Math.max(0,S),end:typeof d=="number"?d:Math.min(b,E)}}},nP=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}},yb=s=>{const{type:e,duration:t,timescale:i=1,periodDuration:n,sourceDuration:r}=s,{start:a,end:u}=sP[e](s),c=J3(a,u).map(nP(s));if(e==="static"){const d=c.length-1,f=typeof n=="number"?n:r;c[d].duration=f-t/i*d}return c},ck=s=>{const{baseUrl:e,initialization:t={},sourceDuration:i,indexRange:n="",periodStart:r,presentationTime:a,number:u=0,duration:c}=s;if(!e)throw new Error(Uc.NO_BASE_URL);const d=Nh({baseUrl:e,source:t.sourceURL,range:t.range}),f=Nh({baseUrl:e,source:e,indexRange:n});if(f.map=d,c){const p=yb(s);p.length&&(f.duration=p[0].duration,f.timeline=p[0].timeline)}else i&&(f.duration=i,f.timeline=r);return f.presentationTime=a||r,f.number=u,[f]},vb=(s,e,t)=>{const i=s.sidx.map?s.sidx.map:null,n=s.sidx.duration,r=s.timeline||0,a=s.sidx.byterange,u=a.offset+a.length,c=e.timescale,d=e.references.filter(E=>E.referenceType!==1),f=[],p=s.endList?"static":"dynamic",y=s.sidx.timeline;let v=y,b=s.mediaSequence||0,S;typeof e.firstOffset=="bigint"?S=he.BigInt(u)+e.firstOffset:S=u+e.firstOffset;for(let E=0;EtP(s,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),oP=(s,e)=>{for(let t=0;t{let e=[];return K3(s,rP,(t,i,n,r)=>{e=e.concat(t.playlists||[])}),e},O2=({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=oP(s,i.attributes.NAME);if(!n||i.sidx)return;const r=i.segments[0],a=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[a].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,i.discontinuityStarts.unshift(0),i.discontinuitySequence--),O2({playlist:i,mediaSequence:n.segments[a].number})})},uP=({oldManifest:s,newManifest:e})=>{const t=s.playlists.concat(N2(s)),i=e.playlists.concat(N2(e));return e.timelineStarts=dk([s.timelineStarts,e.timelineStarts]),lP({oldPlaylists:t,newPlaylists:i,timelineStarts:e.timelineStarts}),e},cp=s=>s&&s.uri+"-"+iP(s.byterange),Jy=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=lk(i.reduce((r,a)=>{const u=a.attributes.id+(a.attributes.lang||"");return r[u]?(a.segments&&(a.segments[0]&&(a.segments[0].discontinuity=!0),r[u].segments.push(...a.segments)),a.attributes.contentProtection&&(r[u].attributes.contentProtection=a.attributes.contentProtection)):(r[u]=a,r[u].attributes.timelineStarts=[]),r[u].attributes.timelineStarts.push({start:a.attributes.periodStart,timeline:a.attributes.periodStart}),r},{}));t=t.concat(n)}),t.map(i=>(i.discontinuityStarts=eP(i.segments||[],"discontinuity"),i))},xb=(s,e)=>{const t=cp(s.sidx),i=t&&e[t]&&e[t].sidx;return i&&vb(s,i,s.sidx.resolvedUri),s},cP=(s,e={})=>{if(!Object.keys(e).length)return s;for(const t in s)s[t]=xb(s[t],e);return s},dP=({attributes:s,segments:e,sidx:t,mediaSequence:i,discontinuitySequence:n,discontinuityStarts:r},a)=>{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),a&&(u.attributes.AUDIO="audio",u.attributes.SUBTITLES="subs"),u},hP=({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 a={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&&(a.attributes.serviceLocation=s.serviceLocation),a},fP=(s,e={},t=!1)=>{let i;const n=s.reduce((r,a)=>{const u=a.attributes.role&&a.attributes.role.value||"",c=a.attributes.lang||"";let d=a.attributes.label||"main";if(c&&!a.attributes.label){const p=u?` (${u})`:"";d=`${a.attributes.lang}${p}`}r[d]||(r[d]={language:c,autoselect:!0,default:u==="main",playlists:[],uri:""});const f=xb(dP(a,t),e);return r[d].playlists.push(f),typeof i>"u"&&u==="main"&&(i=a,i.default=!0),r},{});if(!i){const r=Object.keys(n)[0];n[r].default=!0}return n},mP=(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(xb(hP(i),e)),t},{}),pP=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),{}),gP=({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},yP=({attributes:s})=>s.mimeType==="video/mp4"||s.mimeType==="video/webm"||s.contentType==="video",vP=({attributes:s})=>s.mimeType==="audio/mp4"||s.mimeType==="audio/webm"||s.contentType==="audio",xP=({attributes:s})=>s.mimeType==="text/vtt"||s.contentType==="text",bP=(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})})},M2=s=>s?Object.keys(s).reduce((e,t)=>{const i=s[t];return e.concat(i.playlists)},[]):[],TP=({dashPlaylists:s,locations:e,contentSteering:t,sidxMapping:i={},previousManifest:n,eventStream:r})=>{if(!s.length)return{};const{sourceDuration:a,type:u,suggestedPresentationDelay:c,minimumUpdatePeriod:d}=s[0].attributes,f=Jy(s.filter(yP)).map(gP),p=Jy(s.filter(vP)),y=Jy(s.filter(xP)),v=s.map(H=>H.attributes.captionServices).filter(Boolean),b={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:a,playlists:cP(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 S=b.playlists.length===0,E=p.length?fP(p,i,S):null,L=y.length?mP(y,i):null,N=f.concat(M2(E),M2(L)),R=N.map(({timelineStarts:H})=>H);return b.timelineStarts=dk(R),bP(N,b.timelineStarts),E&&(b.mediaGroups.AUDIO.audio=E),L&&(b.mediaGroups.SUBTITLES.subs=L),v.length&&(b.mediaGroups["CLOSED-CAPTIONS"].cc=pP(v)),n?uP({oldManifest:n,newManifest:b}):b},SP=(s,e,t)=>{const{NOW:i,clientOffset:n,availabilityStartTime:r,timescale:a=1,periodStart:u=0,minimumUpdatePeriod:c=0}=s,d=(i+n)/1e3,f=r+u,y=d+c-f;return Math.ceil((y*a-e)/t)},hk=(s,e)=>{const{type:t,minimumUpdatePeriod:i=0,media:n="",sourceDuration:r,timescale:a=1,startNumber:u=1,periodStart:c}=s,d=[];let f=-1;for(let p=0;pf&&(f=S);let E;if(b<0){const R=p+1;R===e.length?t==="dynamic"&&i>0&&n.indexOf("$Number$")>0?E=SP(s,f,v):E=(r*a-f)/v:E=(e[R].t-f)/v}else E=b+1;const L=u+d.length+E;let N=u+d.length;for(;N(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}`},P2=(s,e)=>s.replace(_P,EP(e)),wP=(s,e)=>!s.duration&&!e?[{number:s.startNumber||1,duration:s.sourceDuration,time:0,timeline:s.periodStart}]:s.duration?yb(s):hk(s,e),AP=(s,e)=>{const t={RepresentationID:s.id,Bandwidth:s.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=s,n=Nh({baseUrl:s.baseUrl,source:P2(i.sourceURL,t),range:i.range});return wP(s,e).map(a=>{t.Number=a.number,t.Time=a.time;const u=P2(s.media||"",t),c=s.timescale||1,d=s.presentationTimeOffset||0,f=s.periodStart+(a.time-d)/c;return{uri:u,timeline:a.timeline,duration:a.duration,resolvedUri:lp(s.baseUrl||"",u),map:n,number:a.number,presentationTime:f}})},kP=(s,e)=>{const{baseUrl:t,initialization:i={}}=s,n=Nh({baseUrl:t,source:i.sourceURL,range:i.range}),r=Nh({baseUrl:t,source:e.media,range:e.mediaRange});return r.map=n,r},CP=(s,e)=>{const{duration:t,segmentUrls:i=[],periodStart:n}=s;if(!t&&!e||t&&e)throw new Error(Uc.SEGMENT_TIME_UNSPECIFIED);const r=i.map(c=>kP(s,c));let a;return t&&(a=yb(s)),e&&(a=hk(s,e)),a.map((c,d)=>{if(r[d]){const f=r[d],p=s.timescale||1,y=s.presentationTimeOffset||0;return f.timeline=c.timeline,f.duration=c.duration,f.number=c.number,f.presentationTime=n+(c.time-y)/p,f}}).filter(c=>c)},DP=({attributes:s,segmentInfo:e})=>{let t,i;e.template?(i=AP,t=Tn(s,e.template)):e.base?(i=ck,t=Tn(s,e.base)):e.list&&(i=CP,t=Tn(s,e.list));const n={attributes:s};if(!i)return n;const r=i(t,e.segmentTimeline);if(t.duration){const{duration:a,timescale:u=1}=t;t.duration=a/u}else r.length?t.duration=r.reduce((a,u)=>Math.max(a,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},LP=s=>s.map(DP),Os=(s,e)=>uk(s.childNodes).filter(({tagName:t})=>t===e),Yh=s=>s.textContent.trim(),RP=s=>parseFloat(s.split("/").reduce((e,t)=>e/t)),sc=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,y,v]=u.slice(1);return parseFloat(c||0)*31536e3+parseFloat(d||0)*2592e3+parseFloat(f||0)*86400+parseFloat(p||0)*3600+parseFloat(y||0)*60+parseFloat(v||0)},IP=s=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(s)&&(s+="Z"),Date.parse(s)),B2={mediaPresentationDuration(s){return sc(s)},availabilityStartTime(s){return IP(s)/1e3},minimumUpdatePeriod(s){return sc(s)},suggestedPresentationDelay(s){return sc(s)},type(s){return s},timeShiftBufferDepth(s){return sc(s)},start(s){return sc(s)},width(s){return parseInt(s,10)},height(s){return parseInt(s,10)},bandwidth(s){return parseInt(s,10)},frameRate(s){return RP(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)?sc(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}},ln=s=>s&&s.attributes?uk(s.attributes).reduce((e,t)=>{const i=B2[t.name]||B2.DEFAULT;return e[t.name]=i(t.value),e},{}):{},NP={"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"},dp=(s,e)=>e.length?Fc(s.map(function(t){return e.map(function(i){const n=Yh(i),r=lp(t.baseUrl,n),a=Tn(ln(i),{baseUrl:r});return r!==n&&!a.serviceLocation&&t.serviceLocation&&(a.serviceLocation=t.serviceLocation),a})})):s,bb=s=>{const e=Os(s,"SegmentTemplate")[0],t=Os(s,"SegmentList")[0],i=t&&Os(t,"SegmentURL").map(p=>Tn({tag:"SegmentURL"},ln(p))),n=Os(s,"SegmentBase")[0],r=t||e,a=r&&Os(r,"SegmentTimeline")[0],u=t||n||e,c=u&&Os(u,"Initialization")[0],d=e&&ln(e);d&&c?d.initialization=c&&ln(c):d&&d.initialization&&(d.initialization={sourceURL:d.initialization});const f={template:d,segmentTimeline:a&&Os(a,"S").map(p=>ln(p)),list:t&&Tn(ln(t),{segmentUrls:i,initialization:ln(c)}),base:n&&Tn(ln(n),{initialization:ln(c)})};return Object.keys(f).forEach(p=>{f[p]||delete f[p]}),f},OP=(s,e,t)=>i=>{const n=Os(i,"BaseURL"),r=dp(e,n),a=Tn(s,ln(i)),u=bb(i);return r.map(c=>({segmentInfo:Tn(t,u),attributes:Tn(a,c)}))},MP=s=>s.reduce((e,t)=>{const i=ln(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=NP[i.schemeIdUri];if(n){e[n]={attributes:i};const r=Os(t,"cenc:pssh")[0];if(r){const a=Yh(r);e[n].pssh=a&&tk(a)}}return e},{}),PP=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(a=>{const[u,c]=a.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})},BP=s=>Fc(Os(s.node,"EventStream").map(e=>{const t=ln(e),i=t.schemeIdUri;return Os(e,"Event").map(n=>{const r=ln(n),a=r.presentationTime||0,u=t.timescale||1,c=r.duration||0,d=a/u+s.attributes.start;return{schemeIdUri:i,value:t.value,id:r.id,start:d,end:d+c/u,messageData:Yh(n)||r.messageData,contentEncoding:t.contentEncoding,presentationTimeOffset:t.presentationTimeOffset||0}})})),FP=(s,e,t)=>i=>{const n=ln(i),r=dp(e,Os(i,"BaseURL")),a=Os(i,"Role")[0],u={role:ln(a)};let c=Tn(s,n,u);const d=Os(i,"Accessibility")[0],f=PP(ln(d));f&&(c=Tn(c,{captionServices:f}));const p=Os(i,"Label")[0];if(p&&p.childNodes.length){const E=p.childNodes[0].nodeValue.trim();c=Tn(c,{label:E})}const y=MP(Os(i,"ContentProtection"));Object.keys(y).length&&(c=Tn(c,{contentProtection:y}));const v=bb(i),b=Os(i,"Representation"),S=Tn(t,v);return Fc(b.map(OP(c,r,S)))},UP=(s,e)=>(t,i)=>{const n=dp(e,Os(t.node,"BaseURL")),r=Tn(s,{periodStart:t.attributes.start});typeof t.attributes.duration=="number"&&(r.periodDuration=t.attributes.duration);const a=Os(t.node,"AdaptationSet"),u=bb(t.node);return Fc(a.map(FP(r,n,u)))},jP=(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=Tn({serverURL:Yh(s[0])},ln(s[0]));return t.queryBeforeStart=t.queryBeforeStart==="true",t},$P=({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,HP=(s,e={})=>{const{manifestUri:t="",NOW:i=Date.now(),clientOffset:n=0,eventHandler:r=function(){}}=e,a=Os(s,"Period");if(!a.length)throw new Error(Uc.INVALID_NUMBER_OF_PERIOD);const u=Os(s,"Location"),c=ln(s),d=dp([{baseUrl:t}],Os(s,"BaseURL")),f=Os(s,"ContentSteering");c.type=c.type||"static",c.sourceDuration=c.mediaPresentationDuration||0,c.NOW=i,c.clientOffset=n,u.length&&(c.locations=u.map(Yh));const p=[];return a.forEach((y,v)=>{const b=ln(y),S=p[v-1];b.start=$P({attributes:b,priorPeriodAttributes:S?S.attributes:null,mpdType:c.type}),p.push({node:y,attributes:b})}),{locations:c.locations,contentSteeringInfo:jP(f,r),representationInfo:Fc(p.map(UP(c,d))),eventStream:Fc(p.map(BP))}},fk=s=>{if(s==="")throw new Error(Uc.DASH_EMPTY_MANIFEST);const e=new Z3.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(Uc.DASH_INVALID_XML);return i},zP=s=>{const e=Os(s,"UTCTiming")[0];if(!e)return null;const t=ln(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(Uc.UNSUPPORTED_UTC_TIMING_SCHEME)}return t},GP=(s,e={})=>{const t=HP(fk(s),e),i=LP(t.representationInfo);return TP({dashPlaylists:i,locations:t.locations,contentSteering:t.contentSteeringInfo,sidxMapping:e.sidxMapping,previousManifest:e.previousManifest,eventStream:t.eventStream})},VP=s=>zP(fk(s));var ev,F2;function qP(){if(F2)return ev;F2=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,a--)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 tv=e,tv}var WP=KP();const YP=Wc(WP);var XP=ti([73,68,51]),QP=function(e,t){t===void 0&&(t=0),e=ti(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},hh=function s(e,t){return t===void 0&&(t=0),e=ti(e),e.length-t<10||!Ns(e,XP,{offset:t})?t:(t+=QP(e,t),s(e,t))},j2=function(e){return typeof e=="string"?ak(e):e},ZP=function(e){return Array.isArray(e)?e.map(function(t){return j2(t)}):[j2(e)]},JP=function s(e,t,i){i===void 0&&(i=!1),t=ZP(t),e=ti(e);var n=[];if(!t.length)return n;for(var r=0;r>>0,u=e.subarray(r+4,r+8);if(a===0)break;var c=r+a;if(c>e.length){if(i)break;c=e.length}var d=e.subarray(r+8,c);Ns(u,t[0])&&(t.length===1?n.push(d):n.push.apply(n,s(d,t.slice(1),i))),r=c}return n},wm={EBML:ti([26,69,223,163]),DocType:ti([66,130]),Segment:ti([24,83,128,103]),SegmentInfo:ti([21,73,169,102]),Tracks:ti([22,84,174,107]),Track:ti([174]),TrackNumber:ti([215]),DefaultDuration:ti([35,227,131]),TrackEntry:ti([174]),TrackType:ti([131]),FlagDefault:ti([136]),CodecID:ti([134]),CodecPrivate:ti([99,162]),VideoTrack:ti([224]),AudioTrack:ti([225]),Cluster:ti([31,67,182,117]),Timestamp:ti([231]),TimestampScale:ti([42,215,177]),BlockGroup:ti([160]),BlockDuration:ti([155]),Block:ti([161]),SimpleBlock:ti([163])},fx=[128,64,32,16,8,4,2,1],e4=function(e){for(var t=1,i=0;i=t.length)return t.length;var n=v0(t,i,!1);if(Ns(e.bytes,n.bytes))return i;var r=v0(t,i+n.length);return s(e,t,i+r.length+r.value+n.length)},H2=function s(e,t){t=t4(t),e=ti(e);var i=[];if(!t.length)return i;for(var n=0;ne.length?e.length:u+a.value,d=e.subarray(u,c);Ns(t[0],r.bytes)&&(t.length===1?i.push(d):i=i.concat(s(d,t.slice(1))));var f=r.length+a.length+d.length;n+=f}return i},s4=ti([0,0,0,1]),n4=ti([0,0,1]),r4=ti([0,0,3]),a4=function(e){for(var t=[],i=1;i>1&63),i.indexOf(d)!==-1&&(a=r+c),r+=c+(t==="h264"?1:2)}return e.subarray(0,0)},o4=function(e,t,i){return mk(e,"h264",t,i)},l4=function(e,t,i){return mk(e,"h265",t,i)},Wn={webm:ti([119,101,98,109]),matroska:ti([109,97,116,114,111,115,107,97]),flac:ti([102,76,97,67]),ogg:ti([79,103,103,83]),ac3:ti([11,119]),riff:ti([82,73,70,70]),avi:ti([65,86,73]),wav:ti([87,65,86,69]),"3gp":ti([102,116,121,112,51,103]),mp4:ti([102,116,121,112]),fmp4:ti([115,116,121,112]),mov:ti([102,116,121,112,113,116]),moov:ti([109,111,111,118]),moof:ti([109,111,111,102])},jc={aac:function(e){var t=hh(e);return Ns(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=hh(e);return Ns(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=H2(e,[wm.EBML,wm.DocType])[0];return Ns(t,Wn.webm)},mkv:function(e){var t=H2(e,[wm.EBML,wm.DocType])[0];return Ns(t,Wn.matroska)},mp4:function(e){if(jc["3gp"](e)||jc.mov(e))return!1;if(Ns(e,Wn.mp4,{offset:4})||Ns(e,Wn.fmp4,{offset:4})||Ns(e,Wn.moof,{offset:4})||Ns(e,Wn.moov,{offset:4}))return!0},mov:function(e){return Ns(e,Wn.mov,{offset:4})},"3gp":function(e){return Ns(e,Wn["3gp"],{offset:4})},ac3:function(e){var t=hh(e);return Ns(e,Wn.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return e[0]===71;for(var t=0;t+1880},iv,z2;function d4(){if(z2)return iv;z2=1;var s=9e4,e,t,i,n,r,a,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))},a=function(c,d){return t(i(c),d)},u=function(c,d,f){return i(f?c:c-d)},iv={ONE_SECOND_IN_TS:s,secondsToVideoTs:e,secondsToAudioTs:t,videoTsToSeconds:i,audioTsToSeconds:n,audioTsToVideoTs:r,videoTsToAudioTs:a,metadataTsToSeconds:u},iv}var mu=d4();var px="8.23.4";const wo={},Dl=function(s,e){return wo[s]=wo[s]||[],e&&(wo[s]=wo[s].concat(e)),wo[s]},h4=function(s,e){Dl(s,e)},pk=function(s,e){const t=Dl(s).indexOf(e);return t<=-1?!1:(wo[s]=wo[s].slice(),wo[s].splice(t,1),!0)},f4=function(s,e){Dl(s,[].concat(e).map(t=>{const i=(...n)=>(pk(s,i),t(...n));return i}))},x0={prefixed:!0},Qm=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],G2=Qm[0];let fh;for(let s=0;s(i,n,r)=>{const a=e.levels[n],u=new RegExp(`^(${a})$`);let c=s;if(i!=="log"&&r.unshift(i.toUpperCase()+":"),t&&(c=`%c${s}`,r.unshift(t)),r.unshift(c+":"),mr){mr.push([].concat(r));const f=mr.length-1e3;mr.splice(0,f>0?f:0)}if(!he.console)return;let d=he.console[i];!d&&i==="debug"&&(d=he.console.info||he.console.log),!(!d||!a||!u.test(i))&&d[Array.isArray(r)?"apply":"call"](he.console,r)};function gx(s,e=":",t=""){let i="info",n;function r(...a){n("log",i,a)}return n=m4(s,r,t),r.createLogger=(a,u,c)=>{const d=u!==void 0?u:e,f=c!==void 0?c:t,p=`${s} ${d} ${a}`;return gx(p,d,f)},r.createNewLogger=(a,u,c)=>gx(a,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=a=>{if(typeof a=="string"){if(!r.levels.hasOwnProperty(a))throw new Error(`"${a}" in not a valid log level`);i=a}return i},r.history=()=>mr?[].concat(mr):[],r.history.filter=a=>(mr||[]).filter(u=>new RegExp(`.*${a}.*`).test(u[0])),r.history.clear=()=>{mr&&(mr.length=0)},r.history.disable=()=>{mr!==null&&(mr.length=0,mr=null)},r.history.enable=()=>{mr===null&&(mr=[])},r.error=(...a)=>n("error",i,a),r.warn=(...a)=>n("warn",i,a),r.debug=(...a)=>n("debug",i,a),r}const Ei=gx("VIDEOJS"),gk=Ei.createLogger,p4=Object.prototype.toString,yk=function(s){return Va(s)?Object.keys(s):[]};function Tc(s,e){yk(s).forEach(t=>e(s[t],t))}function vk(s,e,t=0){return yk(s).reduce((i,n)=>e(i,s[n],n),t)}function Va(s){return!!s&&typeof s=="object"}function $c(s){return Va(s)&&p4.call(s)==="[object Object]"&&s.constructor===Object}function cs(...s){const e={};return s.forEach(t=>{t&&Tc(t,(i,n)=>{if(!$c(i)){e[n]=i;return}$c(e[n])||(e[n]={}),e[n]=cs(e[n],i)})}),e}function xk(s={}){const e=[];for(const t in s)if(s.hasOwnProperty(t)){const i=s[t];e.push(i)}return e}function hp(s,e,t,i=!0){const n=a=>Object.defineProperty(s,e,{value:a,enumerable:!0,writable:!0}),r={configurable:!0,enumerable:!0,get(){const a=t();return n(a),a}};return i&&(r.set=n),Object.defineProperty(s,e,r)}var g4=Object.freeze({__proto__:null,each:Tc,reduce:vk,isObject:Va,isPlain:$c,merge:cs,values:xk,defineLazyProperty:hp});let Sb=!1,bk=null,pa=!1,Tk,Sk=!1,Sc=!1,_c=!1,qa=!1,_b=null,fp=null;const y4=!!(he.cast&&he.cast.framework&&he.cast.framework.CastReceiverContext);let _k=null,b0=!1,mp=!1,T0=!1,pp=!1,S0=!1,_0=!1,E0=!1;const Oh=!!(Yc()&&("ontouchstart"in he||he.navigator.maxTouchPoints||he.DocumentTouch&&he.document instanceof he.DocumentTouch)),fl=he.navigator&&he.navigator.userAgentData;fl&&fl.platform&&fl.brands&&(pa=fl.platform==="Android",Sc=!!fl.brands.find(s=>s.brand==="Microsoft Edge"),_c=!!fl.brands.find(s=>s.brand==="Chromium"),qa=!Sc&&_c,_b=fp=(fl.brands.find(s=>s.brand==="Chromium")||{}).version||null,mp=fl.platform==="Windows");if(!_c){const s=he.navigator&&he.navigator.userAgent||"";Sb=/iPod/i.test(s),bk=(function(){const e=s.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null})(),pa=/Android/i.test(s),Tk=(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})(),Sk=/Firefox/i.test(s),Sc=/Edg/i.test(s),_c=/Chrome/i.test(s)||/CriOS/i.test(s),qa=!Sc&&_c,_b=fp=(function(){const e=s.match(/(Chrome|CriOS)\/(\d+)/);return e&&e[2]?parseFloat(e[2]):null})(),_k=(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})(),S0=/Tizen/i.test(s),_0=/Web0S/i.test(s),E0=S0||_0,b0=/Safari/i.test(s)&&!qa&&!pa&&!Sc&&!E0,mp=/Windows/i.test(s),T0=/iPad/i.test(s)||b0&&Oh&&!/iPhone/i.test(s),pp=/iPhone/i.test(s)&&!T0}const Hn=pp||T0||Sb,gp=(b0||Hn)&&!qa;var Ek=Object.freeze({__proto__:null,get IS_IPOD(){return Sb},get IOS_VERSION(){return bk},get IS_ANDROID(){return pa},get ANDROID_VERSION(){return Tk},get IS_FIREFOX(){return Sk},get IS_EDGE(){return Sc},get IS_CHROMIUM(){return _c},get IS_CHROME(){return qa},get CHROMIUM_VERSION(){return _b},get CHROME_VERSION(){return fp},IS_CHROMECAST_RECEIVER:y4,get IE_VERSION(){return _k},get IS_SAFARI(){return b0},get IS_WINDOWS(){return mp},get IS_IPAD(){return T0},get IS_IPHONE(){return pp},get IS_TIZEN(){return S0},get IS_WEBOS(){return _0},get IS_SMART_TV(){return E0},TOUCH_ENABLED:Oh,IS_IOS:Hn,IS_ANY_SAFARI:gp});function V2(s){return typeof s=="string"&&!!s.trim()}function v4(s){if(s.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}function Yc(){return yt===he.document}function Xc(s){return Va(s)&&s.nodeType===1}function wk(){try{return he.parent!==he.self}catch{return!0}}function Ak(s){return function(e,t){if(!V2(e))return yt[s](null);V2(t)&&(t=yt.querySelector(t));const i=Xc(t)?t:yt;return i[s]&&i[s](e)}}function ri(s="div",e={},t={},i){const n=yt.createElement(s);return Object.getOwnPropertyNames(e).forEach(function(r){const a=e[r];r==="textContent"?Nl(n,a):(n[r]!==a||r==="tabIndex")&&(n[r]=a)}),Object.getOwnPropertyNames(t).forEach(function(r){n.setAttribute(r,t[r])}),i&&Eb(n,i),n}function Nl(s,e){return typeof s.textContent>"u"?s.innerText=e:s.textContent=e,s}function yx(s,e){e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)}function Eh(s,e){return v4(e),s.classList.contains(e)}function yu(s,...e){return s.classList.add(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s}function yp(s,...e){return s?(s.classList.remove(...e.reduce((t,i)=>t.concat(i.split(/\s+/)),[])),s):(Ei.warn("removeClass was called with an element that doesn't exist"),null)}function kk(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 Ck(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 bl(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 a=i[n].value;t.includes(r)&&(a=a!==null),e[r]=a}}return e}function Dk(s,e){return s.getAttribute(e)}function Hc(s,e,t){s.setAttribute(e,t)}function vp(s,e){s.removeAttribute(e)}function Lk(){yt.body.focus(),yt.onselectstart=function(){return!1}}function Rk(){yt.onselectstart=function(){return!0}}function zc(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(Gc(s,"height"))),t.width||(t.width=parseFloat(Gc(s,"width"))),t}}function Mh(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!==yt[x0.fullscreenElement];)i+=s.offsetLeft,n+=s.offsetTop,s=s.offsetParent;return{left:i,top:n,width:e,height:t}}function xp(s,e){const t={x:0,y:0};if(Hn){let f=s;for(;f&&f.nodeName.toLowerCase()!=="html";){const p=Gc(f,"transform");if(/^matrix/.test(p)){const y=p.slice(7,-1).split(/,\s/).map(Number);t.x+=y[4],t.y+=y[5]}else if(/^matrix3d/.test(p)){const y=p.slice(9,-1).split(/,\s/).map(Number);t.x+=y[12],t.y+=y[13]}if(f.assignedSlot&&f.assignedSlot.parentElement&&he.WebKitCSSMatrix){const y=he.getComputedStyle(f.assignedSlot.parentElement).transform,v=new he.WebKitCSSMatrix(y);t.x+=v.m41,t.y+=v.m42}f=f.parentNode||f.host}}const i={},n=Mh(e.target),r=Mh(s),a=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/a)),i}function Ik(s){return Va(s)&&s.nodeType===3}function bp(s){for(;s.firstChild;)s.removeChild(s.firstChild);return s}function Nk(s){return typeof s=="function"&&(s=s()),(Array.isArray(s)?s:[s]).map(e=>{if(typeof e=="function"&&(e=e()),Xc(e)||Ik(e))return e;if(typeof e=="string"&&/\S/.test(e))return yt.createTextNode(e)}).filter(e=>e)}function Eb(s,e){return Nk(e).forEach(t=>s.appendChild(t)),s}function Ok(s,e){return Eb(bp(s),e)}function Ph(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=Ak("querySelector"),Mk=Ak("querySelectorAll");function Gc(s,e){if(!s||!e)return"";if(typeof he.getComputedStyle=="function"){let t;try{t=he.getComputedStyle(s)}catch{return""}return t?t.getPropertyValue(e)||t[e]:""}return""}function Pk(s){[...yt.styleSheets].forEach(e=>{try{const t=[...e.cssRules].map(n=>n.cssText).join(""),i=yt.createElement("style");i.textContent=t,s.document.head.appendChild(i)}catch{const i=yt.createElement("link");i.rel="stylesheet",i.type=e.type,i.media=e.media.mediaText,i.href=e.href,s.document.head.appendChild(i)}})}var Bk=Object.freeze({__proto__:null,isReal:Yc,isEl:Xc,isInFrame:wk,createEl:ri,textContent:Nl,prependTo:yx,hasClass:Eh,addClass:yu,removeClass:yp,toggleClass:kk,setAttributes:Ck,getAttributes:bl,getAttribute:Dk,setAttribute:Hc,removeAttribute:vp,blockTextSelection:Lk,unblockTextSelection:Rk,getBoundingClientRect:zc,findPosition:Mh,getPointerPosition:xp,isTextNode:Ik,emptyEl:bp,normalizeContent:Nk,appendContent:Eb,insertContent:Ok,isSingleLeftClick:Ph,$:Ll,$$:Mk,computedStyle:Gc,copyStyleSheetsToWindow:Pk});let Fk=!1,vx;const x4=function(){if(vx.options.autoSetup===!1)return;const s=Array.prototype.slice.call(yt.getElementsByTagName("video")),e=Array.prototype.slice.call(yt.getElementsByTagName("audio")),t=Array.prototype.slice.call(yt.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 zn(s,e,t){if(!Xn.has(s))return;const i=Xn.get(s);if(!i.handlers)return;if(Array.isArray(e))return wb(zn,s,e,t);const n=function(a,u){i.handlers[u]=[],q2(a,u)};if(e===void 0){for(const a in i.handlers)Object.prototype.hasOwnProperty.call(i.handlers||{},a)&&n(s,a);return}const r=i.handlers[e];if(r){if(!t){n(s,e);return}if(t.guid)for(let a=0;a=e&&(s(...n),t=r)}},$k=function(s,e,t,i=he){let n;const r=()=>{i.clearTimeout(n),n=null},a=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 a.cancel=r,a};var w4=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:Zr,bind_:Ts,throttle:Ka,debounce:$k});let ih;class Hr{on(e,t){const i=this.addEventListener;this.addEventListener=()=>{},$r(this,e,t),this.addEventListener=i}off(e,t){zn(this,e,t)}one(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Sp(this,e,t),this.addEventListener=i}any(e,t){const i=this.addEventListener;this.addEventListener=()=>{},Ab(this,e,t),this.addEventListener=i}trigger(e){const t=e.type||e;typeof e=="string"&&(e={type:t}),e=Tp(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),Qc(this,e)}queueTrigger(e){ih||(ih=new Map);const t=e.type||e;let i=ih.get(this);i||(i=new Map,ih.set(this,i));const n=i.get(t);i.delete(t),he.clearTimeout(n);const r=he.setTimeout(()=>{i.delete(t),i.size===0&&(i=null,ih.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 _p=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,Do=s=>s instanceof Hr||!!s.eventBusEl_&&["on","one","off","trigger"].every(e=>typeof s[e]=="function"),A4=(s,e)=>{Do(s)?e():(s.eventedCallbacks||(s.eventedCallbacks=[]),s.eventedCallbacks.push(e))},Tx=s=>typeof s=="string"&&/\S/.test(s)||Array.isArray(s)&&!!s.length,w0=(s,e,t)=>{if(!s||!s.nodeName&&!Do(s))throw new Error(`Invalid target for ${_p(e)}#${t}; must be a DOM node or evented object.`)},Hk=(s,e,t)=>{if(!Tx(s))throw new Error(`Invalid event type for ${_p(e)}#${t}; must be a non-empty string or array.`)},zk=(s,e,t)=>{if(typeof s!="function")throw new Error(`Invalid listener for ${_p(e)}#${t}; must be a function.`)},sv=(s,e,t)=>{const i=e.length<3||e[0]===s||e[0]===s.eventBusEl_;let n,r,a;return i?(n=s.eventBusEl_,e.length>=3&&e.shift(),[r,a]=e):(n=e[0],r=e[1],a=e[2]),w0(n,s,t),Hk(r,s,t),zk(a,s,t),a=Ts(s,a),{isTargetingSelf:i,target:n,type:r,listener:a}},su=(s,e,t,i)=>{w0(s,s,e),s.nodeName?E4[e](s,t,i):s[e](t,i)},k4={on(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=sv(this,s,"on");if(su(t,"on",i,n),!e){const r=()=>this.off(t,i,n);r.guid=n.guid;const a=()=>this.off("dispose",r);a.guid=n.guid,su(this,"on","dispose",r),su(t,"on","dispose",a)}},one(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=sv(this,s,"one");if(e)su(t,"one",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,su(t,"one",i,r)}},any(...s){const{isTargetingSelf:e,target:t,type:i,listener:n}=sv(this,s,"any");if(e)su(t,"any",i,n);else{const r=(...a)=>{this.off(t,i,r),n.apply(null,a)};r.guid=n.guid,su(t,"any",i,r)}},off(s,e,t){if(!s||Tx(s))zn(this.eventBusEl_,s,e);else{const i=s,n=e;w0(i,this,"off"),Hk(n,this,"off"),zk(t,this,"off"),t=Ts(this,t),this.off("dispose",t),i.nodeName?(zn(i,n,t),zn(i,"dispose",t)):Do(i)&&(i.off(n,t),i.off("dispose",t))}},trigger(s,e){w0(this.eventBusEl_,this,"trigger");const t=s&&typeof s!="string"?s.type:s;if(!Tx(t))throw new Error(`Invalid event type for ${_p(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return Qc(this.eventBusEl_,s,e)}};function kb(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_=ri("span",{className:"vjs-event-bus"});return Object.assign(s,k4),s.eventedCallbacks&&s.eventedCallbacks.forEach(i=>{i()}),s.on("dispose",()=>{s.off(),[s,s.el_,s.eventBusEl_].forEach(function(i){i&&Xn.has(i)&&Xn.delete(i)}),he.setTimeout(()=>{s.eventBusEl_=null},0)}),s}const C4={state:{},setState(s){typeof s=="function"&&(s=s());let e;return Tc(s,(t,i)=>{this.state[i]!==t&&(e=e||{},e[i]={from:this.state[i],to:t}),this.state[i]=t}),e&&Do(this)&&this.trigger({changes:e,type:"statechanged"}),e}};function Gk(s,e){return Object.assign(s,C4),s.state=Object.assign({},s.state,e),typeof s.handleStateChanged=="function"&&Do(s)&&s.on("statechanged",s.handleStateChanged),s}const wh=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toLowerCase())},Ws=function(s){return typeof s!="string"?s:s.replace(/./,e=>e.toUpperCase())},Vk=function(s,e){return Ws(s)===Ws(e)};var D4=Object.freeze({__proto__:null,toLowerCase:wh,toTitleCase:Ws,titleCaseEquals:Vk});class We{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=cs({},this.options_),t=this.options_=cs(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_${Qr()}`}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&&(kb(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),Gk(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_=cs(this.options_,e),this.options_):this.options_}el(){return this.el_}createEl(e,t,i){return ri(e,t,i)}localize(e,t,i=e){const n=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),a=r&&r[n],u=n&&n.split("-")[0],c=r&&r[u];let d=i;return a&&a[e]?d=a[e]:c&&c[e]&&(d=c[e]),t&&(d=d.replace(/\{(\d+)\}/g,function(f,p){const y=t[p-1];let v=y;return typeof y>"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_[Ws(e.name())]=null,this.childNameIndex_[wh(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=a=>{const u=a.name;let c=a.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=We.getComponent("Tech");Array.isArray(e)?n=e:n=Object.keys(e),n.concat(Object.keys(this.options_).filter(function(a){return!n.some(function(u){return typeof u=="string"?a===u:a===u.name})})).map(a=>{let u,c;return typeof a=="string"?(u=a,c=e[u]||this.options_[u]||{}):(u=a.name,c=a),{name:u,opts:c}}).filter(a=>{const u=We.getComponent(a.opts.componentClass||Ws(a.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 Mk(e,t||this.contentEl())}hasClass(e){return Eh(this.el_,e)}addClass(...e){yu(this.el_,...e)}removeClass(...e){yp(this.el_,...e)}toggleClass(e,t){kk(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 Dk(this.el_,e)}setAttribute(e,t){Hc(this.el_,e,t)}removeAttribute(e){vp(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"+Ws(e)],10)}currentDimension(e){let t=0;if(e!=="width"&&e!=="height")throw new Error("currentDimension only accepts width or height value");if(t=Gc(this.el_,e),t=parseFloat(t),t===0||isNaN(t)){const i=`offset${Ws(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=he.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 a=function(){r=!1};this.on("touchleave",a),this.on("touchcancel",a),this.on("touchend",function(u){t=null,r===!0&&he.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),he.clearTimeout(e)),e}setInterval(e,t){e=Ts(this,e),this.clearTimersOnDispose_();const i=he.setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),he.clearInterval(e)),e}requestAnimationFrame(e){this.clearTimersOnDispose_();var t;return e=Ts(this,e),t=he.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),he.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 a=he.getComputedStyle(r,null),u=a.getPropertyValue("visibility");return a.getPropertyValue("display")!=="none"&&!["hidden","collapse"].includes(u)}function i(r){return!(!t(r.parentElement)||!t(r)||r.style.opacity==="0"||he.getComputedStyle(r).height==="0px"||he.getComputedStyle(r).width==="0px")}function n(r){if(r.offsetWidth+r.offsetHeight+r.getBoundingClientRect().height+r.getBoundingClientRect().width===0)return!1;const a={x:r.getBoundingClientRect().left+r.offsetWidth/2,y:r.getBoundingClientRect().top+r.offsetHeight/2};if(a.x<0||a.x>(yt.documentElement.clientWidth||he.innerWidth)||a.y<0||a.y>(yt.documentElement.clientHeight||he.innerHeight))return!1;let u=yt.elementFromPoint(a.x,a.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=We.getComponent("Tech"),n=i&&i.isTech(t),r=We===t||We.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=Ws(e),We.components_||(We.components_={});const a=We.getComponent("Player");if(e==="Player"&&a&&a.players){const u=a.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 K2(s,e,t,i){return L4(s,i,t.length-1),t[i][e]}function nv(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:K2.bind(null,"start",0,s),end:K2.bind(null,"end",1,s)},he.Symbol&&he.Symbol.iterator&&(e[he.Symbol.iterator]=()=>(s||[]).values()),e}function ma(s,e){return Array.isArray(s)?nv(s):s===void 0||e===void 0?nv():nv([[s,e]])}const qk=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),a=Math.floor(e/3600);return(isNaN(s)||s===1/0)&&(n=i=t="-"),n=n>0||a>0?n+":":"",i=((n||r>=10)&&i<10?"0"+i:i)+":",t=t<10?"0"+t:t,n+i+t};let Cb=qk;function Kk(s){Cb=s}function Wk(){Cb=qk}function wu(s,e=s){return Cb(s,e)}var R4=Object.freeze({__proto__:null,createTimeRanges:ma,createTimeRange:ma,setFormatTime:Kk,resetFormatTime:Wk,formatTime:wu});function Yk(s,e){let t=0,i,n;if(!e)return 0;(!s||!s.length)&&(s=ma(0,0));for(let r=0;re&&(n=e),t+=n-i;return t/e}function js(s){if(s instanceof js)return s;typeof s=="number"?this.code=s:typeof s=="string"?this.message=s:Va(s)&&(typeof s.code=="number"&&(this.code=s.code),Object.assign(this,s)),this.message||(this.message=js.defaultMessages[this.code]||"")}js.prototype.code=0;js.prototype.message="";js.prototype.status=null;js.prototype.metadata=null;js.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"];js.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."};js.MEDIA_ERR_CUSTOM=0;js.prototype.MEDIA_ERR_CUSTOM=0;js.MEDIA_ERR_ABORTED=1;js.prototype.MEDIA_ERR_ABORTED=1;js.MEDIA_ERR_NETWORK=2;js.prototype.MEDIA_ERR_NETWORK=2;js.MEDIA_ERR_DECODE=3;js.prototype.MEDIA_ERR_DECODE=3;js.MEDIA_ERR_SRC_NOT_SUPPORTED=4;js.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4;js.MEDIA_ERR_ENCRYPTED=5;js.prototype.MEDIA_ERR_ENCRYPTED=5;function Ah(s){return s!=null&&typeof s.then=="function"}function Pa(s){Ah(s)&&s.then(null,e=>{})}const Sx=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}})})},I4=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=Sx(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(Sx))},N4=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 _x={textTracksToJson:I4,jsonToTextTracks:N4,trackToJson:Sx};const rv="vjs-modal-dialog";class Zc extends We{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_=ri("div",{className:`${rv}-content`},{role:"document"}),this.descEl_=ri("p",{className:`${rv}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),Nl(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`${rv} 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(),Ok(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"),bp(this.contentEl()),this.trigger("modalempty")}content(e){return typeof e<"u"&&(this.content_=e),this.content_}conditionalFocus_(){const e=yt.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 he.HTMLAnchorElement||t instanceof he.HTMLAreaElement)&&t.hasAttribute("href")||(t instanceof he.HTMLInputElement||t instanceof he.HTMLSelectElement||t instanceof he.HTMLTextAreaElement||t instanceof he.HTMLButtonElement)&&!t.hasAttribute("disabled")||t instanceof he.HTMLIFrameElement||t instanceof he.HTMLObjectElement||t instanceof he.HTMLEmbedElement||t.hasAttribute("tabindex")&&t.getAttribute("tabindex")!==-1||t.hasAttribute("contenteditable"))}}Zc.prototype.options_={pauseOnOpen:!0,temporary:!0};We.registerComponent("ModalDialog",Zc);class Au 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})},Do(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,n=this.length;i=0;t--)if(e[t].enabled){av(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&av(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{this.changing_||(this.changing_=!0,av(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 ov=function(s,e){for(let t=0;t=0;t--)if(e[t].selected){ov(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let t=0;t{this.changing_||(this.changing_=!0,ov(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 Db extends Au{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 O4{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;t0&&(he.console&&he.console.groupCollapsed&&he.console.groupCollapsed(`Text Track parsing errors for ${e.src}`),i.forEach(n=>Ei.error(n)),he.console&&he.console.groupEnd&&he.console.groupEnd()),t.flush()},X2=function(s,e){const t={uri:s},i=Ep(s);i&&(t.cors=i);const n=e.tech_.crossOrigin()==="use-credentials";n&&(t.withCredentials=n),ek(t,Ts(this,function(r,a,u){if(r)return Ei.error(r,a);e.loaded_=!0,typeof he.WebVTT!="function"?e.tech_&&e.tech_.any(["vttjsloaded","vttjserror"],c=>{if(c.type==="vttjserror"){Ei.error(`vttjs failed to load, stopping trying to process ${e.src}`);return}return Y2(u,e)}):Y2(u,e)}))};class Xh extends Lb{constructor(e={}){if(!e.tech)throw new Error("A tech was not provided.");const t=cs(e,{kind:B4[e.kind]||"subtitles",language:e.language||e.srclang||""});let i=W2[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 A0(this.cues_),a=new A0(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){W2[d]&&i!==d&&(i=d,!this.preload_&&i!=="disabled"&&this.cues.length===0&&X2(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 a;const d=this.tech_.currentTime(),f=[];for(let p=0,y=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=Ro.LOADED,this.trigger({type:"load",target:this})})}}Ro.prototype.allowedEvents_={load:"load"};Ro.NONE=0;Ro.LOADING=1;Ro.LOADED=2;Ro.ERROR=3;const Xr={audio:{ListClass:Xk,TrackClass:Jk,capitalName:"Audio"},video:{ListClass:Qk,TrackClass:eC,capitalName:"Video"},text:{ListClass:Db,TrackClass:Xh,capitalName:"Text"}};Object.keys(Xr).forEach(function(s){Xr[s].getterName=`${s}Tracks`,Xr[s].privateName=`${s}Tracks_`});const Vc={remoteText:{ListClass:Db,TrackClass:Xh,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:O4,TrackClass:Ro,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},Yn=Object.assign({},Xr,Vc);Vc.names=Object.keys(Vc);Xr.names=Object.keys(Xr);Yn.names=[].concat(Vc.names).concat(Xr.names);function U4(s,e,t,i,n={}){const r=s.textTracks();n.kind=e,t&&(n.label=t),i&&(n.language=i),n.tech=s;const a=new Yn.text.TrackClass(n);return r.addTrack(a),a}class gi extends We{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}),Yn.names.forEach(i=>{const n=Yn[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 Yn.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 ma(0,0)}bufferedPercent(){return Yk(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 js(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?ma(0,0):ma()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){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(!he.WebVTT)if(yt.body.contains(this.el())){if(!this.options_["vtt.js"]&&$c(b2)&&Object.keys(b2).length>0){this.trigger("vttjsloaded");return}const e=yt.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}),he.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"),a=()=>{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=Qr();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 gi.canPlayType(e.type)}static isTech(e){return e.prototype instanceof gi||e instanceof gi||e===gi}static registerTech(e,t){if(gi.techs_||(gi.techs_={}),!gi.isTech(t))throw new Error(`Tech ${e} must be a Tech`);if(!gi.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!gi.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return e=Ws(e),gi.techs_[e]=t,gi.techs_[wh(e)]=t,e!=="Tech"&&gi.defaultTechOrder_.push(e),t}static getTech(e){if(e){if(gi.techs_&&gi.techs_[e])return gi.techs_[e];if(e=Ws(e),he&&he.videojs&&he.videojs[e])return Ei.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),he.videojs[e]}}}Yn.names.forEach(function(s){const e=Yn[s];gi.prototype[e.getterName]=function(){return this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName]}});gi.prototype.featuresVolumeControl=!0;gi.prototype.featuresMuteControl=!0;gi.prototype.featuresFullscreenResize=!1;gi.prototype.featuresPlaybackRate=!1;gi.prototype.featuresProgressEvents=!1;gi.prototype.featuresSourceset=!1;gi.prototype.featuresTimeupdateEvents=!1;gi.prototype.featuresNativeTextTracks=!1;gi.prototype.featuresVideoFrameCallback=!1;gi.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;ruu(e,vu[e.type],t,s),1)}function H4(s,e){s.forEach(t=>t.setTech&&t.setTech(e))}function z4(s,e,t){return s.reduceRight(Nb(t),e[t]())}function G4(s,e,t,i){return e[t](s.reduce(Nb(t),i))}function Q2(s,e,t,i=null){const n="call"+Ws(t),r=s.reduce(Nb(n),i),a=r===C0,u=a?null:e[t](r);return K4(s,t,u,a),u}const V4={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},q4={setCurrentTime:1,setMuted:1,setVolume:1},Z2={play:1,pause:1};function Nb(s){return(e,t)=>e===C0?C0:t[s]?t[s](e):e}function K4(s,e,t,i){for(let n=s.length-1;n>=0;n--){const r=s[n];r[e]&&r[e](i,t)}}function W4(s){k0.hasOwnProperty(s.id())&&delete k0[s.id()]}function Y4(s,e){const t=k0[s.id()];let i=null;if(t==null)return i=e(s),k0[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 eE=S0?10009:_0?461:8,nc={codes:{play:415,pause:19,ff:417,rw:412,back:eE},names:{415:"play",19:"pause",417:"ff",412:"rw",[eE]:"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}},tE=5;class J4 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(nc.isEventKey(t,"play")||nc.isEventKey(t,"pause")||nc.isEventKey(t,"ff")||nc.isEventKey(t,"rw")){t.preventDefault();const i=nc.getEventName(t);this.performMediaAction_(i)}else nc.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()+tE);break;case"rw":this.userSeek_(this.player_.currentTime()-tE);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(a=>a!==t&&this.isInDirection_(i.boundingClientRect,a.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 a of t){const u=a.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"&&Ei.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=ri(e,t,i);return this.player_.options_.experimentalSvgIcons||n.appendChild(ri("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(n),n}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=ri("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,Nl(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)}}We.registerComponent("ClickableComponent",wp);class Ex extends wp{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 ri("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(ri("picture",{className:"vjs-poster",tabIndex:-1},{},ri("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()?Pa(this.player_.play()):this.player_.pause())}}Ex.prototype.crossorigin=Ex.prototype.crossOrigin;We.registerComponent("PosterImage",Ex);const Yr="#222",iE="#ccc",tB={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 lv(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 Ca(s,e,t){try{s.style[e]=t}catch{return}}function sE(s){return s?`${s}px`:""}class iB extends We{constructor(e,t,i){super(e,t,i);const n=a=>this.updateDisplay(a),r=a=>{this.updateDisplayOverlay(),this.updateDisplay(a)};e.on("loadstart",a=>this.toggleDisplay(a)),e.on("useractive",n),e.on("userinactive",n),e.on("texttrackchange",n),e.on("loadedmetadata",a=>{this.updateDisplayOverlay(),this.preselectTrack(a)}),e.ready(Ts(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",r),e.on("playerresize",r);const a=he.screen.orientation||he,u=he.screen.orientation?"change":"orientationchange";a.addEventListener(u,r),e.on("dispose",()=>a.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()||!he.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,a=0;Math.abs(i-n)>.1&&(i>n?r=Math.round((e-t*n)/2):a=Math.round((t-e/n)/2)),Ca(this.el_,"insetInline",sE(r)),Ca(this.el_,"insetBlock",sE(a))}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 a=r.displayState;if(t.color&&(a.firstChild.style.color=t.color),t.textOpacity&&Ca(a.firstChild,"color",lv(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(a.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&Ca(a.firstChild,"backgroundColor",lv(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?Ca(a,"backgroundColor",lv(t.windowColor,t.windowOpacity)):a.style.backgroundColor=t.windowColor),t.edgeStyle&&(t.edgeStyle==="dropshadow"?a.firstChild.style.textShadow=`2px 2px 3px ${Yr}, 2px 2px 4px ${Yr}, 2px 2px 5px ${Yr}`:t.edgeStyle==="raised"?a.firstChild.style.textShadow=`1px 1px ${Yr}, 2px 2px ${Yr}, 3px 3px ${Yr}`:t.edgeStyle==="depressed"?a.firstChild.style.textShadow=`1px 1px ${iE}, 0 1px ${iE}, -1px -1px ${Yr}, 0 -1px ${Yr}`:t.edgeStyle==="uniform"&&(a.firstChild.style.textShadow=`0 0 4px ${Yr}, 0 0 4px ${Yr}, 0 0 4px ${Yr}, 0 0 4px ${Yr}`)),t.fontPercent&&t.fontPercent!==1){const u=he.parseFloat(a.style.fontSize);a.style.fontSize=u*t.fontPercent+"px",a.style.height="auto",a.style.top="auto"}t.fontFamily&&t.fontFamily!=="default"&&(t.fontFamily==="small-caps"?a.firstChild.style.fontVariant="small-caps":a.firstChild.style.fontFamily=tB[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),typeof he.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){Pa(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();Ah(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}iC.prototype.controlText_="Play Video";We.registerComponent("BigPlayButton",iC);class nB extends Gn{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)}}We.registerComponent("CloseButton",nB);class sC extends Gn{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()?Pa(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))}}sC.prototype.controlText_="Play";We.registerComponent("PlayToggle",sC);class Jc extends We{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=ri("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)} `},{role:"presentation"});return t.appendChild(i),this.contentEl_=ri("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=wu(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,Ei.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_=yt.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";We.registerComponent("TimeDisplay",Jc);class Ob 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)}}Ob.prototype.labelText_="Current Time";Ob.prototype.controlText_="Current Time";We.registerComponent("CurrentTimeDisplay",Ob);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";We.registerComponent("DurationDisplay",Mb);class rB extends We{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}}We.registerComponent("TimeDivider",rB);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(ri("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";We.registerComponent("RemainingTimeDisplay",Pb);class aB extends We{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_=ri("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(ri("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")} `})),this.contentEl_.appendChild(yt.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()}}We.registerComponent("LiveDisplay",aB);class nC extends Gn{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_=ri("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()}}nC.prototype.controlText_="Seek to live, currently playing live";We.registerComponent("SeekToLive",nC);function Qh(s,e,t){return s=Number(s),Math.min(t,Math.max(e,isNaN(s)?e:s))}var oB=Object.freeze({__proto__:null,clamp:Qh});class Bb extends We{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"&&!qa&&e.preventDefault(),Lk(),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;Rk(),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(Qh(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){const t=xp(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")}}We.registerComponent("Slider",Bb);const uv=(s,e)=>Qh(s/e*100,0,100).toFixed(2)+"%";class lB extends We{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=ri("span",{className:"vjs-control-text"}),i=ri("span",{textContent:this.localize("Loaded")}),n=yt.createTextNode(": ");return this.percentageEl_=ri("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(),a=this.partEls_,u=uv(r,n);this.percent_!==u&&(this.el_.style.width=u,Nl(this.percentageEl_,u),this.percent_=u);for(let c=0;ci.length;c--)this.el_.removeChild(a[c-1]);a.length=i.length})}}We.registerComponent("LoadProgressBar",lB);class uB extends We{constructor(e,t){super(e,t),this.update=Ka(Ts(this,this.update),Zr)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){const n=Mh(this.el_),r=zc(this.player_.el()),a=e.width*t;if(!r||!n)return;let u=e.left-r.left+a,c=e.width-a+(r.right-e.right);c||(c=e.width-a,u=a);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){Nl(this.el_,e)}updateTime(e,t,i,n){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;const a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const u=this.player_.liveTracker.liveWindow(),c=u-t*u;r=(c<1?"":"-")+wu(c,u)}else r=wu(i,a);this.update(e,t,r),n&&n()})}}We.registerComponent("TimeTooltip",uB);class Fb extends We{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=Ka(Ts(this,this.update),Zr)}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)}}Fb.prototype.options_={children:[]};!Hn&&!pa&&Fb.prototype.options_.children.push("timeTooltip");We.registerComponent("PlayProgressBar",Fb);class rC extends We{constructor(e,t){super(e,t),this.update=Ka(Ts(this,this.update),Zr)}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`})}}rC.prototype.options_={children:["timeTooltip"]};We.registerComponent("MouseTimeDisplay",rC);class Ap extends Bb{constructor(e,t){t=cs(Ap.prototype.options_,t),t.children=[...t.children];const i=e.options_.disableSeekWhileScrubbingOnMobile&&(Hn||pa)||e.options_.disableSeekWhileScrubbingOnSTV;(!Hn&&!pa||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=Ka(this.update_,Zr),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 yt&&"visibilityState"in yt&&this.on(yt,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){yt.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,Zr))}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(yt.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}",[wu(i,r),wu(r,r)],"{1} of {2}")),this.currentTime_=i,this.duration_=r),this.bar&&this.bar.update(zc(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){Ph(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbing_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Ph(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 a=r.seekableStart(),u=r.liveCurrentTime();if(i=a+n*r.liveWindow(),i>=u&&(i=u),i<=a&&(i=a+.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?Pa(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 yt&&"visibilityState"in yt&&this.off(yt,"visibilitychange",this.toggleVisibility_),super.dispose()}}Ap.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar",stepSeconds:5,pageMultiplier:12};We.registerComponent("SeekBar",Ap);class aC extends We{constructor(e,t){super(e,t),this.handleMouseMove=Ka(Ts(this,this.handleMouseMove),Zr),this.throttledHandleMouseSeek=Ka(Ts(this,this.handleMouseSeek),Zr),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(),a=Mh(r);let u=xp(r,e).x;u=Qh(u,0,1),n&&n.update(a,u),i&&i.update(a,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&&Pa(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()}}aC.prototype.options_={children:["seekBar"]};We.registerComponent("ProgressControl",aC);class oC extends Gn{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(){yt.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in he?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 yt.exitPictureInPicture=="function"&&super.show()}}oC.prototype.controlText_="Picture-in-Picture";We.registerComponent("PictureInPictureToggle",oC);class lC extends Gn{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),yt[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()}}lC.prototype.controlText_="Fullscreen";We.registerComponent("FullscreenToggle",lC);const cB=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 dB extends We{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}}We.registerComponent("VolumeLevel",dB);class hB extends We{constructor(e,t){super(e,t),this.update=Ka(Ts(this,this.update),Zr)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,n){if(!i){const r=zc(this.el_),a=zc(this.player_.el()),u=e.width*t;if(!a||!r)return;const c=e.left-a.left+u,d=e.width-u+(a.right-e.right);let f=r.width/2;cr.width&&(f=r.width),this.el_.style.right=`-${f}px`}this.write(`${n}%`)}write(e){Nl(this.el_,e)}updateVolume(e,t,i,n,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,n.toFixed(0)),r&&r()})}}We.registerComponent("VolumeLevelTooltip",hB);class uC extends We{constructor(e,t){super(e,t),this.update=Ka(Ts(this,this.update),Zr)}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`})}}uC.prototype.options_={children:["volumeLevelTooltip"]};We.registerComponent("MouseVolumeLevelDisplay",uC);class kp extends Bb{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){Ph(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),n=zc(i),r=this.vertical();let a=xp(i,e);a=r?a.y:a.x,a=Qh(a,0,1),t.update(n,a,r)}Ph(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)})}}kp.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!Hn&&!pa&&kp.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");kp.prototype.playerEvent="volumechange";We.registerComponent("VolumeBar",kp);class cC extends We{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||$c(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),cB(this,e),this.throttledHandleMouseMove=Ka(Ts(this,this.handleMouseMove),Zr),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)}}cC.prototype.options_={children:["volumeBar"]};We.registerComponent("VolumeControl",cC);const fB=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 dC extends Gn{constructor(e,t){super(e,t),fB(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),yp(this.el_,[0,1,2,3].reduce((i,n)=>i+`${n?" ":""}vjs-vol-${n}`,"")),yu(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}dC.prototype.controlText_="Mute";We.registerComponent("MuteToggle",dC);class hC extends We{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||$c(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"),$r(yt,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),zn(yt,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}hC.prototype.options_={children:["muteToggle","volumeControl"]};We.registerComponent("VolumePanel",hC);class fC extends Gn{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]))}}fC.prototype.controlText_="Skip Forward";We.registerComponent("SkipForward",fC);class mC extends Gn{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]))}}mC.prototype.controlText_="Skip Backward";We.registerComponent("SkipBackward",mC);class pC extends We{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 We&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof We&&(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_=ri(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_),$r(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||yt.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())}}We.registerComponent("Menu",pC);class Ub extends We{constructor(e,t={}){super(e,t),this.menuButton_=new Gn(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=Gn.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(),$r(yt,"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 pC(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=ri("li",{className:"vjs-menu-title",textContent:Ws(this.options_.title),tabIndex:-1}),i=new We(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,u)},a=(...u)=>{this.handleSelectedLanguageChange.apply(this,u)};if(e.on(["loadstart","texttrackchange"],r),n.addEventListener("change",r),n.addEventListener("selectedlanguagechange",a),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),n.removeEventListener("change",r),n.removeEventListener("selectedlanguagechange",a)}),n.onchange===void 0){let u;this.on(["tap","click"],function(){if(typeof he.Event!="object")try{u=new he.Event("change")}catch{}u||(u=yt.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&&a.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&&a.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()}}We.registerComponent("OffTextTrackMenuItem",gC);class ed extends jb{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=Jh){let i;this.label_&&(i=`${this.label_} off`),e.push(new gC(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:a,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});u.addClass(`vjs-${a.kind}-menu-item`),e.push(u)}}return e}}We.registerComponent("TextTrackButton",ed);class yC extends Zh{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(Ws(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(Ws(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 Gb(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,vC),e}}qb.prototype.kinds_=["captions","subtitles"];qb.prototype.controlText_="Subtitles";We.registerComponent("SubsCapsButton",qb);class xC extends Zh{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=(...a)=>{this.handleTracksChange.apply(this,a)};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(ri("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(ri("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)}}Kb.prototype.contentElType="button";We.registerComponent("PlaybackRateMenuItem",Kb);class TC extends Ub{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_=ri("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 Kb(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")}}TC.prototype.controlText_="Playback Rate";We.registerComponent("PlaybackRateMenuButton",TC);class SC extends We{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}We.registerComponent("Spacer",SC);class mB extends SC{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}We.registerComponent("CustomControlSpacer",mB);class _C extends We{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}_C.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};We.registerComponent("ControlBar",_C);class EC extends Zc{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):""}}EC.prototype.options_=Object.assign({},Zc.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});We.registerComponent("ErrorDisplay",EC);class wC extends We{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(),ri("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${Qr()}`)+"-"+t[1].replace(/\W+/g,""),n=ri("option",{id:i,value:this.localize(t[0]),textContent:this.localize(t[1])});return n.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),n}))}}We.registerComponent("TextTrackSelect",wC);class xu extends We{constructor(e,t={}){super(e,t);const i=ri("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 a=this.options_.selectConfigs[r],u=a.className,c=a.id.replace("%s",this.options_.id_);let d=null;const f=`vjs_select_${Qr()}`;if(this.options_.type==="colors"){d=ri("span",{className:u});const y=ri("label",{id:c,className:"vjs-label",textContent:this.localize(a.label)});y.setAttribute("for",f),d.appendChild(y)}const p=new wC(e,{SelectOptions:a.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 ri("fieldset",{className:this.options_.className})}}We.registerComponent("TextTrackFieldset",xu);class AC extends We{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new xu(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 xu(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 a=new xu(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(a)}createEl(){return ri("div",{className:"vjs-track-settings-colors"})}}We.registerComponent("TextTrackSettingsColors",AC);class kC extends We{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,n=new xu(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 xu(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 a=new xu(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(a)}createEl(){return ri("div",{className:"vjs-track-settings-font"})}}We.registerComponent("TextTrackSettingsFont",kC);class CC extends We{constructor(e,t={}){super(e,t);const i=new Gn(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 Gn(e,{controlText:n,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=n,this.addChild(r)}createEl(){return ri("div",{className:"vjs-track-settings-controls"})}}We.registerComponent("TrackSettingsControls",CC);const cv="vjs-text-track-settings",nE=["#000","Black"],rE=["#00F","Blue"],aE=["#0FF","Cyan"],oE=["#0F0","Green"],lE=["#F0F","Magenta"],uE=["#F00","Red"],cE=["#FFF","White"],dE=["#FF0","Yellow"],dv=["1","Opaque"],hv=["0.5","Semi-Transparent"],hE=["0","Transparent"],Tl={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[nE,cE,uE,oE,rE,dE,lE,aE],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[dv,hv,hE],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[cE,nE,uE,oE,rE,dE,lE,aE],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:[dv,hv],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:[hE,hv,dv],className:"vjs-window-opacity vjs-opacity"}};Tl.windowColor.options=Tl.backgroundColor.options;function DC(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function pB(s,e){const t=s.options[s.options.selectedIndex].value;return DC(t,e)}function gB(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()}),Tc(Tl,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 vk(Tl,(e,t,i)=>{const n=pB(this.$(t.selector),t.parser);return n!==void 0&&(e[i]=n),e},{})}setValues(e){Tc(Tl,(t,i)=>{gB(this.$(t.selector),e[i],t.parser)})}setDefaults(){Tc(Tl,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(he.localStorage.getItem(cv))}catch(t){Ei.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?he.localStorage.setItem(cv,JSON.stringify(e)):he.localStorage.removeItem(cv)}catch(t){Ei.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}We.registerComponent("TextTrackSettings",yB);class vB extends We{constructor(e,t){let i=t.ResizeObserver||he.ResizeObserver;t.ResizeObserver===null&&(i=!1);const n=cs({createEl:!i,reportTouchActivity:!1},t);super(e,n),this.ResizeObserver=t.ResizeObserver||he.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=$k(()=>{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 a=this.unloadListener_=function(){zn(this,"resize",r),zn(this,"unload",a),a=null};$r(this.el_.contentWindow,"unload",a),$r(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()}}We.registerComponent("ResizeManager",vB);const xB={trackingThreshold:20,liveTolerance:15};class bB extends We{constructor(e,t){const i=cs(xB,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(he.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 a=this.player_.paused()||this.seekedBehindLive_||Math.abs(n-r)>this.options_.liveTolerance;(!this.timeupdateSeen_||n===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Zr),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()}}We.registerComponent("LiveTracker",bB);class TB extends We{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:ri("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${Qr()}`}),description:ri("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${Qr()}`})},ri("div",{className:"vjs-title-bar"},{},xk(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],a=this.els[n],u=i[n];bp(a),r&&Nl(a,r),t&&(t.removeAttribute(u),r&&t.setAttribute(u,a.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}}We.registerComponent("TitleBar",TB);const SB={initialDisplay:4e3,position:[],takeFocus:!1};class _B extends Gn{constructor(e,t){t=cs(SB,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=ri("button",{},{type:"button",class:this.buildCSSClass()},ri("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()}}We.registerComponent("TransientButton",_B);const wx=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;iLC([s.el(),he.HTMLMediaElement.prototype,he.Element.prototype,EB],"innerHTML"),fE=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=wB(s),n=r=>(...a)=>{const u=r.apply(e,a);return wx(s),u};["append","appendChild","insertAdjacentHTML"].forEach(r=>{e[r]&&(t[r]=e[r],e[r]=n(t[r]))}),Object.defineProperty(e,"innerHTML",cs(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_)},AB=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?Zk(he.Element.prototype.getAttribute.call(this,"src")):""},set(s){return he.Element.prototype.setAttribute.call(this,"src",s),s}}),kB=s=>LC([s.el(),he.HTMLMediaElement.prototype,AB],"src"),CB=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=kB(s),i=e.setAttribute,n=e.load;Object.defineProperty(e,"src",cs(t,{set:r=>{const a=t.set.call(e,r);return s.triggerSourceset(e.src),a}})),e.setAttribute=(r,a)=>{const u=i.call(e,r,a);return/src/i.test(r)&&s.triggerSourceset(e.src),u},e.load=()=>{const r=n.call(e);return wx(s)||(s.triggerSourceset(""),fE(s)),r},e.currentSrc?s.triggerSourceset(e.currentSrc):wx(s)||fE(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=n,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class Lt extends gi{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 a=r.length;const u=[];for(;a--;){const c=r[a];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")&&Ep(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[Vc.remoteText.getterName]().trigger(c)},addtrack(u){n.addTrack(u.track)},removetrack(u){n.removeTrack(u.track)}},a=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",a),this.on("dispose",u=>this.off("loadstart",a))}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),Lt.disposeMediaElement(e),e=i}else{e=yt.createElement("video");const i=this.options_.tag&&bl(this.options_.tag),n=cs({},i);(!Oh||this.options_.nativeControlsForTouch!==!0)&&delete n.controls,Ck(e,Object.assign(n,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&Hc(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&&gp?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){Ei(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&pa&&qa&&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)Pa(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 Ei.error("Invalid source URL."),!1;const i={src:e};t&&(i.type=t);const n=ri("source",{},i);return this.el_.appendChild(n),!0}removeSourceElement(e){if(!e)return Ei.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 Ei.warn(`No matching source element found with src: ${e}`),!1}reset(){Lt.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=yt.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),he.performance&&(e.creationTime=he.performance.now()),e}}hp(Lt,"TEST_VID",function(){if(!Yc())return;const s=yt.createElement("video"),e=yt.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});Lt.isSupported=function(){try{Lt.TEST_VID.volume=.5}catch{return!1}return!!(Lt.TEST_VID&&Lt.TEST_VID.canPlayType)};Lt.canPlayType=function(s){return Lt.TEST_VID.canPlayType(s)};Lt.canPlaySource=function(s,e){return Lt.canPlayType(s.type)};Lt.canControlVolume=function(){try{const s=Lt.TEST_VID.volume;Lt.TEST_VID.volume=s/2+.1;const e=s!==Lt.TEST_VID.volume;return e&&Hn?(he.setTimeout(()=>{Lt&&Lt.prototype&&(Lt.prototype.featuresVolumeControl=s!==Lt.TEST_VID.volume)}),!1):e}catch{return!1}};Lt.canMuteVolume=function(){try{const s=Lt.TEST_VID.muted;return Lt.TEST_VID.muted=!s,Lt.TEST_VID.muted?Hc(Lt.TEST_VID,"muted","muted"):vp(Lt.TEST_VID,"muted","muted"),s!==Lt.TEST_VID.muted}catch{return!1}};Lt.canControlPlaybackRate=function(){if(pa&&qa&&fp<58)return!1;try{const s=Lt.TEST_VID.playbackRate;return Lt.TEST_VID.playbackRate=s/2+.1,s!==Lt.TEST_VID.playbackRate}catch{return!1}};Lt.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty(yt.createElement("video"),"src",{get:s,set:s}),Object.defineProperty(yt.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty(yt.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty(yt.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};Lt.supportsNativeTextTracks=function(){return gp||Hn&&qa};Lt.supportsNativeVideoTracks=function(){return!!(Lt.TEST_VID&&Lt.TEST_VID.videoTracks)};Lt.supportsNativeAudioTracks=function(){return!!(Lt.TEST_VID&&Lt.TEST_VID.audioTracks)};Lt.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]){hp(Lt.prototype,s,()=>Lt[e](),!0)});Lt.prototype.featuresVolumeControl=Lt.canControlVolume();Lt.prototype.movingMediaElementInDOM=!Hn;Lt.prototype.featuresFullscreenResize=!0;Lt.prototype.featuresProgressEvents=!0;Lt.prototype.featuresTimeupdateEvents=!0;Lt.prototype.featuresVideoFrameCallback=!!(Lt.TEST_VID&&Lt.TEST_VID.requestVideoFrameCallback);Lt.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{}})()}};Lt.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){Lt.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){Lt.prototype["set"+Ws(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){Lt.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){Lt.prototype["set"+Ws(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){Lt.prototype[s]=function(){return this.el_[s]()}});gi.withSourceHandlers(Lt);Lt.nativeSourceHandler={};Lt.nativeSourceHandler.canPlayType=function(s){try{return Lt.TEST_VID.canPlayType(s)}catch{return""}};Lt.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return Lt.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=Ib(s.src);return Lt.nativeSourceHandler.canPlayType(`video/${t}`)}return""};Lt.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};Lt.nativeSourceHandler.dispose=function(){};Lt.registerSourceHandler(Lt.nativeSourceHandler);gi.registerTech("Html5",Lt);const RC=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],fv={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},Ax=["tiny","xsmall","small","medium","large","xlarge","huge"],Zm={};Ax.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;Zm[s]=`vjs-layout-${e}`});const DB={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let Ms=class fc extends We{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${Qr()}`,t=Object.assign(fc.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const a=e.closest("[lang]");a&&(t.language=a.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=a=>this.documentFullscreenChange_(a),this.boundFullWindowOnEscKey_=a=>this.fullWindowOnEscKey(a),this.boundUpdateStyleEl_=a=>this.updateStyleEl_(a),this.boundApplyInitTime_=a=>this.applyInitTime_(a),this.boundUpdateCurrentBreakpoint_=a=>this.updateCurrentBreakpoint_(a),this.boundHandleTechClick_=a=>this.handleTechClick_(a),this.boundHandleTechDoubleClick_=a=>this.handleTechDoubleClick_(a),this.boundHandleTechTouchStart_=a=>this.handleTechTouchStart_(a),this.boundHandleTechTouchMove_=a=>this.handleTechTouchMove_(a),this.boundHandleTechTouchEnd_=a=>this.handleTechTouchEnd_(a),this.boundHandleTechTap_=a=>this.handleTechTap_(a),this.boundUpdatePlayerHeightOnAudioOnlyMode_=a=>this.updatePlayerHeightOnAudioOnlyMode_(a),this.isFullscreen_=!1,this.log=gk(this.id_),this.fsApi_=x0,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&&bl(e),this.language(this.options_.language),t.languages){const a={};Object.getOwnPropertyNames(t.languages).forEach(function(u){a[u.toLowerCase()]=t.languages[u]}),this.languages_=a}else this.languages_=fc.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(a=>{if(typeof this[a]!="function")throw new Error(`plugin "${a}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),kb(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&($r(yt,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const n=cs(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(a=>{this[a](t.plugins[a])}),t.debug&&this.debug(!0),this.options_.playerOptions=n,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const u=new he.DOMParser().parseFromString(Z4,"image/svg+xml");if(u.querySelector("parsererror"))Ei.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 J4(this),this.addClass("vjs-spatial-navigation-enabled")),Oh&&this.addClass("vjs-touch-enabled"),Hn||this.addClass("vjs-workinghover"),fc.players[this.id_]=this;const r=px.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",a=>this.listenForUserActivity_(a)),this.on("keydown",a=>this.handleKeyDown(a)),this.on("languagechange",a=>this.handleLanguagechange(a)),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"),zn(yt,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),zn(yt,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),fc.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),W4(this),Yn.names.forEach(e=>{const t=Yn[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=bl(e);if(n){for(t=this.el_=e,e=this.tag=yt.createElement("video");t.children.length;)e.appendChild(t.firstChild);Eh(t,"video-js")||yu(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",qa&&mp&&(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 a=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(c=>Ek[c]).map(c=>"vjs-device-"+c.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),he.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=Uk("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"){Ei.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)){Ei.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,Do(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),A4(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(he.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(":"),a=r[1]/r[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/a:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*a,/^[^a-zA-Z]/.test(this.id())?n="dimensions-"+this.id():n=this.id()+"-dimensions",this.addClass(n),jk(this.styleEl_,` .${n} { width: ${e}px; height: ${t}px; } .${n}.vjs-fluid:not(.vjs-audio-only-mode) { padding-top: ${a*100}%; } `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=Ws(e),n=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(gi.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 a={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};Yn.names.forEach(c=>{const d=Yn[c];a[d.getterName]=this[d.privateName]}),Object.assign(a,this.options_[i]),Object.assign(a,this.options_[n]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);const u=gi.getTech(e);if(!u)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new u(a),this.tech_.ready(Ts(this,this.handleTechReady_),!0),_x.jsonToTextTracks(this.textTracksJson_||[],this.tech_),RC.forEach(c=>{this.on(this.tech_,c,d=>this[`handleTech${Ws(c)}_`](d))}),Object.keys(fv).forEach(c=>{this.on(this.tech_,c,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${fv[c]}_`].bind(this),event:d});return}this[`handleTech${fv[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)&&yx(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Yn.names.forEach(e=>{const t=Yn[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=_x.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&&Ei.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":px}}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 a=this.play();if(Ah(a))return a.catch(u=>{throw r(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${u||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),Ah(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Ah(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=Q4(this,t)),this.cache_.source=cs({},e,{src:t,type:i});const n=this.cache_.sources.filter(c=>c.src&&c.src===t),r=[],a=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 a=this.techGet_("currentSrc");this.lastSource_.tech=a,this.updateSourceCaches_(a)})}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()?Pa(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()&&!yt.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=yt[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 q4)return G4(this.middleware_,this.tech_,e,t);if(e in Z2)return Q2(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw Ei(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in V4)return z4(this.middleware_,this.tech_,e);if(e in Z2)return Q2(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(Ei(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(Ei(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(Ei(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Pa){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(gp||Hn);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=a=>{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")||ma(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=ma(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=ma(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return Yk(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",a)}function a(){r(),i()}function u(d,f){r(),n(f)}t.one("fullscreenchange",a),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",a),e.off("fullscreenchange",r)}function r(){n(),t()}function a(c,d){n(),i(d)}e.one("fullscreenchange",r),e.one("fullscreenerror",a);const u=e.exitFullscreenHelper_();u&&(u.then(n,n),u.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=yt[this.fsApi_.exitFullscreen]();return e&&Pa(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=yt.documentElement.style.overflow,$r(yt,"keydown",this.boundFullWindowOnEscKey_),yt.documentElement.style.overflow="hidden",yu(yt.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,zn(yt,"keydown",this.boundFullWindowOnEscKey_),yt.documentElement.style.overflow=this.docOrigOverflow,yp(yt.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&&he.documentPictureInPicture){const e=yt.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(ri("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),he.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(Pk(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 yt&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(he.documentPictureInPicture&&he.documentPictureInPicture.window)return he.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in yt)return yt.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(n=>{const r=n.tagName.toLowerCase();if(n.isContentEditable)return!0;const a=["button","checkbox","hidden","radio","reset","submit"];return r==="input"?a.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=a=>e.key.toLowerCase()==="f",muteKey:n=a=>e.key.toLowerCase()==="m",playPauseKey:r=a=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=We.getComponent("FullscreenToggle");yt[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else n.call(this,e)?(e.preventDefault(),e.stopPropagation(),We.getComponent("MuteToggle").prototype.handleClick.call(this,e)):r.call(this,e)&&(e.preventDefault(),e.stopPropagation(),We.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,n=this.options_.techOrder;i[u,gi.getTech(u)]).filter(([u,c])=>c?c.isSupported():(Ei.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(y=>{if(f=d(p,y),f)return!0})),f};let n;const r=u=>(c,d)=>u(d,c),a=([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(a)):n=i(t,e,a),n||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=tC(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]),$4(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}H4(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?Vk(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();Pa(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}),Do(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(Dl("beforeerror").forEach(t=>{const i=t(this,e);if(!(Va(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 js(e),this.addClass("vjs-error"),Ei.error(`(CODE:${this.error_.code} ${js.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),Dl("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())},a=function(){n(),this.clearInterval(e),e=this.setInterval(n,250)},u=function(p){n(),this.clearInterval(e)};this.on("mousedown",a),this.on("mousemove",r),this.on("mouseup",u),this.on("mouseleave",u);const c=this.getChild("controlBar");c&&!Hn&&!pa&&(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(),Do(this)&&this.trigger("languagechange"))}languages(){return cs(fc.prototype.options_.languages,this.languages_)}toJSON(){const e=cs(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:a||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:D0(n.poster)}]),n}return cs(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=bl(e),n=i["data-setup"];if(Eh(e,"vjs-fill")&&(i.fill=!0),Eh(e,"vjs-fluid")&&(i.fluid=!0),n!==null)try{Object.assign(i,JSON.parse(n||"{}"))}catch(r){Ei.error("data-setup",r)}if(Object.assign(t,i),e.hasChildNodes()){const r=e.childNodes;for(let a=0,u=r.length;atypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};Ms.prototype.videoTracks=()=>{};Ms.prototype.audioTracks=()=>{};Ms.prototype.textTracks=()=>{};Ms.prototype.remoteTextTracks=()=>{};Ms.prototype.remoteTextTrackEls=()=>{};Yn.names.forEach(function(s){const e=Yn[s];Ms.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});Ms.prototype.crossorigin=Ms.prototype.crossOrigin;Ms.players={};const sh=he.navigator;Ms.prototype.options_={techOrder:gi.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:sh&&(sh.languages&&sh.languages[0]||sh.userLanguage||sh.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};RC.forEach(function(s){Ms.prototype[`handleTech${Ws(s)}_`]=function(){return this.trigger(s)}});We.registerComponent("Player",Ms);const L0="plugin",Ec="activePlugins_",pc={},R0=s=>pc.hasOwnProperty(s),Jm=s=>R0(s)?pc[s]:void 0,IC=(s,e)=>{s[Ec]=s[Ec]||{},s[Ec][e]=!0},I0=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},LB=function(s,e){const t=function(){I0(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return IC(this,s),I0(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},mE=(s,e)=>(e.prototype.name=s,function(...t){I0(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,I0(this,i.getEventHash()),i});class xr{constructor(e){if(this.constructor===xr)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),kb(this),delete this.trigger,Gk(this,this.constructor.defaultState),IC(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 Qc(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[Ec][e]=!1,this.player=this.state=null,t[e]=mE(e,pc[e])}static isBasic(e){const t=typeof e=="string"?Jm(e):e;return typeof t=="function"&&!xr.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(R0(e))Ei.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(Ms.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 pc[e]=t,e!==L0&&(xr.isBasic(t)?Ms.prototype[e]=LB(e,t):Ms.prototype[e]=mE(e,t)),t}static deregisterPlugin(e){if(e===L0)throw new Error("Cannot de-register base plugin.");R0(e)&&(delete pc[e],delete Ms.prototype[e])}static getPlugins(e=Object.keys(pc)){let t;return e.forEach(i=>{const n=Jm(i);n&&(t=t||{},t[i]=n)}),t}static getPluginVersion(e){const t=Jm(e);return t&&t.VERSION||""}}xr.getPlugin=Jm;xr.BASE_PLUGIN_NAME=L0;xr.registerPlugin(L0,xr);Ms.prototype.usingPlugin=function(s){return!!this[Ec]&&this[Ec][s]===!0};Ms.prototype.hasPlugin=function(s){return!!R0(s)};function RB(s,e){let t=!1;return function(...i){return t||Ei.warn(s),t=!0,e.apply(this,i)}}function ga(s,e,t,i){return RB(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var IB={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 NC=s=>s.indexOf("#")===0?s.slice(1):s;function Le(s,e,t){let i=Le.getPlayer(s);if(i)return e&&Ei.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const n=typeof s=="string"?Ll("#"+NC(s)):s;if(!Xc(n))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in n?n.getRootNode()instanceof he.ShadowRoot:!1)?n.getRootNode():n.ownerDocument.body;(!n.ownerDocument.defaultView||!a.contains(n))&&Ei.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)),Dl("beforesetup").forEach(c=>{const d=c(n,cs(e));if(!Va(d)||Array.isArray(d)){Ei.error("please return an object in beforesetup hooks");return}e=cs(e,d)});const u=We.getComponent("Player");return i=new u(n,e,t),Dl("setup").forEach(c=>c(i)),i}Le.hooks_=wo;Le.hooks=Dl;Le.hook=h4;Le.hookOnce=f4;Le.removeHook=pk;if(he.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&Yc()){let s=Ll(".vjs-styles-defaults");if(!s){s=Uk("vjs-styles-defaults");const e=Ll("head");e&&e.insertBefore(s,e.firstChild),jk(s,` .video-js { width: 300px; height: 150px; } .vjs-fluid:not(.vjs-audio-only-mode) { padding-top: 56.25% } `)}}xx(1,Le);Le.VERSION=px;Le.options=Ms.prototype.options_;Le.getPlayers=()=>Ms.players;Le.getPlayer=s=>{const e=Ms.players;let t;if(typeof s=="string"){const i=NC(s),n=e[i];if(n)return n;t=Ll("#"+i)}else t=s;if(Xc(t)){const{player:i,playerId:n}=t;if(i||e[n])return i||e[n]}};Le.getAllPlayers=()=>Object.keys(Ms.players).map(s=>Ms.players[s]).filter(Boolean);Le.players=Ms.players;Le.getComponent=We.getComponent;Le.registerComponent=(s,e)=>(gi.isTech(e)&&Ei.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),We.registerComponent.call(We,s,e));Le.getTech=gi.getTech;Le.registerTech=gi.registerTech;Le.use=j4;Object.defineProperty(Le,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(Le.middleware,"TERMINATOR",{value:C0,writeable:!1,enumerable:!0});Le.browser=Ek;Le.obj=g4;Le.mergeOptions=ga(9,"videojs.mergeOptions","videojs.obj.merge",cs);Le.defineLazyProperty=ga(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",hp);Le.bind=ga(9,"videojs.bind","native Function.prototype.bind",Ts);Le.registerPlugin=xr.registerPlugin;Le.deregisterPlugin=xr.deregisterPlugin;Le.plugin=(s,e)=>(Ei.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),xr.registerPlugin(s,e));Le.getPlugins=xr.getPlugins;Le.getPlugin=xr.getPlugin;Le.getPluginVersion=xr.getPluginVersion;Le.addLanguage=function(s,e){return s=(""+s).toLowerCase(),Le.options.languages=cs(Le.options.languages,{[s]:e}),Le.options.languages[s]};Le.log=Ei;Le.createLogger=gk;Le.time=R4;Le.createTimeRange=ga(9,"videojs.createTimeRange","videojs.time.createTimeRanges",ma);Le.createTimeRanges=ga(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",ma);Le.formatTime=ga(9,"videojs.formatTime","videojs.time.formatTime",wu);Le.setFormatTime=ga(9,"videojs.setFormatTime","videojs.time.setFormatTime",Kk);Le.resetFormatTime=ga(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",Wk);Le.parseUrl=ga(9,"videojs.parseUrl","videojs.url.parseUrl",Rb);Le.isCrossOrigin=ga(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",Ep);Le.EventTarget=Hr;Le.any=Ab;Le.on=$r;Le.one=Sp;Le.off=zn;Le.trigger=Qc;Le.xhr=ek;Le.TrackList=Au;Le.TextTrack=Xh;Le.TextTrackList=Db;Le.AudioTrack=Jk;Le.AudioTrackList=Xk;Le.VideoTrack=eC;Le.VideoTrackList=Qk;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{Le[s]=function(){return Ei.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),Bk[s].apply(null,arguments)}});Le.computedStyle=ga(9,"videojs.computedStyle","videojs.dom.computedStyle",Gc);Le.dom=Bk;Le.fn=w4;Le.num=oB;Le.str=D4;Le.url=F4;Le.Error=IB;class NB{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 N0 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 NB(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=OC,i},MC=function(s){return OB(this,Le.obj.merge({},s))};Le.registerPlugin("qualityLevels",MC);MC.VERSION=OC;const pr=lp,O0=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,ta=s=>Le.log.debug?Le.log.debug.bind(Le,"VHS:",`${s} >`):function(){};function Qi(...s){const e=Le.obj||Le;return(e.merge||e.mergeOptions).apply(e,s)}function Sn(...s){const e=Le.time||Le;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function MB(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 Ba=1/30,Fa=Ba*3,PC=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},km=function(s,e){return PC(s,function(t){return t-Ba>=e})},PB=function(s){if(s.length<2)return Sn();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(", ")},FB=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},pu=s=>{const e=[];for(let t=0;tr)){if(e>n&&e<=r){t+=r-e;continue}t+=r-n}}return t},Yb=(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},kx=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),[]),FC=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},UC=({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},jC=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=FC(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},jB=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+=Yb(s,n),typeof n.start<"u")return{result:t+n.start,precise:!0}}return{result:t,precise:!1}},$B=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 he.Infinity}return $C(s,e,t)},kh=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(a+=f.duration,r){if(a<0)continue}else if(a+Ba<=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n-kh({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(a-=s.targetDuration,a<0)return{partIndex:u[0]&&u[0].partIndex||null,segmentIndex:u[0]&&u[0].segmentIndex||0,startTime:e};c=0}for(let d=c;dBa,y=a===0,v=p&&a+Ba>=0;if(!((y||v)&&d!==u.length-1)){if(r){if(a>0)continue}else if(a-Ba>=0)continue;return{partIndex:f.partIndex,segmentIndex:f.segmentIndex,startTime:n+kh({defaultDuration:s.targetDuration,durationList:u,startIndex:c,endIndex:d})}}}return{segmentIndex:u[u.length-1].segmentIndex,partIndex:u[u.length-1].partIndex,startTime:e}},GC=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Xb=function(s){return s.excludeUntil&&s.excludeUntil===1/0},Cp=function(s){const e=GC(s);return!s.disabled&&!e},GB=function(s){return s.disabled},VB=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=>Cp(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),pE=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},ef=s=>{if(!s||!s.playlists||!s.playlists.length)return pE(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;esk(r))||pE(s,r=>Qb(t,r))))return!1}return!0};var gr={liveEdgeDelay:jC,duration:HC,seekable:HB,getMediaInfoForTime:zB,isEnabled:Cp,isDisabled:GB,isExcluded:GC,isIncompatible:Xb,playlistEnd:zC,isAes:VB,hasAttribute:VC,estimateSegmentRequestTime:qB,isLowestEnabledRendition:Cx,isAudioOnly:ef,playlistMatch:Qb,segmentDurationWithParts:Yb};const{log:qC}=Le,wc=(s,e)=>`${s}-${e}`,KC=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,KB=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:n=[],llhls:r})=>{const a=new O3;s&&a.on("warn",s),e&&a.on("info",e),i.forEach(d=>a.addParser(d)),n.forEach(d=>a.addTagMapper(d)),a.push(t),a.end();const u=a.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=FC(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}`}),qC.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},td=(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)}})},WC=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},WB=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];WC({playlist:t,id:wc(e,t.uri)}),t.resolvedUri=pr(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||qC.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},YB=s=>{td(s,e=>{e.uri&&(e.resolvedUri=pr(s.uri,e.uri))})},XB=(s,e)=>{const t=wc(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:he.location.href,resolvedUri:he.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},YC=(s,e,t=KC)=>{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,a={uri:e.uri,requestType:s},u=n&&!r||i;if(t&&r)a.error=sn({},t),a.errorType=Le.Error.NetworkRequestFailed;else if(e.aborted)a.errorType=Le.Error.NetworkRequestAborted;else if(e.timedout)a.errorType=Le.Error.NetworkRequestTimeout;else if(u){const c=i?Le.Error.NetworkBodyParserFailed:Le.Error.NetworkBadStatus;a.errorType=c,a.status=e.status,a.headers=e.headers}return a},QB=ta("CodecUtils"),QC=function(s){const e=s.attributes||{};if(e.CODECS)return Na(e.CODECS)},ZC=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},ZB=(s,e)=>{if(!ZC(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},Bh=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:n})=>{e[t]=e[t]||[],e[t].push(ik(`${i}${n}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){QB(`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},Ch=function(s,e){const t=e.attributes||{},i=Bh(QC(e)||[]);if(ZC(s,e)&&!i.audio&&!ZB(s,e)){const n=Bh(P3(s,t.AUDIO)||[]);n.audio&&(i.audio=n.audio)}return i},{EventTarget:JB}=Le,eF=(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||[],a=UC(e)-1;a>-1&&a!==r.length-1&&(t._HLS_part=a),(a>-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 he.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},tF=(s,e)=>{if(!s)return e;const t=Qi(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 a;for(let u=0;u{!s.resolvedUri&&s.uri&&(s.resolvedUri=pr(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=pr(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=pr(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=pr(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=pr(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=pr(e,t.uri))})},eD=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,Dx=(s,e,t=tD)=>{const i=Qi(s,{}),n=i.playlists[e.id];if(!n||t(n,e))return null;e.segments=eD(e);const r=Qi(n,e);if(r.preloadSegment&&!e.preloadSegment&&delete r.preloadSegment,n.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a{JC(a,r.resolvedUri)});for(let a=0;a{if(a.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},vE=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(n=>{if(!n.attributes)return;const{BANDWIDTH:r,RESOLUTION:a,CODECS:u}=n.attributes;i.push({id:n.id,bandwidth:r,resolution:a,codecs:u})}),{type:e,isLive:t,renditions:i}};let yc=class extends JB{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=ta("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 gE,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=pr(this.main.uri,e.uri);this.llhls&&(t=eF(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:bu({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=KB({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:a}=n.RESOLUTION||{};if(r&&a)return!0;const u=QC(i)||[];return!!Bh(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 a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),WC({playlist:a,uri:i,id:n});const u=Dx(this.main,a);this.targetDuration=a.partTargetDuration||a.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=vE(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),he.clearTimeout(this.mediaUpdateTimeout),he.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new gE,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(he.clearTimeout(this.finalRenditionTimeout),t){const u=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=he.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 a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(u,c)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=O0(e.resolvedUri,c),u)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),this.haveMetadata({playlistString:c.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(he.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&&(he.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=he.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&&(he.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=he.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=he.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:bu({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=O0(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=vE(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,YC(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=eD(i),i.segments.forEach(n=>{JC(n,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||he.location.href;this.main=XB(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 a=i.playlists[r];if(a.attributes["PATHWAY-ID"]===n){const u=a.resolvedUri,c=a.id;if(t){const d=this.createCloneURI_(a.resolvedUri,e),f=wc(n,d),p=this.createCloneAttributes_(n,a.attributes),y=this.createClonePlaylist_(a,f,e,p);i.playlists[r]=y,i.playlists[f]=y,i.playlists[d]=y}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 a in i.mediaGroups[r])if(a===n){for(const u in i.mediaGroups[r][a])i.mediaGroups[r][a][u].playlists.forEach((d,f)=>{const p=i.playlists[d.id],y=p.id,v=p.resolvedUri;delete i.playlists[y],delete i.playlists[v]});delete i.mediaGroups[r][a]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),a=wc(e.ID,r),u=this.createCloneAttributes_(e.ID,t.attributes),c=this.createClonePlaylist_(t,a,e,u);i.playlists[n]=c,i.playlists[a]=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 a in n.mediaGroups[r]){if(a===i)n.mediaGroups[r][t]={};else continue;for(const u in n.mediaGroups[r][a]){const c=n.mediaGroups[r][a][u];n.mediaGroups[r][t][u]=sn({},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,y)=>{const v=n.playlists[p.id],b=KC(r,t,u),S=wc(t,b);if(v&&!n.playlists[S]){const E=this.createClonePlaylist_(v,S,e),L=E.resolvedUri;n.playlists[S]=E,n.playlists[L]=E}d.playlists[y]=this.createClonePlaylist_(p,S,e)})}}})}createClonePlaylist_(e,t,i,n){const r=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:r,uri:r,id:t};return e.segments&&(a.segments=[]),n&&(a.attributes=n),Qi(e,a)}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 Rx=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)},sF=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},nF=(s,e,t,i)=>{!s||!s.size||s.forEach(n=>{n(e,t,i)})},iD=function(){const s=function e(t,i){t=Qi({timeout:45e3},t);const n=e.beforeRequest||Le.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Le.Vhs.xhr._requestCallbackSet||new Set,a=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=sF(r,t);r.delete(n);const d=u(c||t,function(p,y){return nF(a,d,p,y),Rx(d,p,y,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},rF=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=he.BigInt(s.offset)+he.BigInt(s.length)-he.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},Ix=function(s){const e={};return s.byterange&&(e.Range=rF(s.byterange)),e},aF=function(s,e){return s.start(e)+"-"+s.end(e)},oF=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},lF=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},sD=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];rk(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},M0=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},nD=function(s){return s.resolvedUri},rD=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",n,r;for(let a=0;arD(s),cF=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)},fF=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,mF=(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:gr.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},pF=(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*aD)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},gF=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const n=t.getTime();return(i.getTime()-n)/1e3},yF=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=pF(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=hF(e,i.segment);return r&&(n.programDateTime=r.toISOString()),t(null,n)},oD=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:n=!0,tech:r,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!r.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!yF(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const u=mF(s,e);if(!u)return a({message:`${s} was not found in the stream`});const c=u.segment,d=gF(c.dateTimeObject,s);if(u.type==="estimate"){if(t===0)return a({message:`${s} is not buffered yet. Try again`});i(u.estimatedStart+d),r.one("seeked",()=>{oD({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:n,tech:r,callback:a})});return}const f=c.start+d,p=()=>a(null,r.currentTime());r.one("seeked",p),n&&r.pause(),i(f)},pv=(s,e)=>{if(s.readyState===4)return e()},xF=(s,e,t,i)=>{let n=[],r,a=!1;const u=function(p,y,v,b){return y.abort(),a=!0,t(p,y,v,b)},c=function(p,y){if(a)return;if(p)return p.metadata=bu({requestType:i,request:y,error:p}),u(p,y,"",n);const v=y.responseText.substring(n&&n.byteLength||0,y.responseText.length);if(n=q3(n,ak(v,!0)),r=r||hh(n),n.length<10||r&&n.lengthu(p,y,"",n));const b=Tb(n);return b==="ts"&&n.length<188?pv(y,()=>u(p,y,"",n)):!b&&n.length<376?pv(y,()=>u(p,y,"",n)):u(null,y,b,n)},f=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:y,loaded:v}){return Rx(p,null,{statusCode:p.status},c)})}},function(p,y){return Rx(f,p,y,c)});return f},{EventTarget:bF}=Le,xE=function(s,e){if(!tD(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}`},SF=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:n})=>{const r=GP(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:n});return YC(r,e,TF),r},_F=(s,e)=>{td(s,(t,i,n,r)=>{(!e.mediaGroups[i][n]||!(r in e.mediaGroups[i][n]))&&delete s.mediaGroups[i][n][r]})},EF=(s,e,t)=>{let i=!0,n=Qi(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=Dx(n,r.playlists[0],xE);f&&(n=f,c in n.mediaGroups[a][u]||(n.mediaGroups[a][u][c]=r),n.mediaGroups[a][u][c].playlists[0]=n.playlists[d],i=!1)}}),_F(n,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:n},wF=(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,bE=(s,e)=>{const t={};for(const i in s){const r=s[i].sidx;if(r){const a=cp(r);if(!e[a])break;const u=e[a].sidxInfo;wF(u,r)&&(t[a]=e[a])}}return t},AF=(s,e)=>{let i=bE(s.playlists,e);return td(s,(n,r,a,u)=>{if(n.playlists&&n.playlists.length){const c=n.playlists;i=Qi(i,bE(c,e))}}),i};class Nx extends bF{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_=ta("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&&cp(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n]){he.clearTimeout(this.mediaRequest_),this.mediaRequest_=he.setTimeout(()=>i(!1),0);return}const r=O0(e.sidx.resolvedUri),a=(c,d)=>{if(this.requestErrored_(c,d,t))return;const f=this.mainPlaylistLoader_.sidxMapping_,{requestType:p}=d;let y;try{y=YP(ti(d.response).subarray(8))}catch(v){v.metadata=bu({requestType:p,request:d,parseFailure:!0}),this.requestErrored_(v,d,t);return}return f[n]={sidxInfo:e.sidx,sidx:y},vb(e,y,e.sidx.resolvedUri),i(!0)},u="dash-sidx";this.request=xF(r,this.vhs_.xhr,(c,d,f,p)=>{if(c)return a(c,d);if(!f||f!=="mp4"){const b=f||"unknown";return a({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:y,length:v}=e.sidx.byterange;if(p.length>=v+y)return a(c,{response:p.subarray(y,y+v),status:d.status,uri:d.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:Ix({byterange:e.sidx.byterange})},a)},u)}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},he.clearTimeout(this.minimumUpdatePeriodTimeout_),he.clearTimeout(this.mediaRequest_),he.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,he.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(),he.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(he.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){this.isPaused_=!1,he.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=he.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_){he.clearTimeout(this.mediaRequest_),this.mediaRequest_=he.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:a}=n;i.metadata=bu({requestType:a,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=O0(this.mainPlaylistLoader_.srcUrl,n),r){this.handleMain_(),this.syncClientServerClock_(()=>e(n,r));return}return e(n,r)})}syncClientServerClock_(e){const t=VP(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:pr(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:a}=n;return this.error.metadata=bu({requestType:a,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_(){he.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=SF({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=EF(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:a}=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:!a,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_&&(he.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_=he.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_=AF(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=he.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 bn={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 kF=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(A){var C,k,O,P;if(C=x[A],!!C)if(arguments.length===2)for(O=C.length,k=0;k"u")){for(x in q)q.hasOwnProperty(x)&&(q[x]=[x.charCodeAt(0),x.charCodeAt(1),x.charCodeAt(2),x.charCodeAt(3)]);le=new Uint8Array([105,115,111,109]),V=new Uint8Array([97,118,99,49]),te=new Uint8Array([0,0,0,1]),G=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]),J=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:G,audio:J},X=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]),se=new Uint8Array([0,0,0,0,0,0,0,0]),fe=se,pe=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),de=se,oe=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),u=function(x){var A=[],C=0,k,O,P;for(k=1;k>>1,x.samplingfrequencyindex<<7|x.channelcount<<3,6,1,2]))},f=function(){return u(q.ftyp,le,te,le,V)},$=function(x){return u(q.hdlr,ie[x])},p=function(x){return u(q.mdat,x)},F=function(x){var A=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&&(A[12]=x.samplerate>>>24&255,A[13]=x.samplerate>>>16&255,A[14]=x.samplerate>>>8&255,A[15]=x.samplerate&255),u(q.mdhd,A)},H=function(x){return u(q.mdia,F(x),$(x.type),v(x))},y=function(x){return u(q.mfhd,new Uint8Array([0,0,0,0,(x&4278190080)>>24,(x&16711680)>>16,(x&65280)>>8,x&255]))},v=function(x){return u(q.minf,x.type==="video"?u(q.vmhd,oe):u(q.smhd,j),c(),W(x))},b=function(x,A){for(var C=[],k=A.length;k--;)C[k]=I(A[k]);return u.apply(null,[q.moof,y(x)].concat(C))},S=function(x){for(var A=x.length,C=[];A--;)C[A]=N(x[A]);return u.apply(null,[q.moov,L(4294967295)].concat(C).concat(E(x)))},E=function(x){for(var A=x.length,C=[];A--;)C[A]=Q(x[A]);return u.apply(null,[q.mvex].concat(C))},L=function(x){var A=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(q.mvhd,A)},M=function(x){var A=x.samples||[],C=new Uint8Array(4+A.length),k,O;for(O=0;O>>8),P.push(k[ue].byteLength&255),P=P.concat(Array.prototype.slice.call(k[ue]));for(ue=0;ue>>8),ne.push(O[ue].byteLength&255),ne=ne.concat(Array.prototype.slice.call(O[ue]));if(ce=[q.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.width&65280)>>8,C.width&255,(C.height&65280)>>8,C.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(q.avcC,new Uint8Array([1,C.profileIdc,C.profileCompatibility,C.levelIdc,255].concat([k.length],P,[O.length],ne))),u(q.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],C.sarRatio){var me=C.sarRatio[0],Se=C.sarRatio[1];ce.push(u(q.pasp,new Uint8Array([(me&4278190080)>>24,(me&16711680)>>16,(me&65280)>>8,me&255,(Se&4278190080)>>24,(Se&16711680)>>16,(Se&65280)>>8,Se&255])))}return u.apply(null,ce)},A=function(C){return u(q.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(C.channelcount&65280)>>8,C.channelcount&255,(C.samplesize&65280)>>8,C.samplesize&255,0,0,0,0,(C.samplerate&65280)>>8,C.samplerate&255,0,0]),d(C))}})(),R=function(x){var A=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(q.tkhd,A)},I=function(x){var A,C,k,O,P,ne,ue;return A=u(q.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])),ne=Math.floor(x.baseMediaDecodeTime/a),ue=Math.floor(x.baseMediaDecodeTime%a),C=u(q.tfdt,new Uint8Array([1,0,0,0,ne>>>24&255,ne>>>16&255,ne>>>8&255,ne&255,ue>>>24&255,ue>>>16&255,ue>>>8&255,ue&255])),P=92,x.type==="audio"?(k=K(x,P),u(q.traf,A,C,k)):(O=M(x),k=K(x,O.length+P),u(q.traf,A,C,k,O))},N=function(x){return x.duration=x.duration||4294967295,u(q.trak,R(x),H(x))},Q=function(x){var A=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"&&(A[A.length-1]=0),u(q.trex,A)},(function(){var x,A,C;C=function(k,O){var P=0,ne=0,ue=0,ce=0;return k.length&&(k[0].duration!==void 0&&(P=1),k[0].size!==void 0&&(ne=2),k[0].flags!==void 0&&(ue=4),k[0].compositionTimeOffset!==void 0&&(ce=8)),[0,0,P|ne|ue|ce,1,(k.length&4278190080)>>>24,(k.length&16711680)>>>16,(k.length&65280)>>>8,k.length&255,(O&4278190080)>>>24,(O&16711680)>>>16,(O&65280)>>>8,O&255]},A=function(k,O){var P,ne,ue,ce,me,Se;for(ce=k.samples||[],O+=20+16*ce.length,ue=C(ce,O),ne=new Uint8Array(ue.length+ce.length*16),ne.set(ue),P=ue.length,Se=0;Se>>24,ne[P++]=(me.duration&16711680)>>>16,ne[P++]=(me.duration&65280)>>>8,ne[P++]=me.duration&255,ne[P++]=(me.size&4278190080)>>>24,ne[P++]=(me.size&16711680)>>>16,ne[P++]=(me.size&65280)>>>8,ne[P++]=me.size&255,ne[P++]=me.flags.isLeading<<2|me.flags.dependsOn,ne[P++]=me.flags.isDependedOn<<6|me.flags.hasRedundancy<<4|me.flags.paddingValue<<1|me.flags.isNonSyncSample,ne[P++]=me.flags.degradationPriority&61440,ne[P++]=me.flags.degradationPriority&15,ne[P++]=(me.compositionTimeOffset&4278190080)>>>24,ne[P++]=(me.compositionTimeOffset&16711680)>>>16,ne[P++]=(me.compositionTimeOffset&65280)>>>8,ne[P++]=me.compositionTimeOffset&255;return u(q.trun,ne)},x=function(k,O){var P,ne,ue,ce,me,Se;for(ce=k.samples||[],O+=20+8*ce.length,ue=C(ce,O),P=new Uint8Array(ue.length+ce.length*8),P.set(ue),ne=ue.length,Se=0;Se>>24,P[ne++]=(me.duration&16711680)>>>16,P[ne++]=(me.duration&65280)>>>8,P[ne++]=me.duration&255,P[ne++]=(me.size&4278190080)>>>24,P[ne++]=(me.size&16711680)>>>16,P[ne++]=(me.size&65280)>>>8,P[ne++]=me.size&255;return u(q.trun,P)},K=function(k,O){return k.type==="audio"?x(k,O):A(k,O)}})();var Ve={ftyp:f,mdat:p,moof:b,moov:S,initSegment:function(x){var A=f(),C=S(x),k;return k=new Uint8Array(A.byteLength+C.byteLength),k.set(A),k.set(C,A.byteLength),k}},Ze=function(x){var A,C,k=[],O=[];for(O.byteLength=0,O.nalCount=0,O.duration=0,k.byteLength=0,A=0;A1&&(A=x.shift(),x.byteLength-=A.byteLength,x.nalCount-=A.nalCount,x[0][0].dts=A.dts,x[0][0].pts=A.pts,x[0][0].duration+=A.duration),x},Fe=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},qe=function(x,A){var C=Fe();return C.dataOffset=A,C.compositionTimeOffset=x.pts-x.dts,C.duration=x.duration,C.size=4*x.length,C.size+=x.byteLength,x.keyFrame&&(C.flags.dependsOn=2,C.flags.isNonSyncSample=0),C},dt=function(x,A){var C,k,O,P,ne,ue=A||0,ce=[];for(C=0;CZt.ONE_SECOND_IN_TS/2))){for(me=yi()[x.samplerate],me||(me=A[0].data),Se=0;Se=C?x:(A.minSegmentDts=1/0,x.filter(function(k){return k.dts>=C?(A.minSegmentDts=Math.min(A.minSegmentDts,k.dts),A.minSegmentPts=A.minSegmentDts,!0):!1}))},Di=function(x){var A,C,k=[];for(A=0;A=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--},ii.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},ii.prototype.addText=function(x){this.rows[this.rowIdx]+=x},ii.prototype.backspace=function(){if(!this.isEmpty()){var x=this.rows[this.rowIdx];this.rows[this.rowIdx]=x.substr(0,x.length-1)}};var Ht=function(x,A,C){this.serviceNum=x,this.text="",this.currentWindow=new ii(-1),this.windows=[],this.stream=C,typeof A=="string"&&this.createTextDecoder(A)};Ht.prototype.init=function(x,A){this.startPts=x;for(var C=0;C<8;C++)this.windows[C]=new ii(C),typeof A=="function"&&(this.windows[C].beforeRowOverflow=A)},Ht.prototype.setCurrentWindow=function(x){this.currentWindow=this.windows[x]},Ht.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(A){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+x+" encoding. "+A})}};var Kt=function(x){x=x||{},Kt.prototype.init.call(this);var A=this,C=x.captionServices||{},k={},O;Object.keys(C).forEach(P=>{O=C[P],/^SERVICE/.test(P)&&(k[P]=O.encoding)}),this.serviceEncodings=k,this.current708Packet=null,this.services={},this.push=function(P){P.type===3?(A.new708Packet(),A.add708Bytes(P)):(A.current708Packet===null&&A.new708Packet(),A.add708Bytes(P))}};Kt.prototype=new ai,Kt.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Kt.prototype.add708Bytes=function(x){var A=x.ccData,C=A>>>8,k=A&255;this.current708Packet.ptsVals.push(x.pts),this.current708Packet.data.push(C),this.current708Packet.data.push(k)},Kt.prototype.push708Packet=function(){var x=this.current708Packet,A=x.data,C=null,k=null,O=0,P=A[O++];for(x.seq=P>>6,x.sizeCode=P&63;O>5,k=P&31,C===7&&k>0&&(P=A[O++],C=P),this.pushServiceBlock(C,O,k),k>0&&(O+=k-1)},Kt.prototype.pushServiceBlock=function(x,A,C){var k,O=A,P=this.current708Packet.data,ne=this.services[x];for(ne||(ne=this.initService(x,O));O("0"+(Dt&255).toString(16)).slice(-2)).join("")}if(O?(He=[ue,ce],x++):He=[ue],A.textDecoder_&&!k)Se=A.textDecoder_.decode(new Uint8Array(He));else if(O){const Ye=_t(He);Se=String.fromCharCode(parseInt(Ye,16))}else Se=$i(ne|ue);return me.pendingNewLine&&!me.isEmpty()&&me.newLine(this.getPts(x)),me.pendingNewLine=!1,me.addText(Se),x},Kt.prototype.multiByteCharacter=function(x,A){var C=this.current708Packet.data,k=C[x+1],O=C[x+2];return Hi(k)&&Hi(O)&&(x=this.handleText(++x,A,{isMultiByte:!0})),x},Kt.prototype.setCurrentWindow=function(x,A){var C=this.current708Packet.data,k=C[x],O=k&7;return A.setCurrentWindow(O),x},Kt.prototype.defineWindow=function(x,A){var C=this.current708Packet.data,k=C[x],O=k&7;A.setCurrentWindow(O);var P=A.currentWindow;return k=C[++x],P.visible=(k&32)>>5,P.rowLock=(k&16)>>4,P.columnLock=(k&8)>>3,P.priority=k&7,k=C[++x],P.relativePositioning=(k&128)>>7,P.anchorVertical=k&127,k=C[++x],P.anchorHorizontal=k,k=C[++x],P.anchorPoint=(k&240)>>4,P.rowCount=k&15,k=C[++x],P.columnCount=k&63,k=C[++x],P.windowStyle=(k&56)>>3,P.penStyle=k&7,P.virtualRowCount=P.rowCount+1,x},Kt.prototype.setWindowAttributes=function(x,A){var C=this.current708Packet.data,k=C[x],O=A.currentWindow.winAttr;return k=C[++x],O.fillOpacity=(k&192)>>6,O.fillRed=(k&48)>>4,O.fillGreen=(k&12)>>2,O.fillBlue=k&3,k=C[++x],O.borderType=(k&192)>>6,O.borderRed=(k&48)>>4,O.borderGreen=(k&12)>>2,O.borderBlue=k&3,k=C[++x],O.borderType+=(k&128)>>5,O.wordWrap=(k&64)>>6,O.printDirection=(k&48)>>4,O.scrollDirection=(k&12)>>2,O.justify=k&3,k=C[++x],O.effectSpeed=(k&240)>>4,O.effectDirection=(k&12)>>2,O.displayEffect=k&3,x},Kt.prototype.flushDisplayed=function(x,A){for(var C=[],k=0;k<8;k++)A.windows[k].visible&&!A.windows[k].isEmpty()&&C.push(A.windows[k].getText());A.endPts=x,A.text=C.join(` `),this.pushCaption(A),A.startPts=x},Kt.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)},Kt.prototype.displayWindows=function(x,A){var C=this.current708Packet.data,k=C[++x],O=this.getPts(x);this.flushDisplayed(O,A);for(var P=0;P<8;P++)k&1<>4,O.offset=(k&12)>>2,O.penSize=k&3,k=C[++x],O.italics=(k&128)>>7,O.underline=(k&64)>>6,O.edgeType=(k&56)>>3,O.fontStyle=k&7,x},Kt.prototype.setPenColor=function(x,A){var C=this.current708Packet.data,k=C[x],O=A.currentWindow.penColor;return k=C[++x],O.fgOpacity=(k&192)>>6,O.fgRed=(k&48)>>4,O.fgGreen=(k&12)>>2,O.fgBlue=k&3,k=C[++x],O.bgOpacity=(k&192)>>6,O.bgRed=(k&48)>>4,O.bgGreen=(k&12)>>2,O.bgBlue=k&3,k=C[++x],O.edgeRed=(k&48)>>4,O.edgeGreen=(k&12)>>2,O.edgeBlue=k&3,x},Kt.prototype.setPenLocation=function(x,A){var C=this.current708Packet.data,k=C[x],O=A.currentWindow.penLoc;return A.currentWindow.pendingNewLine=!0,k=C[++x],O.row=k&15,k=C[++x],O.column=k&63,x},Kt.prototype.reset=function(x,A){var C=this.getPts(x);return this.flushDisplayed(C,A),this.initService(A.serviceNum,x)};var Ui={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},rs=function(x){return x===null?"":(x=Ui[x]||x,String.fromCharCode(x))},mn=14,_n=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],je=function(){for(var x=[],A=mn+1;A--;)x.push({text:"",indent:0,offset:0});return x},gt=function(x,A){gt.prototype.init.call(this),this.field_=x||0,this.dataChannel_=A||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(C){var k,O,P,ne,ue;if(k=C.ccData&32639,k===this.lastControlCode_){this.lastControlCode_=null;return}if((k&61440)===4096?this.lastControlCode_=k:k!==this.PADDING_&&(this.lastControlCode_=null),P=k>>>8,ne=k&255,k!==this.PADDING_)if(k===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(k===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(C.pts),this.flushDisplayed(C.pts),O=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=O,this.startPts_=C.pts;else if(k===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(C.pts);else if(k===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(C.pts);else if(k===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(C.pts);else if(k===this.CARRIAGE_RETURN_)this.clearFormatting(C.pts),this.flushDisplayed(C.pts),this.shiftRowsUp_(),this.startPts_=C.pts;else if(k===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(k===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(C.pts),this.displayed_=je();else if(k===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=je();else if(k===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(C.pts),this.displayed_=je()),this.mode_="paintOn",this.startPts_=C.pts;else if(this.isSpecialCharacter(P,ne))P=(P&3)<<8,ue=rs(P|ne),this[this.mode_](C.pts,ue),this.column_++;else if(this.isExtCharacter(P,ne))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),P=(P&3)<<8,ue=rs(P|ne),this[this.mode_](C.pts,ue),this.column_++;else if(this.isMidRowCode(P,ne))this.clearFormatting(C.pts),this[this.mode_](C.pts," "),this.column_++,(ne&14)===14&&this.addFormatting(C.pts,["i"]),(ne&1)===1&&this.addFormatting(C.pts,["u"]);else if(this.isOffsetControlCode(P,ne)){const me=ne&3;this.nonDisplayed_[this.row_].offset=me,this.column_+=me}else if(this.isPAC(P,ne)){var ce=_n.indexOf(k&7968);if(this.mode_==="rollUp"&&(ce-this.rollUpRows_+1<0&&(ce=this.rollUpRows_-1),this.setRollUp(C.pts,ce)),ce!==this.row_&&ce>=0&&ce<=14&&(this.clearFormatting(C.pts),this.row_=ce),ne&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(C.pts,["u"]),(k&16)===16){const me=(k&14)>>1;this.column_=me*4,this.nonDisplayed_[this.row_].indent+=me}this.isColorPAC(ne)&&(ne&14)===14&&this.addFormatting(C.pts,["i"])}else this.isNormalChar(P)&&(ne===0&&(ne=null),ue=rs(P),ue+=rs(ne),this[this.mode_](C.pts,ue),this.column_+=ue.length)}};gt.prototype=new ai,gt.prototype.flushDisplayed=function(x){const A=k=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+k+"."})},C=[];this.displayed_.forEach((k,O)=>{if(k&&k.text&&k.text.length){try{k.text=k.text.trim()}catch{A(O)}k.text.length&&C.push({text:k.text,line:O+1,position:10+Math.min(70,k.indent*10)+k.offset*2.5})}else k==null&&A(O)}),C.length&&this.trigger("data",{startPts:this.startPts_,endPts:x,content:C,stream:this.name_})},gt.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=je(),this.nonDisplayed_=je(),this.lastControlCode_=null,this.column_=0,this.row_=mn,this.rollUpRows_=2,this.formatting_=[]},gt.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},gt.prototype.isSpecialCharacter=function(x,A){return x===this.EXT_&&A>=48&&A<=63},gt.prototype.isExtCharacter=function(x,A){return(x===this.EXT_+1||x===this.EXT_+2)&&A>=32&&A<=63},gt.prototype.isMidRowCode=function(x,A){return x===this.EXT_&&A>=32&&A<=47},gt.prototype.isOffsetControlCode=function(x,A){return x===this.OFFSET_&&A>=33&&A<=35},gt.prototype.isPAC=function(x,A){return x>=this.BASE_&&x=64&&A<=127},gt.prototype.isColorPAC=function(x){return x>=64&&x<=79||x>=96&&x<=127},gt.prototype.isNormalChar=function(x){return x>=32&&x<=127},gt.prototype.setRollUp=function(x,A){if(this.mode_!=="rollUp"&&(this.row_=mn,this.mode_="rollUp",this.flushDisplayed(x),this.nonDisplayed_=je(),this.displayed_=je()),A!==void 0&&A!==this.row_)for(var C=0;C"},"");this[this.mode_](x,C)},gt.prototype.clearFormatting=function(x){if(this.formatting_.length){var A=this.formatting_.reverse().reduce(function(C,k){return C+""},"");this.formatting_=[],this[this.mode_](x,A)}},gt.prototype.popOn=function(x,A){var C=this.nonDisplayed_[this.row_].text;C+=A,this.nonDisplayed_[this.row_].text=C},gt.prototype.rollUp=function(x,A){var C=this.displayed_[this.row_].text;C+=A,this.displayed_[this.row_].text=C},gt.prototype.shiftRowsUp_=function(){var x;for(x=0;xA&&(C=-1);Math.abs(A-x)>Ut;)x+=C*mi;return x},Ss=function(x){var A,C;Ss.prototype.init.call(this),this.type_=x||zi,this.push=function(k){if(k.type==="metadata"){this.trigger("data",k);return}this.type_!==zi&&k.type!==this.type_||(C===void 0&&(C=k.dts),k.dts=Si(k.dts,C),k.pts=Si(k.pts,C),A=k.dts,this.trigger("data",k))},this.flush=function(){C=A,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){C=void 0,A=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Ss.prototype=new Bt;var ks={TimestampRolloverStream:Ss,handleRollover:Si},Ys=(x,A,C)=>{if(!x)return-1;for(var k=C;k";x.data[0]===Cs.Utf8&&(C=as(x.data,0,A),!(C<0)&&(x.mimeType=Wi(x.data,A,C),A=C+1,x.pictureType=x.data[A],A++,k=as(x.data,0,A),!(k<0)&&(x.description=hs(x.data,A,k),A=k+1,x.mimeType===O?x.url=Wi(x.data,A,x.data.length):x.pictureData=x.data.subarray(A,x.data.length))))},"T*":function(x){x.data[0]===Cs.Utf8&&(x.value=hs(x.data,1,x.data.length).replace(/\0*$/,""),x.values=x.value.split("\0"))},TXXX:function(x){var A;x.data[0]===Cs.Utf8&&(A=as(x.data,0,1),A!==-1&&(x.description=hs(x.data,1,A),x.value=hs(x.data,A+1,x.data.length).replace(/\0*$/,""),x.data=x.value))},"W*":function(x){x.url=Wi(x.data,0,x.data.length).replace(/\0.*$/,"")},WXXX:function(x){var A;x.data[0]===Cs.Utf8&&(A=as(x.data,0,1),A!==-1&&(x.description=hs(x.data,1,A),x.url=Wi(x.data,A+1,x.data.length).replace(/\0.*$/,"")))},PRIV:function(x){var A;for(A=0;A>>2;Dt*=4,Dt+=Ye[7]&3,Se.timeStamp=Dt,ue.pts===void 0&&ue.dts===void 0&&(ue.pts=Se.timeStamp,ue.dts=Se.timeStamp),this.trigger("timestamp",Se)}ue.frames.push(Se),ce+=10,ce+=me}while(ce>>4>1&&(ne+=O[ne]+1),P.pid===0)P.type="pat",x(O.subarray(ne),P),this.trigger("data",P);else if(P.pid===this.pmtPid)for(P.type="pmt",x(O.subarray(ne),P),this.trigger("data",P);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([O,ne,P]):this.processPes_(O,ne,P)},this.processPes_=function(O,P,ne){ne.pid===this.programMapTable.video?ne.streamType=Ie.H264_STREAM_TYPE:ne.pid===this.programMapTable.audio?ne.streamType=Ie.ADTS_STREAM_TYPE:ne.streamType=this.programMapTable["timed-metadata"][ne.pid],ne.type="pes",ne.data=O.subarray(P),this.trigger("data",ne)}},St.prototype=new Ds,St.STREAM_TYPES={h264:27,adts:15},ei=function(){var x=this,A=!1,C={data:[],size:0},k={data:[],size:0},O={data:[],size:0},P,ne=function(ce,me){var Se;const He=ce[0]<<16|ce[1]<<8|ce[2];me.data=new Uint8Array,He===1&&(me.packetLength=6+(ce[4]<<8|ce[5]),me.dataAlignmentIndicator=(ce[6]&4)!==0,Se=ce[7],Se&192&&(me.pts=(ce[9]&14)<<27|(ce[10]&255)<<20|(ce[11]&254)<<12|(ce[12]&255)<<5|(ce[13]&254)>>>3,me.pts*=4,me.pts+=(ce[13]&6)>>>1,me.dts=me.pts,Se&64&&(me.dts=(ce[14]&14)<<27|(ce[15]&255)<<20|(ce[16]&254)<<12|(ce[17]&255)<<5|(ce[18]&254)>>>3,me.dts*=4,me.dts+=(ce[18]&6)>>>1)),me.data=ce.subarray(9+ce[8]))},ue=function(ce,me,Se){var He=new Uint8Array(ce.size),_t={type:me},Ye=0,Dt=0,hi=!1,Qs;if(!(!ce.data.length||ce.size<9)){for(_t.trackId=ce.data[0].pid,Ye=0;Ye>5,ce=((A[O+6]&3)+1)*1024,me=ce*Ls/we[(A[O+2]&60)>>>2],A.byteLength-O>>6&3)+1,channelcount:(A[O+2]&1)<<2|(A[O+3]&192)>>>6,samplerate:we[(A[O+2]&60)>>>2],samplingfrequencyindex:(A[O+2]&60)>>>2,samplesize:16,data:A.subarray(O+7+ne,O+P)}),C++,O+=P}typeof Se=="number"&&(this.skipWarn_(Se,O),Se=null),A=A.subarray(O)}},this.flush=function(){C=0,this.trigger("done")},this.reset=function(){A=void 0,this.trigger("reset")},this.endTimeline=function(){A=void 0,this.trigger("endedtimeline")}},ve.prototype=new Fn;var ke=ve,Y;Y=function(x){var A=x.byteLength,C=0,k=0;this.length=function(){return 8*A},this.bitsAvailable=function(){return 8*A+k},this.loadWord=function(){var O=x.byteLength-A,P=new Uint8Array(4),ne=Math.min(4,A);if(ne===0)throw new Error("no bytes available");P.set(x.subarray(O,O+ne)),C=new DataView(P.buffer).getUint32(0),k=ne*8,A-=ne},this.skipBits=function(O){var P;k>O?(C<<=O,k-=O):(O-=k,P=Math.floor(O/8),O-=P*8,A-=P,this.loadWord(),C<<=O,k-=O)},this.readBits=function(O){var P=Math.min(k,O),ne=C>>>32-P;return k-=P,k>0?C<<=P:A>0&&this.loadWord(),P=O-P,P>0?ne<>>O)!==0)return C<<=O,k-=O,O;return this.loadWord(),O+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var O=this.skipLeadingZeros();return this.readBits(O+1)-1},this.readExpGolomb=function(){var O=this.readUnsignedExpGolomb();return 1&O?1+O>>>1:-1*(O>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var ae=Y,_e=t,Me=ae,Ce,$e,tt;$e=function(){var x=0,A,C;$e.prototype.init.call(this),this.push=function(k){var O;C?(O=new Uint8Array(C.byteLength+k.data.byteLength),O.set(C),O.set(k.data,C.byteLength),C=O):C=k.data;for(var P=C.byteLength;x3&&this.trigger("data",C.subarray(x+3)),C=null,x=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},$e.prototype=new _e,tt={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Ce=function(){var x=new $e,A,C,k,O,P,ne,ue;Ce.prototype.init.call(this),A=this,this.push=function(ce){ce.type==="video"&&(C=ce.trackId,k=ce.pts,O=ce.dts,x.push(ce))},x.on("data",function(ce){var me={trackId:C,pts:k,dts:O,data:ce,nalUnitTypeCode:ce[0]&31};switch(me.nalUnitTypeCode){case 5:me.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:me.nalUnitType="sei_rbsp",me.escapedRBSP=P(ce.subarray(1));break;case 7:me.nalUnitType="seq_parameter_set_rbsp",me.escapedRBSP=P(ce.subarray(1)),me.config=ne(me.escapedRBSP);break;case 8:me.nalUnitType="pic_parameter_set_rbsp";break;case 9:me.nalUnitType="access_unit_delimiter_rbsp";break}A.trigger("data",me)}),x.on("done",function(){A.trigger("done")}),x.on("partialdone",function(){A.trigger("partialdone")}),x.on("reset",function(){A.trigger("reset")}),x.on("endedtimeline",function(){A.trigger("endedtimeline")}),this.flush=function(){x.flush()},this.partialFlush=function(){x.partialFlush()},this.reset=function(){x.reset()},this.endTimeline=function(){x.endTimeline()},ue=function(ce,me){var Se=8,He=8,_t,Ye;for(_t=0;_t>4;return C=C>=0?C:0,O?C+20:C+10},pt=function(x,A){return x.length-A<10||x[A]!==73||x[A+1]!==68||x[A+2]!==51?A:(A+=at(x,A),pt(x,A))},Mt=function(x){var A=pt(x,0);return x.length>=A+2&&(x[A]&255)===255&&(x[A+1]&240)===240&&(x[A+1]&22)===16},Nt=function(x){return x[0]<<21|x[1]<<14|x[2]<<7|x[3]},Ft=function(x,A,C){var k,O="";for(k=A;k>5,k=x[A+4]<<3,O=x[A+3]&6144;return O|k|C},ui=function(x,A){return x[A]===73&&x[A+1]===68&&x[A+2]===51?"timed-metadata":x[A]&!0&&(x[A+1]&240)===240?"audio":null},un=function(x){for(var A=0;A+5>>2]}return null},Ps=function(x){var A,C,k,O;A=10,x[5]&64&&(A+=4,A+=Nt(x.subarray(10,14)));do{if(C=Nt(x.subarray(A+4,A+8)),C<1)return null;if(O=String.fromCharCode(x[A],x[A+1],x[A+2],x[A+3]),O==="PRIV"){k=x.subarray(A+10,A+C+10);for(var P=0;P>>2;return ce*=4,ce+=ue[7]&3,ce}break}}A+=10,A+=C}while(A=3;){if(x[O]===73&&x[O+1]===68&&x[O+2]===51){if(x.length-O<10||(k=pn.parseId3TagSize(x,O),O+k>x.length))break;ne={type:"timed-metadata",data:x.subarray(O,O+k)},this.trigger("data",ne),O+=k;continue}else if((x[O]&255)===255&&(x[O+1]&240)===240){if(x.length-O<7||(k=pn.parseAdtsSize(x,O),O+k>x.length))break;ue={type:"audio",data:x.subarray(O,O+k),pts:A,dts:A},this.trigger("data",ue),O+=k;continue}O++}P=x.length-O,P>0?x=x.subarray(O):x=new Uint8Array},this.reset=function(){x=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){x=new Uint8Array,this.trigger("endedtimeline")}},Jn.prototype=new zr;var Za=Jn,xs=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Xs=xs,sa=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Ol=sa,No=t,Ml=Ve,Pl=bt,Du=Ki,Sr=re,na=An,Bl=Gt,tf=ke,Ip=ut.H264Stream,Np=Za,Op=Es.isLikelyAacData,id=Gt.ONE_SECOND_IN_TS,sf=Xs,nf=Ol,Lu,Oo,Ru,Ja,Mp=function(x,A){A.stream=x,this.trigger("log",A)},rf=function(x,A){for(var C=Object.keys(A),k=0;k=-1e4&&Se<=ce&&(!He||me>Se)&&(He=Ye,me=Se)));return He?He.gop:null},this.alignGopsAtStart_=function(ue){var ce,me,Se,He,_t,Ye,Dt,hi;for(_t=ue.byteLength,Ye=ue.nalCount,Dt=ue.duration,ce=me=0;ceSe.pts){ce++;continue}me++,_t-=He.byteLength,Ye-=He.nalCount,Dt-=He.duration}return me===0?ue:me===ue.length?null:(hi=ue.slice(me),hi.byteLength=_t,hi.duration=Dt,hi.nalCount=Ye,hi.pts=hi[0].pts,hi.dts=hi[0].dts,hi)},this.alignGopsAtEnd_=function(ue){var ce,me,Se,He,_t,Ye;for(ce=O.length-1,me=ue.length-1,_t=null,Ye=!1;ce>=0&&me>=0;){if(Se=O[ce],He=ue[me],Se.pts===He.pts){Ye=!0;break}if(Se.pts>He.pts){ce--;continue}ce===O.length-1&&(_t=me),me--}if(!Ye&&_t===null)return null;var Dt;if(Ye?Dt=me:Dt=_t,Dt===0)return ue;var hi=ue.slice(Dt),Qs=hi.reduce(function(Vn,Ea){return Vn.byteLength+=Ea.byteLength,Vn.duration+=Ea.duration,Vn.nalCount+=Ea.nalCount,Vn},{byteLength:0,duration:0,nalCount:0});return hi.byteLength=Qs.byteLength,hi.duration=Qs.duration,hi.nalCount=Qs.nalCount,hi.pts=hi[0].pts,hi.dts=hi[0].dts,hi},this.alignGopsWith=function(ue){O=ue}},Lu.prototype=new No,Ja=function(x,A){this.numberOfTracks=0,this.metadataStream=A,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,Ja.prototype.init.call(this),this.push=function(C){if(C.content||C.text)return this.pendingCaptions.push(C);if(C.frames)return this.pendingMetadata.push(C);this.pendingTracks.push(C.track),this.pendingBytes+=C.boxes.byteLength,C.track.type==="video"&&(this.videoTrack=C.track,this.pendingBoxes.push(C.boxes)),C.track.type==="audio"&&(this.audioTrack=C.track,this.pendingBoxes.unshift(C.boxes))}},Ja.prototype=new No,Ja.prototype.flush=function(x){var A=0,C={captions:[],captionStreams:{},metadata:[],info:{}},k,O,P,ne=0,ue;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(ne=this.videoTrack.timelineStartInfo.pts,nf.forEach(function(ce){C.info[ce]=this.videoTrack[ce]},this)):this.audioTrack&&(ne=this.audioTrack.timelineStartInfo.pts,sf.forEach(function(ce){C.info[ce]=this.audioTrack[ce]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?C.type=this.pendingTracks[0].type:C.type="combined",this.emittedTracks+=this.pendingTracks.length,P=Ml.initSegment(this.pendingTracks),C.initSegment=new Uint8Array(P.byteLength),C.initSegment.set(P),C.data=new Uint8Array(this.pendingBytes),ue=0;ue=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Ja.prototype.setRemux=function(x){this.remuxTracks=x},Ru=function(x){var A=this,C=!0,k,O;Ru.prototype.init.call(this),x=x||{},this.baseMediaDecodeTime=x.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="aac",P.metadataStream=new na.MetadataStream,P.aacStream=new Np,P.audioTimestampRolloverStream=new na.TimestampRolloverStream("audio"),P.timedMetadataTimestampRolloverStream=new na.TimestampRolloverStream("timed-metadata"),P.adtsStream=new tf,P.coalesceStream=new Ja(x,P.metadataStream),P.headOfPipeline=P.aacStream,P.aacStream.pipe(P.audioTimestampRolloverStream).pipe(P.adtsStream),P.aacStream.pipe(P.timedMetadataTimestampRolloverStream).pipe(P.metadataStream).pipe(P.coalesceStream),P.metadataStream.on("timestamp",function(ne){P.aacStream.setTimestamp(ne.timeStamp)}),P.aacStream.on("data",function(ne){ne.type!=="timed-metadata"&&ne.type!=="audio"||P.audioSegmentStream||(O=O||{timelineStartInfo:{baseMediaDecodeTime:A.baseMediaDecodeTime},codec:"adts",type:"audio"},P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Oo(O,x),P.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream),A.trigger("trackinfo",{hasAudio:!!O,hasVideo:!!k}))}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),rf(this,P)},this.setupTsPipeline=function(){var P={};this.transmuxPipeline_=P,P.type="ts",P.metadataStream=new na.MetadataStream,P.packetStream=new na.TransportPacketStream,P.parseStream=new na.TransportParseStream,P.elementaryStream=new na.ElementaryStream,P.timestampRolloverStream=new na.TimestampRolloverStream,P.adtsStream=new tf,P.h264Stream=new Ip,P.captionStream=new na.CaptionStream(x),P.coalesceStream=new Ja(x,P.metadataStream),P.headOfPipeline=P.packetStream,P.packetStream.pipe(P.parseStream).pipe(P.elementaryStream).pipe(P.timestampRolloverStream),P.timestampRolloverStream.pipe(P.h264Stream),P.timestampRolloverStream.pipe(P.adtsStream),P.timestampRolloverStream.pipe(P.metadataStream).pipe(P.coalesceStream),P.h264Stream.pipe(P.captionStream).pipe(P.coalesceStream),P.elementaryStream.on("data",function(ne){var ue;if(ne.type==="metadata"){for(ue=ne.tracks.length;ue--;)!k&&ne.tracks[ue].type==="video"?(k=ne.tracks[ue],k.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime):!O&&ne.tracks[ue].type==="audio"&&(O=ne.tracks[ue],O.timelineStartInfo.baseMediaDecodeTime=A.baseMediaDecodeTime);k&&!P.videoSegmentStream&&(P.coalesceStream.numberOfTracks++,P.videoSegmentStream=new Lu(k,x),P.videoSegmentStream.on("log",A.getLogTrigger_("videoSegmentStream")),P.videoSegmentStream.on("timelineStartInfo",function(ce){O&&!x.keepOriginalTimestamps&&(O.timelineStartInfo=ce,P.audioSegmentStream.setEarliestDts(ce.dts-A.baseMediaDecodeTime))}),P.videoSegmentStream.on("processedGopsInfo",A.trigger.bind(A,"gopInfo")),P.videoSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"videoSegmentTimingInfo")),P.videoSegmentStream.on("baseMediaDecodeTime",function(ce){O&&P.audioSegmentStream.setVideoBaseMediaDecodeTime(ce)}),P.videoSegmentStream.on("timingInfo",A.trigger.bind(A,"videoTimingInfo")),P.h264Stream.pipe(P.videoSegmentStream).pipe(P.coalesceStream)),O&&!P.audioSegmentStream&&(P.coalesceStream.numberOfTracks++,P.audioSegmentStream=new Oo(O,x),P.audioSegmentStream.on("log",A.getLogTrigger_("audioSegmentStream")),P.audioSegmentStream.on("timingInfo",A.trigger.bind(A,"audioTimingInfo")),P.audioSegmentStream.on("segmentTimingInfo",A.trigger.bind(A,"audioSegmentTimingInfo")),P.adtsStream.pipe(P.audioSegmentStream).pipe(P.coalesceStream)),A.trigger("trackinfo",{hasAudio:!!O,hasVideo:!!k})}}),P.coalesceStream.on("data",this.trigger.bind(this,"data")),P.coalesceStream.on("id3Frame",function(ne){ne.dispatchType=P.metadataStream.dispatchType,A.trigger("id3Frame",ne)}),P.coalesceStream.on("caption",this.trigger.bind(this,"caption")),P.coalesceStream.on("done",this.trigger.bind(this,"done")),rf(this,P)},this.setBaseMediaDecodeTime=function(P){var ne=this.transmuxPipeline_;x.keepOriginalTimestamps||(this.baseMediaDecodeTime=P),O&&(O.timelineStartInfo.dts=void 0,O.timelineStartInfo.pts=void 0,Sr.clearDtsInfo(O),ne.audioTimestampRolloverStream&&ne.audioTimestampRolloverStream.discontinuity()),k&&(ne.videoSegmentStream&&(ne.videoSegmentStream.gopCache_=[]),k.timelineStartInfo.dts=void 0,k.timelineStartInfo.pts=void 0,Sr.clearDtsInfo(k),ne.captionStream.reset()),ne.timestampRolloverStream&&ne.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(P){O&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(P)},this.setRemux=function(P){var ne=this.transmuxPipeline_;x.remux=P,ne&&ne.coalesceStream&&ne.coalesceStream.setRemux(P)},this.alignGopsWith=function(P){k&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(P)},this.getLogTrigger_=function(P){var ne=this;return function(ue){ue.stream=P,ne.trigger("log",ue)}},this.push=function(P){if(C){var ne=Op(P);ne&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!ne&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),C=!1}this.transmuxPipeline_.headOfPipeline.push(P)},this.flush=function(){C=!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()}},Ru.prototype=new No;var Pp={Transmuxer:Ru},Bp=function(x){return x>>>0},Fp=function(x){return("00"+x.toString(16)).slice(-2)},Mo={toUnsigned:Bp,toHexString:Fp},Fl=function(x){var A="";return A+=String.fromCharCode(x[0]),A+=String.fromCharCode(x[1]),A+=String.fromCharCode(x[2]),A+=String.fromCharCode(x[3]),A},lf=Fl,uf=Mo.toUnsigned,cf=lf,sd=function(x,A){var C=[],k,O,P,ne,ue;if(!A.length)return null;for(k=0;k1?k+O:x.byteLength,P===A[0]&&(A.length===1?C.push(x.subarray(k+8,ne)):(ue=sd(x.subarray(k+8,ne),A.slice(1)),ue.length&&(C=C.concat(ue)))),k=ne;return C},Iu=sd,df=Mo.toUnsigned,Po=r.getUint64,Up=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4))};return A.version===1?A.baseMediaDecodeTime=Po(x.subarray(4)):A.baseMediaDecodeTime=df(x[4]<<24|x[5]<<16|x[6]<<8|x[7]),A},nd=Up,jp=function(x){var A=new DataView(x.buffer,x.byteOffset,x.byteLength),C={version:x[0],flags:new Uint8Array(x.subarray(1,4)),trackId:A.getUint32(4)},k=C.flags[2]&1,O=C.flags[2]&2,P=C.flags[2]&8,ne=C.flags[2]&16,ue=C.flags[2]&32,ce=C.flags[0]&65536,me=C.flags[0]&131072,Se;return Se=8,k&&(Se+=4,C.baseDataOffset=A.getUint32(12),Se+=4),O&&(C.sampleDescriptionIndex=A.getUint32(Se),Se+=4),P&&(C.defaultSampleDuration=A.getUint32(Se),Se+=4),ne&&(C.defaultSampleSize=A.getUint32(Se),Se+=4),ue&&(C.defaultSampleFlags=A.getUint32(Se)),ce&&(C.durationIsEmpty=!0),!k&&me&&(C.baseDataOffsetIsMoof=!0),C},rd=jp,hf=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]}},Ul=hf,Bo=Ul,$p=function(x){var A={version:x[0],flags:new Uint8Array(x.subarray(1,4)),samples:[]},C=new DataView(x.buffer,x.byteOffset,x.byteLength),k=A.flags[2]&1,O=A.flags[2]&4,P=A.flags[1]&1,ne=A.flags[1]&2,ue=A.flags[1]&4,ce=A.flags[1]&8,me=C.getUint32(4),Se=8,He;for(k&&(A.dataOffset=C.getInt32(Se),Se+=4),O&&me&&(He={flags:Bo(x.subarray(Se,Se+4))},Se+=4,P&&(He.duration=C.getUint32(Se),Se+=4),ne&&(He.size=C.getUint32(Se),Se+=4),ce&&(A.version===1?He.compositionTimeOffset=C.getInt32(Se):He.compositionTimeOffset=C.getUint32(Se),Se+=4),A.samples.push(He),me--);me--;)He={},P&&(He.duration=C.getUint32(Se),Se+=4),ne&&(He.size=C.getUint32(Se),Se+=4),ue&&(He.flags=Bo(x.subarray(Se,Se+4)),Se+=4),ce&&(A.version===1?He.compositionTimeOffset=C.getInt32(Se):He.compositionTimeOffset=C.getUint32(Se),Se+=4),A.samples.push(He);return A},jl=$p,ad={tfdt:nd,trun:jl},od={parseTfdt:ad.tfdt,parseTrun:ad.trun},ld=function(x){for(var A=0,C=String.fromCharCode(x[A]),k="";C!=="\0";)k+=C,A++,C=String.fromCharCode(x[A]);return k+=C,k},ud={uint8ToCString:ld},$l=ud.uint8ToCString,ff=r.getUint64,mf=function(x){var A=4,C=x[0],k,O,P,ne,ue,ce,me,Se;if(C===0){k=$l(x.subarray(A)),A+=k.length,O=$l(x.subarray(A)),A+=O.length;var He=new DataView(x.buffer);P=He.getUint32(A),A+=4,ue=He.getUint32(A),A+=4,ce=He.getUint32(A),A+=4,me=He.getUint32(A),A+=4}else if(C===1){var He=new DataView(x.buffer);P=He.getUint32(A),A+=4,ne=ff(x.subarray(A)),A+=8,ce=He.getUint32(A),A+=4,me=He.getUint32(A),A+=4,k=$l(x.subarray(A)),A+=k.length,O=$l(x.subarray(A)),A+=O.length}Se=new Uint8Array(x.subarray(A,x.byteLength));var _t={scheme_id_uri:k,value:O,timescale:P||1,presentation_time:ne,presentation_time_delta:ue,event_duration:ce,id:me,message_data:Se};return zp(C,_t)?_t:void 0},Hp=function(x,A,C,k){return x||x===0?x/A:k+C/A},zp=function(x,A){var C=A.scheme_id_uri!=="\0",k=x===0&&pf(A.presentation_time_delta)&&C,O=x===1&&pf(A.presentation_time)&&C;return!(x>1)&&k||O},pf=function(x){return x!==void 0||x!==null},Gp={parseEmsgBox:mf,scaleTime:Hp},Hl;typeof window<"u"?Hl=window:typeof s<"u"?Hl=s:typeof self<"u"?Hl=self:Hl={};var Un=Hl,ya=Mo.toUnsigned,Fo=Mo.toHexString,Rs=Iu,eo=lf,Nu=Gp,cd=rd,Vp=jl,Uo=nd,dd=r.getUint64,jo,Ou,hd,va,to,zl,fd,ra=Un,gf=Pn.parseId3Frames;jo=function(x){var A={},C=Rs(x,["moov","trak"]);return C.reduce(function(k,O){var P,ne,ue,ce,me;return P=Rs(O,["tkhd"])[0],!P||(ne=P[0],ue=ne===0?12:20,ce=ya(P[ue]<<24|P[ue+1]<<16|P[ue+2]<<8|P[ue+3]),me=Rs(O,["mdia","mdhd"])[0],!me)?null:(ne=me[0],ue=ne===0?12:20,k[ce]=ya(me[ue]<<24|me[ue+1]<<16|me[ue+2]<<8|me[ue+3]),k)},A)},Ou=function(x,A){var C;C=Rs(A,["moof","traf"]);var k=C.reduce(function(O,P){var ne=Rs(P,["tfhd"])[0],ue=ya(ne[4]<<24|ne[5]<<16|ne[6]<<8|ne[7]),ce=x[ue]||9e4,me=Rs(P,["tfdt"])[0],Se=new DataView(me.buffer,me.byteOffset,me.byteLength),He;me[0]===1?He=dd(me.subarray(4,12)):He=Se.getUint32(4);let _t;return typeof He=="bigint"?_t=He/ra.BigInt(ce):typeof He=="number"&&!isNaN(He)&&(_t=He/ce),_t11?(O.codec+=".",O.codec+=Fo(Ye[9]),O.codec+=Fo(Ye[10]),O.codec+=Fo(Ye[11])):O.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(O.codec)?(Ye=_t.subarray(28),Dt=eo(Ye.subarray(4,8)),Dt==="esds"&&Ye.length>20&&Ye[19]!==0?(O.codec+="."+Fo(Ye[19]),O.codec+="."+Fo(Ye[20]>>>2&63).replace(/^0/,"")):O.codec="mp4a.40.2"):O.codec=O.codec.toLowerCase())}var hi=Rs(k,["mdia","mdhd"])[0];hi&&(O.timescale=zl(hi)),C.push(O)}),C},fd=function(x,A=0){var C=Rs(x,["emsg"]);return C.map(k=>{var O=Nu.parseEmsgBox(new Uint8Array(k)),P=gf(O.message_data);return{cueTime:Nu.scaleTime(O.presentation_time,O.timescale,O.presentation_time_delta,A),duration:Nu.scaleTime(O.event_duration,O.timescale),frames:P}})};var $o={findBox:Rs,parseType:eo,timescale:jo,startTime:Ou,compositionStartTime:hd,videoTrackIds:va,tracks:to,getTimescaleFromMediaHeader:zl,getEmsgID3:fd};const{parseTrun:yf}=od,{findBox:vf}=$o;var xf=Un,qp=function(x){var A=vf(x,["moof","traf"]),C=vf(x,["mdat"]),k=[];return C.forEach(function(O,P){var ne=A[P];k.push({mdat:O,traf:ne})}),k},bf=function(x,A,C){var k=A,O=C.defaultSampleDuration||0,P=C.defaultSampleSize||0,ne=C.trackId,ue=[];return x.forEach(function(ce){var me=yf(ce),Se=me.samples;Se.forEach(function(He){He.duration===void 0&&(He.duration=O),He.size===void 0&&(He.size=P),He.trackId=ne,He.dts=k,He.compositionTimeOffset===void 0&&(He.compositionTimeOffset=0),typeof k=="bigint"?(He.pts=k+xf.BigInt(He.compositionTimeOffset),k+=xf.BigInt(He.duration)):(He.pts=k+He.compositionTimeOffset,k+=He.duration)}),ue=ue.concat(Se)}),ue},md={getMdatTrafPairs:qp,parseSamples:bf},pd=ji.discardEmulationPreventionBytes,_r=Ct.CaptionStream,Ho=Iu,er=nd,zo=rd,{getMdatTrafPairs:gd,parseSamples:Mu}=md,Pu=function(x,A){for(var C=x,k=0;k0?er(Se[0]).baseMediaDecodeTime:0,_t=Ho(ne,["trun"]),Ye,Dt;A===me&&_t.length>0&&(Ye=Mu(_t,He,ce),Dt=yd(P,Ye,me),C[me]||(C[me]={seiNals:[],logs:[]}),C[me].seiNals=C[me].seiNals.concat(Dt.seiNals),C[me].logs=C[me].logs.concat(Dt.logs))}),C},Tf=function(x,A,C){var k;if(A===null)return null;k=io(x,A);var O=k[A]||{};return{seiNals:O.seiNals,logs:O.logs,timescale:C}},Bu=function(){var x=!1,A,C,k,O,P,ne;this.isInitialized=function(){return x},this.init=function(ue){A=new _r,x=!0,ne=ue?ue.isPartial:!1,A.on("data",function(ce){ce.startTime=ce.startPts/O,ce.endTime=ce.endPts/O,P.captions.push(ce),P.captionStreams[ce.stream]=!0}),A.on("log",function(ce){P.logs.push(ce)})},this.isNewInit=function(ue,ce){return ue&&ue.length===0||ce&&typeof ce=="object"&&Object.keys(ce).length===0?!1:k!==ue[0]||O!==ce[k]},this.parse=function(ue,ce,me){var Se;if(this.isInitialized()){if(!ce||!me)return null;if(this.isNewInit(ce,me))k=ce[0],O=me[k];else if(k===null||!O)return C.push(ue),null}else return null;for(;C.length>0;){var He=C.shift();this.parse(He,ce,me)}return Se=Tf(ue,k,O),Se&&Se.logs&&(P.logs=P.logs.concat(Se.logs)),Se===null||!Se.seiNals?P.logs.length?{logs:P.logs,captions:[],captionStreams:[]}:null:(this.pushNals(Se.seiNals),this.flushStream(),P)},this.pushNals=function(ue){if(!this.isInitialized()||!ue||ue.length===0)return null;ue.forEach(function(ce){A.push(ce)})},this.flushStream=function(){if(!this.isInitialized())return null;ne?A.partialFlush():A.flush()},this.clearParsedCaptions=function(){P.captions=[],P.captionStreams={},P.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;A.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){C=[],k=null,O=null,P?this.clearParsedCaptions():P={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},Go=Bu;const{parseTfdt:Kp}=od,Hs=Iu,{getTimescaleFromMediaHeader:vd}=$o,{parseSamples:aa,getMdatTrafPairs:Sf}=md;var xa=function(){let x=9e4;this.init=function(A){const C=Hs(A,["moov","trak","mdia","mdhd"])[0];C&&(x=vd(C))},this.parseSegment=function(A){const C=[],k=Sf(A);let O=0;return k.forEach(function(P){const ne=P.mdat,ue=P.traf,ce=Hs(ue,["tfdt"])[0],me=Hs(ue,["tfhd"])[0],Se=Hs(ue,["trun"]);if(ce&&(O=Kp(ce).baseMediaDecodeTime),Se.length&&me){const He=aa(Se,O,me);let _t=0;He.forEach(function(Ye){const Dt="utf-8",hi=new TextDecoder(Dt),Qs=ne.slice(_t,_t+Ye.size);if(Hs(Qs,["vtte"])[0]){_t+=Ye.size;return}Hs(Qs,["vttc"]).forEach(function(Kl){const bs=Hs(Kl,["payl"])[0],so=Hs(Kl,["sttg"])[0],oa=Ye.pts/x,wa=(Ye.pts+Ye.duration)/x;let es,Gr;if(bs)try{es=hi.decode(bs)}catch(gn){console.error(gn)}if(so)try{Gr=hi.decode(so)}catch(gn){console.error(gn)}Ye.duration&&es&&C.push({cueText:es,start:oa,end:wa,settings:Gr})}),_t+=Ye.size})}}),C}},Gl=Vt,bd=function(x){var A=x[1]&31;return A<<=8,A|=x[2],A},Vo=function(x){return!!(x[1]&64)},Vl=function(x){var A=0;return(x[3]&48)>>>4>1&&(A+=x[4]+1),A},tr=function(x,A){var C=bd(x);return C===0?"pat":C===A?"pmt":A?"pes":null},qo=function(x){var A=Vo(x),C=4+Vl(x);return A&&(C+=x[C]+1),(x[C+10]&31)<<8|x[C+11]},Ko=function(x){var A={},C=Vo(x),k=4+Vl(x);if(C&&(k+=x[k]+1),!!(x[k+5]&1)){var O,P,ne;O=(x[k+1]&15)<<8|x[k+2],P=3+O-4,ne=(x[k+10]&15)<<8|x[k+11];for(var ue=12+ne;ue=x.byteLength)return null;var k=null,O;return O=x[C+7],O&192&&(k={},k.pts=(x[C+9]&14)<<27|(x[C+10]&255)<<20|(x[C+11]&254)<<12|(x[C+12]&255)<<5|(x[C+13]&254)>>>3,k.pts*=4,k.pts+=(x[C+13]&6)>>>1,k.dts=k.pts,O&64&&(k.dts=(x[C+14]&14)<<27|(x[C+15]&255)<<20|(x[C+16]&254)<<12|(x[C+17]&255)<<5|(x[C+18]&254)>>>3,k.dts*=4,k.dts+=(x[C+18]&6)>>>1)),k},jn=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}},ir=function(x){for(var A=4+Vl(x),C=x.subarray(A),k=0,O=0,P=!1,ne;O3&&(ne=jn(C[O+3]&31),ne==="slice_layer_without_partitioning_rbsp_idr"&&(P=!0)),P},ba={parseType:tr,parsePat:qo,parsePmt:Ko,parsePayloadUnitStartIndicator:Vo,parsePesType:Fu,parsePesTime:ql,videoPacketContainsKeyFrame:ir},Er=Vt,kn=ks.handleRollover,_i={};_i.ts=ba,_i.aac=Es;var Ta=Gt.ONE_SECOND_IN_TS,cn=188,sr=71,_f=function(x,A){for(var C=0,k=cn,O,P;k=0;){if(x[k]===sr&&(x[O]===sr||O===x.byteLength)){if(P=x.subarray(k,O),ne=_i.ts.parseType(P,A.pid),ne==="pes"&&(ue=_i.ts.parsePesType(P,A.table),ce=_i.ts.parsePayloadUnitStartIndicator(P),ue==="audio"&&ce&&(me=_i.ts.parsePesTime(P),me&&(me.type="audio",C.audio.push(me),Se=!0))),Se)break;k-=cn,O-=cn;continue}k--,O--}},fs=function(x,A,C){for(var k=0,O=cn,P,ne,ue,ce,me,Se,He,_t,Ye=!1,Dt={data:[],size:0};O=0;){if(x[k]===sr&&x[O]===sr){if(P=x.subarray(k,O),ne=_i.ts.parseType(P,A.pid),ne==="pes"&&(ue=_i.ts.parsePesType(P,A.table),ce=_i.ts.parsePayloadUnitStartIndicator(P),ue==="video"&&ce&&(me=_i.ts.parsePesTime(P),me&&(me.type="video",C.video.push(me),Ye=!0))),Ye)break;k-=cn,O-=cn;continue}k--,O--}},Ii=function(x,A){if(x.audio&&x.audio.length){var C=A;(typeof C>"u"||isNaN(C))&&(C=x.audio[0].dts),x.audio.forEach(function(P){P.dts=kn(P.dts,C),P.pts=kn(P.pts,C),P.dtsTime=P.dts/Ta,P.ptsTime=P.pts/Ta})}if(x.video&&x.video.length){var k=A;if((typeof k>"u"||isNaN(k))&&(k=x.video[0].dts),x.video.forEach(function(P){P.dts=kn(P.dts,k),P.pts=kn(P.pts,k),P.dtsTime=P.dts/Ta,P.ptsTime=P.pts/Ta}),x.firstKeyFrame){var O=x.firstKeyFrame;O.dts=kn(O.dts,k),O.pts=kn(O.pts,k),O.dtsTime=O.dts/Ta,O.ptsTime=O.pts/Ta}}},Sa=function(x){for(var A=!1,C=0,k=null,O=null,P=0,ne=0,ue;x.length-ne>=3;){var ce=_i.aac.parseType(x,ne);switch(ce){case"timed-metadata":if(x.length-ne<10){A=!0;break}if(P=_i.aac.parseId3TagSize(x,ne),P>x.length){A=!0;break}O===null&&(ue=x.subarray(ne,ne+P),O=_i.aac.parseAacTimestamp(ue)),ne+=P;break;case"audio":if(x.length-ne<7){A=!0;break}if(P=_i.aac.parseAdtsSize(x,ne),P>x.length){A=!0;break}k===null&&(ue=x.subarray(ne,ne+P),k=_i.aac.parseSampleRate(ue)),C++,ne+=P;break;default:ne++;break}if(A)return null}if(k===null||O===null)return null;var me=Ta/k,Se={audio:[{type:"audio",dts:O,pts:O},{type:"audio",dts:O+C*1024*me,pts:O+C*1024*me}]};return Se},nr=function(x){var A={pid:null,table:null},C={};_f(x,A);for(var k in A.table)if(A.table.hasOwnProperty(k)){var O=A.table[k];switch(O){case Er.H264_STREAM_TYPE:C.video=[],fs(x,A,C),C.video.length===0&&delete C.video;break;case Er.ADTS_STREAM_TYPE:C.audio=[],nn(x,A,C),C.audio.length===0&&delete C.audio;break}}return C},Td=function(x,A){var C=_i.aac.isLikelyAacData(x),k;return C?k=Sa(x):k=nr(x),!k||!k.audio&&!k.video?null:(Ii(k,A),k)},_a={inspect:Td,parseAudioPes_:nn};const Ef=function(x,A){A.on("data",function(C){const k=C.initSegment;C.initSegment={data:k.buffer,byteOffset:k.byteOffset,byteLength:k.byteLength};const O=C.data;C.data=O.buffer,x.postMessage({action:"data",segment:C,byteOffset:O.byteOffset,byteLength:O.byteLength},[C.data])}),A.on("done",function(C){x.postMessage({action:"done"})}),A.on("gopInfo",function(C){x.postMessage({action:"gopInfo",gopInfo:C})}),A.on("videoSegmentTimingInfo",function(C){const k={start:{decode:Gt.videoTsToSeconds(C.start.dts),presentation:Gt.videoTsToSeconds(C.start.pts)},end:{decode:Gt.videoTsToSeconds(C.end.dts),presentation:Gt.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:Gt.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(k.prependedContentDuration=Gt.videoTsToSeconds(C.prependedContentDuration)),x.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:k})}),A.on("audioSegmentTimingInfo",function(C){const k={start:{decode:Gt.videoTsToSeconds(C.start.dts),presentation:Gt.videoTsToSeconds(C.start.pts)},end:{decode:Gt.videoTsToSeconds(C.end.dts),presentation:Gt.videoTsToSeconds(C.end.pts)},baseMediaDecodeTime:Gt.videoTsToSeconds(C.baseMediaDecodeTime)};C.prependedContentDuration&&(k.prependedContentDuration=Gt.videoTsToSeconds(C.prependedContentDuration)),x.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:k})}),A.on("id3Frame",function(C){x.postMessage({action:"id3Frame",id3Frame:C})}),A.on("caption",function(C){x.postMessage({action:"caption",caption:C})}),A.on("trackinfo",function(C){x.postMessage({action:"trackinfo",trackInfo:C})}),A.on("audioTimingInfo",function(C){x.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:Gt.videoTsToSeconds(C.start),end:Gt.videoTsToSeconds(C.end)}})}),A.on("videoTimingInfo",function(C){x.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:Gt.videoTsToSeconds(C.start),end:Gt.videoTsToSeconds(C.end)}})}),A.on("log",function(C){x.postMessage({action:"log",log:C})})};class Sd{constructor(A,C){this.options=C||{},this.self=A,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new Pp.Transmuxer(this.options),Ef(this.self,this.transmuxer)}pushMp4Captions(A){this.captionParser||(this.captionParser=new Go,this.captionParser.init());const C=new Uint8Array(A.data,A.byteOffset,A.byteLength),k=this.captionParser.parse(C,A.trackIds,A.timescales);this.self.postMessage({action:"mp4Captions",captions:k&&k.captions||[],logs:k&&k.logs||[],data:C.buffer},[C.buffer])}initMp4WebVttParser(A){this.webVttParser||(this.webVttParser=new xa);const C=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.webVttParser.init(C)}getMp4WebVttText(A){this.webVttParser||(this.webVttParser=new xa);const C=new Uint8Array(A.data,A.byteOffset,A.byteLength),k=this.webVttParser.parseSegment(C);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:k||[],data:C.buffer},[C.buffer])}probeMp4StartTime({timescales:A,data:C}){const k=$o.startTime(A,C);this.self.postMessage({action:"probeMp4StartTime",startTime:k,data:C},[C.buffer])}probeMp4Tracks({data:A}){const C=$o.tracks(A);this.self.postMessage({action:"probeMp4Tracks",tracks:C,data:A},[A.buffer])}probeEmsgID3({data:A,offset:C}){const k=$o.getEmsgID3(A,C);this.self.postMessage({action:"probeEmsgID3",id3Frames:k,emsgData:A},[A.buffer])}probeTs({data:A,baseStartTime:C}){const k=typeof C=="number"&&!isNaN(C)?C*Gt.ONE_SECOND_IN_TS:void 0,O=_a.inspect(A,k);let P=null;O&&(P={hasVideo:O.video&&O.video.length===2||!1,hasAudio:O.audio&&O.audio.length===2||!1},P.hasVideo&&(P.videoStart=O.video[0].ptsTime),P.hasAudio&&(P.audioStart=O.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:P,data:A},[A.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(A){const C=new Uint8Array(A.data,A.byteOffset,A.byteLength);this.transmuxer.push(C)}reset(){this.transmuxer.reset()}setTimestampOffset(A){const C=A.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(Gt.secondsToVideoTs(C)))}setAudioAppendStart(A){this.transmuxer.setAudioAppendStart(Math.ceil(Gt.secondsToVideoTs(A.appendStart)))}setRemux(A){this.transmuxer.setRemux(A.remux)}flush(A){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(A){this.transmuxer.alignGopsWith(A.gopsToAlignWith.slice())}}self.onmessage=function(x){if(x.data.action==="init"&&x.data.options){this.messageHandlers=new Sd(self,x.data.options);return}this.messageHandlers||(this.messageHandlers=new Sd(self)),x.data&&x.data.action&&x.data.action!=="init"&&this.messageHandlers[x.data.action]&&this.messageHandlers[x.data.action](x.data)}}));var LF=uD(DF);const RF=(s,e,t)=>{const{type:i,initSegment:n,captions:r,captionStreams:a,metadata:u,videoFrameDtsTime:c,videoFramePtsTime:d}=s.data.segment;e.buffer.push({captions:r,captionStreams:a,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)},IF=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},NF=(s,e)=>{e.gopInfo=s.data.gopInfo},hD=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:n,remux:r,onData:a,onTrackInfo:u,onAudioTimingInfo:c,onVideoTimingInfo:d,onVideoSegmentTimingInfo:f,onAudioSegmentTimingInfo:p,onId3:y,onCaptions:v,onDone:b,onEndedTimeline:S,onTransmuxerLog:E,isEndOfTimeline:L,segment:N,triggerSegmentEventFn:R}=s,H={buffer:[]};let F=L;const $=W=>{e.currentTransmux===s&&(W.data.action==="data"&&RF(W,H,a),W.data.action==="trackinfo"&&u(W.data.trackInfo),W.data.action==="gopInfo"&&NF(W,H),W.data.action==="audioTimingInfo"&&c(W.data.audioTimingInfo),W.data.action==="videoTimingInfo"&&d(W.data.videoTimingInfo),W.data.action==="videoSegmentTimingInfo"&&f(W.data.videoSegmentTimingInfo),W.data.action==="audioSegmentTimingInfo"&&p(W.data.audioSegmentTimingInfo),W.data.action==="id3Frame"&&y([W.data.id3Frame],W.data.id3Frame.dispatchType),W.data.action==="caption"&&v(W.data.caption),W.data.action==="endedtimeline"&&(F=!1,S()),W.data.action==="log"&&E(W.data.log),W.data.type==="transmuxed"&&(F||(e.onmessage=null,IF({transmuxedData:H,callback:b}),fD(e))))},M=()=>{const W={message:"Received an error message from the transmuxer worker",metadata:{errorType:Le.Error.StreamingFailedToTransmuxSegment,segmentInfo:hu({segment:N})}};b(null,W)};if(e.onmessage=$,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 W=t instanceof ArrayBuffer?t:t.buffer,D=t instanceof ArrayBuffer?0:t.byteOffset;R({type:"segmenttransmuxingstart",segment:N}),e.postMessage({action:"push",data:W,byteOffset:D,byteLength:t.byteLength},[W])}L&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},fD=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():hD(s.currentTransmux))},TE=(s,e)=>{s.postMessage({action:e}),fD(s)},mD=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,TE(e,s);return}e.transmuxQueue.push(TE.bind(null,e,s))},OF=s=>{mD("reset",s)},MF=s=>{mD("endTimeline",s)},pD=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,hD(s);return}s.transmuxer.transmuxQueue.push(s)},PF=s=>{const e=new LF;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 gv={reset:OF,endTimeline:MF,transmux:pD,createTransmuxer:PF};const Ac=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,n=sn({},s,{endAction:null,transmuxer:null,callback:null}),r=a=>{a.data.action===t&&(e.removeEventListener("message",r),a.data.data&&(a.data.data=new Uint8Array(a.data.data,s.byteOffset||0,s.byteLength||a.data.data.byteLength),s.data&&(s.data=a.data.data)),i(a.data))};if(e.addEventListener("message",r),s.data){const a=s.data instanceof ArrayBuffer;n.byteOffset=a?0:s.data.byteOffset,n.byteLength=s.data.byteLength;const u=[a?s.data:s.data.buffer];e.postMessage(n,u)}else e.postMessage(n)},Ua={FAILURE:2,TIMEOUT:-101,ABORTED:-102},gD="wvtt",Ox=s=>{s.forEach(e=>{e.abort()})},BF=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),FF=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},Zb=(s,e)=>{const{requestType:t}=e,i=bu({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:Ua.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:Ua.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:Ua.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:Ua.FAILURE,xhr:e,metadata:i}:null},SE=(s,e,t,i)=>(n,r)=>{const a=r.response,u=Zb(n,r);if(u)return t(u,s);if(a.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:Ua.FAILURE,xhr:r},s);const c=new DataView(a),d=new Uint32Array([c.getUint32(0),c.getUint32(4),c.getUint32(8),c.getUint32(12)]);for(let p=0;p{e===gD&&s.transmuxer.postMessage({action:"initMp4WebVttParser",data:s.map.bytes})},jF=(s,e,t)=>{e===gD&&Ac({action:"getMp4WebVttText",data:s.bytes,transmuxer:s.transmuxer,callback:({data:i,mp4VttCues:n})=>{s.bytes=i,t(null,s,{mp4VttCues:n})}})},yD=(s,e)=>{const t=Tb(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:Ua.FAILURE,metadata:{mediaType:n}})}Ac({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"&&UF(s,r.codec))}),e(null))})},$F=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,n)=>{const r=Zb(i,n);if(r)return e(r,s);const a=new Uint8Array(n.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=a,e(null,s);s.map.bytes=a,yD(s,function(u){if(u)return u.xhr=n,u.status=n.status,e(u,s);e(null,s)})},HF=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(n,r)=>{const a=Zb(n,r);if(a)return e(a,s);i({type:"segmentloaded",segment:s});const u=t==="arraybuffer"||!r.responseText?r.response:kF(r.responseText.substring(s.lastReachedChar||0));return s.stats=BF(r),s.key?s.encryptedBytes=new Uint8Array(u):s.bytes=new Uint8Array(u),e(null,s)},zF=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{const b=s.map&&s.map.tracks||{},S=!!(b.audio&&b.video);let E=i.bind(null,s,"audio","start");const L=i.bind(null,s,"audio","end");let N=i.bind(null,s,"video","start");const R=i.bind(null,s,"video","end"),H=()=>pD({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:S,onData:F=>{F.type=F.type==="combined"?"video":F.type,f(s,F)},onTrackInfo:F=>{t&&(S&&(F.isMuxed=!0),t(s,F))},onAudioTimingInfo:F=>{E&&typeof F.start<"u"&&(E(F.start),E=null),L&&typeof F.end<"u"&&L(F.end)},onVideoTimingInfo:F=>{N&&typeof F.start<"u"&&(N(F.start),N=null),R&&typeof F.end<"u"&&R(F.end)},onVideoSegmentTimingInfo:F=>{const $={pts:{start:F.start.presentation,end:F.end.presentation},dts:{start:F.start.decode,end:F.end.decode}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:$}),n(F)},onAudioSegmentTimingInfo:F=>{const $={pts:{start:F.start.pts,end:F.end.pts},dts:{start:F.start.dts,end:F.end.dts}};v({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:$}),r(F)},onId3:(F,$)=>{a(s,F,$)},onCaptions:F=>{u(s,[F])},isEndOfTimeline:c,onEndedTimeline:()=>{d()},onTransmuxerLog:y,onDone:(F,$)=>{p&&(F.type=F.type==="combined"?"video":F.type,v({type:"segmenttransmuxingcomplete",segment:s}),p($,s,F))},segment:s,triggerSegmentEventFn:v});Ac({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:F=>{s.bytes=e=F.data;const $=F.result;$&&(t(s,{hasAudio:$.hasAudio,hasVideo:$.hasVideo,isMuxed:S}),t=null),H()}})},vD=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=new Uint8Array(e);if(c4(b)){s.isFmp4=!0;const{tracks:S}=s.map;if(S.text&&(!S.audio||!S.video)){f(s,{data:b,type:"text"}),jF(s,S.text.codec,p);return}const L={isFmp4:!0,hasVideo:!!S.video,hasAudio:!!S.audio};S.audio&&S.audio.codec&&S.audio.codec!=="enca"&&(L.audioCodec=S.audio.codec),S.video&&S.video.codec&&S.video.codec!=="encv"&&(L.videoCodec=S.video.codec),S.video&&S.audio&&(L.isMuxed=!0),t(s,L);const N=(R,H)=>{f(s,{data:b,type:L.hasAudio&&!L.isMuxed?"audio":"video"}),H&&H.length&&a(s,H),R&&R.length&&u(s,R),p(null,s,{})};Ac({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:R,startTime:H})=>{e=R.buffer,s.bytes=b=R,L.hasAudio&&!L.isMuxed&&i(s,"audio","start",H),L.hasVideo&&i(s,"video","start",H),Ac({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:H,callback:({emsgData:F,id3Frames:$})=>{if(e=F.buffer,s.bytes=b=F,!S.video||!F.byteLength||!s.transmuxer){N(void 0,$);return}Ac({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[S.video.id],callback:M=>{e=M.data.buffer,s.bytes=b=M.data,M.logs.forEach(function(W){y(Qi(W,{stream:"mp4CaptionParser"}))}),N(M.captions,$)}})}})}});return}if(!s.transmuxer){p(null,s,{});return}if(typeof s.container>"u"&&(s.container=Tb(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),p(null,s,{});return}zF({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})},xD=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:n,doneFn:r},a){const u=d=>{if(d.data.source===s){i.removeEventListener("message",u);const f=d.data.decrypted;a(new Uint8Array(f.bytes,f.byteOffset,f.byteLength))}};i.onerror=()=>{const d="An error occurred in the decryption worker",f=hu({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(sD({source:s,encrypted:t,key:c,iv:e.iv}),[t.buffer,c.buffer])},GF=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{v({type:"segmentdecryptionstart"}),xD({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:p},b=>{e.bytes=b,v({type:"segmentdecryptioncomplete",segment:e}),vD({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})})},VF=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})=>{let b=0,S=!1;return(E,L)=>{if(!S){if(E)return S=!0,Ox(s),p(E,L);if(b+=1,b===s.length){const N=function(){if(L.encryptedBytes)return GF({decryptionWorker:e,segment:L,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v});vD({segment:L,bytes:L.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f,doneFn:p,onTransmuxerLog:y,triggerSegmentEventFn:v})};if(L.endOfAllRequests=Date.now(),L.map&&L.map.encryptedBytes&&!L.map.bytes)return v({type:"segmentdecryptionstart",segment:L}),xD({decryptionWorker:e,id:L.requestId+"-init",encryptedBytes:L.map.encryptedBytes,key:L.map.key,segment:L,doneFn:p},R=>{L.map.bytes=R,v({type:"segmentdecryptioncomplete",segment:L}),yD(L,H=>{if(H)return Ox(s),p(H,L);N()})});N()}}}},qF=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},KF=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:d,dataFn:f})=>p=>{if(!p.target.aborted)return s.stats=Qi(s.stats,FF(p)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(p,s)},WF=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:n,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:S,onTransmuxerLog:E,triggerSegmentEventFn:L})=>{const N=[],R=VF({activeXhrs:N,decryptionWorker:t,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b,doneFn:S,onTransmuxerLog:E,triggerSegmentEventFn:L});if(i.key&&!i.key.bytes){const W=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&W.push(i.map.key);const D=Qi(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),I=SE(i,W,R,L),Q={uri:i.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:Q});const K=s(D,I);N.push(K)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const K=Qi(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),q=SE(i,[i.map.key],R,L),le={uri:i.map.key.resolvedUri};L({type:"segmentkeyloadstart",segment:i,keyInfo:le});const te=s(K,q);N.push(te)}const D=Qi(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:Ix(i.map),requestType:"segment-media-initialization"}),I=$F({segment:i,finishProcessingFn:R,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const Q=s(D,I);N.push(Q)}const H=Qi(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:Ix(i),requestType:"segment"}),F=HF({segment:i,finishProcessingFn:R,responseType:H.responseType,triggerSegmentEventFn:L});L({type:"segmentloadstart",segment:i});const $=s(H,F);$.addEventListener("progress",KF({segment:i,progressFn:r,trackInfoFn:a,timingInfoFn:u,videoSegmentTimingInfoFn:c,audioSegmentTimingInfoFn:d,id3Fn:f,captionsFn:p,isEndOfTimeline:y,endedTimelineFn:v,dataFn:b})),N.push($);const M={};return N.forEach(W=>{W.addEventListener("loadend",qF({loadendState:M,abortFn:n}))}),()=>Ox(N)},Cm=ta("PlaylistSelector"),_E=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||""})},kc=function(s,e){if(!s)return"";const t=he.getComputedStyle(s);return t?t[e]:""},Cc=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})},Jb=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||he.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||he.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||he.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||he.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let bD=function(s){const{main:e,bandwidth:t,playerWidth:i,playerHeight:n,playerObjectFit:r,limitRenditionByPlayerDimensions:a,playlistController:u}=s;if(!e)return;const c={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:a};let d=e.playlists;gr.isAudioOnly(e)&&(d=u.getAudioTrackPlaylists_(),c.audioOnly=!0);let f=d.map(M=>{let W;const D=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.width,I=M.attributes&&M.attributes.RESOLUTION&&M.attributes.RESOLUTION.height;return W=M.attributes&&M.attributes.BANDWIDTH,W=W||he.Number.MAX_VALUE,{bandwidth:W,width:D,height:I,playlist:M}});Cc(f,(M,W)=>M.bandwidth-W.bandwidth),f=f.filter(M=>!gr.isIncompatible(M.playlist));let p=f.filter(M=>gr.isEnabled(M.playlist));p.length||(p=f.filter(M=>!gr.isDisabled(M.playlist)));const y=p.filter(M=>M.bandwidth*bn.BANDWIDTH_VARIANCEM.bandwidth===v.bandwidth)[0];if(a===!1){const M=b||p[0]||f[0];if(M&&M.playlist){let W="sortedPlaylistReps";return b&&(W="bandwidthBestRep"),p[0]&&(W="enabledPlaylistReps"),Cm(`choosing ${_E(M)} using ${W} with options`,c),M.playlist}return Cm("could not choose a playlist with options",c),null}const S=y.filter(M=>M.width&&M.height);Cc(S,(M,W)=>M.width-W.width);const E=S.filter(M=>M.width===i&&M.height===n);v=E[E.length-1];const L=E.filter(M=>M.bandwidth===v.bandwidth)[0];let N,R,H;L||(N=S.filter(M=>r==="cover"?M.width>i&&M.height>n:M.width>i||M.height>n),R=N.filter(M=>M.width===N[0].width&&M.height===N[0].height),v=R[R.length-1],H=R.filter(M=>M.bandwidth===v.bandwidth)[0]);let F;if(u.leastPixelDiffSelector){const M=S.map(W=>(W.pixelDiff=Math.abs(W.width-i)+Math.abs(W.height-n),W));Cc(M,(W,D)=>W.pixelDiff===D.pixelDiff?D.bandwidth-W.bandwidth:W.pixelDiff-D.pixelDiff),F=M[0]}const $=F||H||L||b||p[0]||f[0];if($&&$.playlist){let M="sortedPlaylistReps";return F?M="leastPixelDiffRep":H?M="resolutionPlusOneRep":L?M="resolutionBestRep":b?M="bandwidthBestRep":p[0]&&(M="enabledPlaylistReps"),Cm(`choosing ${_E($)} using ${M} with options`,c),$.playlist}return Cm("could not choose a playlist with options",c),null};const EE=function(){let s=this.useDevicePixelRatio&&he.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),bD({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(kc(this.tech_.el(),"width"),10)*s,playerHeight:parseInt(kc(this.tech_.el(),"height"),10)*s,playerObjectFit:this.usePlayerObjectFit?kc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})},XF=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&&he.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),bD({main:this.playlists.main,bandwidth:e,playerWidth:parseInt(kc(this.tech_.el(),"width"),10)*i,playerHeight:parseInt(kc(this.tech_.el(),"height"),10)*i,playerObjectFit:this.usePlayerObjectFit?kc(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},QF=function(s){const{main:e,currentTime:t,bandwidth:i,duration:n,segmentDuration:r,timeUntilRebuffer:a,currentTimeline:u,syncController:c}=s,d=e.playlists.filter(b=>!gr.isIncompatible(b));let f=d.filter(gr.isEnabled);f.length||(f=d.filter(b=>!gr.isDisabled(b)));const y=f.filter(gr.hasAttribute.bind(null,"BANDWIDTH")).map(b=>{const E=c.getSyncPoint(b,n,u,t)?1:2,N=gr.estimateSegmentRequestTime(r,i,b)*E-a;return{playlist:b,rebufferingImpact:N}}),v=y.filter(b=>b.rebufferingImpact<=0);return Cc(v,(b,S)=>Jb(S.playlist,b.playlist)),v.length?v[0]:(Cc(y,(b,S)=>b.rebufferingImpact-S.rebufferingImpact),y[0]||null)},ZF=function(){const s=this.playlists.main.playlists.filter(gr.isEnabled);return Cc(s,(t,i)=>Jb(t,i)),s.filter(t=>!!Ch(this.playlists.main,t).video)[0]||null},JF=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 TD(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const e8=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 a=t,u=t,c=!1;const d=r[i];d&&(a=d.label,u=d.language,c=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:c,label:a,language:u},!1).track}}},t8=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=he.WebKitDataCue||he.VTTCue;e.forEach(n=>{const r=n.stream;n.content?n.content.forEach(a=>{const u=new i(n.startTime+t,n.endTime+t,a.text);u.line=a.line,u.align="left",u.position=a.position,u.positionAlign="line-left",s[r].addCue(u)}):s[r].addCue(new i(n.startTime+t,n.endTime+t,n.text))})},i8=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}}})},s8=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const n=he.WebKitDataCue||he.VTTCue,r=s.metadataTrack_;if(!r||(e.forEach(f=>{const p=f.cueTime+t;typeof p!="number"||he.isNaN(p)||p<0||!(p<1/0)||!f.frames||!f.frames.length||f.frames.forEach(y=>{const v=new n(p,p,y.value||y.url||y.data||"");v.frame=y,v.value=y,i8(v),r.addCue(v)})}),!r.cues||!r.cues.length))return;const a=r.cues,u=[];for(let f=0;f{const y=f[p.startTime]||[];return y.push(p),f[p.startTime]=y,f},{}),d=Object.keys(c).sort((f,p)=>Number(f)-Number(p));d.forEach((f,p)=>{const y=c[f],v=isFinite(i)?i:f,b=Number(d[p+1])||v;y.forEach(S=>{S.endTime=b})})},n8={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"},r8=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),a8=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=he.WebKitDataCue||he.VTTCue;e.forEach(n=>{for(const r of Object.keys(n)){if(r8.has(r))continue;const a=new i(n.startTime,n.endTime,"");a.id=n.id,a.type="com.apple.quicktime.HLS",a.value={key:n8[r],data:n[r]},(r==="scte35Out"||r==="scte35In")&&(a.value.data=new Uint8Array(a.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(a)}n.processDateRange()})},wE=(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))},mh=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)},o8=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}},l8=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*mu.ONE_SECOND_IN_TS);let n;for(n=0;ni);n++);return s.slice(n)},u8=(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)},c8=(s,e,t,i)=>{const n=Math.ceil((e-i)*mu.ONE_SECOND_IN_TS),r=Math.ceil((t-i)*mu.ONE_SECOND_IN_TS),a=s.slice();let u=s.length;for(;u--&&!(s[u].pts<=r););if(u===-1)return a;let c=u+1;for(;c--&&!(s[c].pts<=n););return c=Math.max(c,0),a.splice(c,u-c+1),a},d8=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]},nh=1,f8=500,AE=s=>typeof s=="number"&&isFinite(s),Dm=1/60,m8=(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,p8=(s,e,t)=>{let i=e-bn.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const n=e-t;return Math.min(n,i)},rc=s=>{const{startOfSegment:e,duration:t,segment:i,part:n,playlist:{mediaSequence:r,id:a,segments:u=[]},mediaIndex:c,partIndex:d,timeline:f}=s,p=u.length-1;let y="mediaIndex/partIndex increment";s.getMediaInfoForTime?y=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(y="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(y+=` with independent ${s.independent}`);const v=typeof d=="number",b=s.segment.uri?"segment":"pre-segment",S=v?UC({preloadSegment:i})-1:0;return`${b} [${r+c}/${r+p}]`+(v?` part [${d}/${S}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(v?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${f}] selected by [${y}] playlist [${a}]`},kE=s=>`${s}TimingInfo`,g8=({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},y8=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)},v8=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(Mx({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&y8(s.timelineChangeController_)){if(v8(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}s.timelineChangeController_.trigger("fixBadTimelineChange")}},x8=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 a;typeof n=="bigint"||typeof r=="bigint"?a=he.BigInt(r)-he.BigInt(n):typeof n=="number"&&typeof r=="number"&&(a=r-n),typeof a<"u"&&a>e&&(e=a)}),typeof e=="bigint"&&es?Math.round(s)>e+Ba:!1,b8=(s,e)=>{if(e!=="hls")return null;const t=x8({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,n=CE({segmentDuration:t,maxDuration:i*2}),r=CE({segmentDuration:t,maxDuration:i}),a=`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:a}:null},hu=({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 Px 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_=ta(`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_():ml(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(sn({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():ml(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(sn({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():ml(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():ml(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return gv.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_&&he.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,he.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_&&gv.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Sn();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=M0(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=nD(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: ${mv(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 a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{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-=a,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_&&(he.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_&&gv.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 a=()=>{r--,r===0&&i()};(n||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,a)),(n||this.loaderType_==="main")&&(this.gopBuffer_=c8(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,a));for(const u in this.inbandTextTracks_)mh(e,t,this.inbandTextTracks_[u]);mh(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&he.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=he.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&he.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=he.setTimeout(this.monitorBufferTick_.bind(this),f8)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:hu({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,a=!n||!n.parts||i+1===n.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&r&&a}chooseNextRequest_(){const e=this.buffered_(),t=mv(e)||0,i=Wb(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.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=h8(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${u.mediaIndex}`);else if(this.mediaIndex!==null){const y=a[this.mediaIndex],v=typeof this.partIndex=="number"?this.partIndex:-1;u.startOfSegment=y.end?y.end:t,y.parts&&y.parts[v+1]?(u.mediaIndex=this.mediaIndex,u.partIndex=v+1):u.mediaIndex=this.mediaIndex+1}else{let y,v,b;const S=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: For TargetTime: ${S}. CurrentTime: ${this.currentTime_()} BufferedEnd: ${t} Fetch At Buffer: ${this.fetchAtBuffer_} `,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const E=this.getSyncInfoFromMediaSequenceSync_(S);if(!E){const L="No sync info found while using media sequence sync";return this.error({message:L,metadata:{errorType:Le.Error.StreamingFailedToSelectNextSegment,error:new Error(L)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${E.start} --> ${E.end})`),y=E.segmentIndex,v=E.partIndex,b=E.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const E=gr.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:S,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});y=E.segmentIndex,v=E.partIndex,b=E.startTime}u.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${S}`:`currentTime ${S}`,u.mediaIndex=y,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=a[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 y=a[u.mediaIndex-1],v=y.parts&&y.parts.length&&y.parts[y.parts.length-1];v&&v.independent&&(u.mediaIndex-=1,u.partIndex=y.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>=a.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:a,partIndex:u,forceTimestampOffset:c,getMediaInfoForTime:d}=e,f=i.segments[n],p=typeof u=="number"&&f.parts[u],y={requestId:"segment-loader-"+Math.random(),uri:p&&p.resolvedUri||f.resolvedUri,mediaIndex:n,partIndex:p?u:null,isSyncRequest:a,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_;y.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:f.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:v});const b=mv(this.sourceUpdater_.audioBuffered());return typeof b=="number"&&(y.audioAppendStart=b-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(y.gopsToAlignWith=l8(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),y}timestampOffsetForSegment_(e){return g8(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=gr.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),a=FB(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=a)return;const u=QF({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!u)return;const d=r-a-u.rebufferingImpact;let f=.5;a<=Ba&&(f=1),!(!u.playlist||u.playlist.uri===this.playlist_.uri||d{r[a.stream]=r[a.stream]||{startTime:1/0,captions:[],endTime:0};const u=r[a.stream];u.startTime=Math.min(u.startTime,a.startTime+n),u.endTime=Math.max(u.endTime,a.endTime+n),u.captions.push(a)}),Object.keys(r).forEach(a=>{const{startTime:u,endTime:c,captions:d}=r[a],f=this.inbandTextTracks_;this.logger_(`adding cues from ${u} -> ${c} for ${a}`),e8(f,this.vhs_.tech_,a),mh(u,c,f[a]),t8({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_()?!Mx({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||Mx({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_()){ml(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[kE(t.type)].start;else{const n=this.getCurrentMediaInfo_(),r=this.loaderType_==="main"&&n&&n.hasVideo;let a;r&&(a=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:a,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=M0(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(),a=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+pu(r).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+pu(a).join(", "));const u=r.length?r.start(0):0,c=r.length?r.end(r.length-1):0,d=a.length?a.start(0):0,f=a.length?a.end(a.length-1):0;if(c-u<=nh&&f-d<=nh){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${pu(r).join(", ")}, video buffer: ${pu(a).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const y=this.currentTime_()-nh;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${y}`),this.remove(0,y,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${nh}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=he.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},nh*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){if(n){if(n.code===XC){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=JF({bytes:c,segments:u})}const a={segmentInfo:hu({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),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_()){ml(this),this.loadQueue_.push(()=>{const t=sn({},e,{forceTimestampOffset:!0});sn(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,a=i||n&&r;this.logger_(`Requesting ${TD(e.uri)} ${rc(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=WF({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:a,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:u,level:c,stream:d})=>{this.logger_(`${rc(e)} logged from transmuxer stream ${d} as a ${c}: ${u}`)},triggerSegmentEventFn:({type:u,segment:c,keyInfo:d,trackInfo:f,timingInfo:p})=>{const v={segmentInfo:hu({segment:c})};d&&(v.keyInfo=d),f&&(v.trackInfo=f),p&&(v.timingInfo=p),this.trigger({type:u,metadata:v})}})}trimBackBuffer_(e){const t=p8(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,a={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?a.baseStartTime=u.videoTimingInfo.transmuxedDecodeEnd:u.audioTimingInfo&&(a.baseStartTime=u.audioTimingInfo.transmuxedDecodeEnd)),t.key){const c=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=c}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,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,a=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}a&&e.waitingOnAppends++,u&&e.waitingOnAppends++,a&&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=m8(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:hu({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=b8(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 ${rc(e)}`);return}this.logger_(`Appended ${rc(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,a=n&&n.end&&this.currentTime_()-n.end>e.playlist.partTargetDuration*3;if(r||a){this.logger_(`bad ${r?"segment":"part"} ${rc(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())},T8=["video","audio"],Bx=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},S8=(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(),Dc("audio",e),Dc("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||Bx(s,e))){if(i.type!==s){if(t=S8(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,Dc(s,e);return}}},_D=(s,e)=>{const t=e[`${s}Buffer`],i=SD(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},Oa=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,Ir={appendBuffer:(s,e,t)=>(i,n)=>{const r=n[`${i}Buffer`];if(Oa(n.mediaSource,r)){n.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{r.appendBuffer(s)}catch(a){n.logger_(`Error with code ${a.code} `+(a.code===XC?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),n.queuePending[i]=null,t(a)}}},remove:(s,e)=>(t,i)=>{const n=i[`${t}Buffer`];if(Oa(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`];Oa(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(Oa(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=SD(s),n=Bc(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(_D(s,e),!!Oa(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=Bc(s);if(!Oa(t.mediaSource,i))return;const r=s.substring(0,s.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))===r)return;const c={codecsChangeInfo:{from:a,to:s}};t.trigger({type:"codecschange",metadata:c}),t.logger_(`changing ${e}Buffer codec from ${a} 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}),Dc(s,e)},DE=(s,e)=>t=>{const i=e[`${s}Buffered`](),n=MB(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_`])}Dc(s,e)};class ED extends Le.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>Dc("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=ta("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=DE("video",this),this.onAudioUpdateEnd_=DE("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:Ir.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){Nr({type:e,sourceUpdater:this,action:Ir.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){Le.log.error("removeSourceBuffer is not supported!");return}Nr({type:"mediaSource",sourceUpdater:this,action:Ir.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!Le.browser.IS_FIREFOX&&he.MediaSource&&he.MediaSource.prototype&&typeof he.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return he.SourceBuffer&&he.SourceBuffer.prototype&&typeof he.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:Ir.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 a=t;if(Nr({type:n,sourceUpdater:this,action:Ir.appendBuffer(r,i||{mediaIndex:-1},a),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 Oa(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Sn()}videoBuffered(){return Oa(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Sn()}buffered(){const e=Oa(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=Oa(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():BB(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=Ao){Nr({type:"mediaSource",sourceUpdater:this,action:Ir.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=Ao){typeof e!="string"&&(e=void 0),Nr({type:"mediaSource",sourceUpdater:this,action:Ir.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=Ao){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}Nr({type:"audio",sourceUpdater:this,action:Ir.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=Ao){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}Nr({type:"video",sourceUpdater:this,action:Ir.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(Bx("audio",this)||Bx("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(Nr({type:"audio",sourceUpdater:this,action:Ir.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:Ir.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&Nr({type:"audio",sourceUpdater:this,action:Ir.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&Nr({type:"video",sourceUpdater:this,action:Ir.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),T8.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>_D(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const LE=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),_8=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},RE=new Uint8Array(` `.split("").map(s=>s.charCodeAt(0)));class E8 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class w8 extends Px{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 Sn();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return Sn([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=M0(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const r=RE.byteLength+e.bytes.byteLength,a=new Uint8Array(r);a.set(e.bytes),a.set(RE,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}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){mh(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===Ua.TIMEOUT&&this.handleTimeout_(),e.code===Ua.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 a=n.segment;if(a.map&&(a.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof he.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}a.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+=a.duration,n.cues.forEach(u=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new he.VTTCue(u.startTime,u.endTime,u.text):u)}),o8(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,a=new he.VTTCue(n,r,i.cueText);i.settings&&i.settings.split(" ").forEach(u=>{const c=u.split(":"),d=c[0],f=c[1];a[d]=isNaN(f)?f:Number(f)}),e.cues.push(a)})}parseVTTCues_(e){let t,i=!1;if(typeof he.WebVTT!="function")throw new E8;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof he.TextDecoder=="function"?t=new he.TextDecoder("utf8"):(t=he.WebVTT.StringDecoder(),i=!0);const n=new he.WebVTT.Parser(he,he.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=a=>{e.timestampmap=a},n.onparsingerror=a=>{Le.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=LE(a)),n.parse(a)}let r=e.bytes;i&&(r=LE(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:a}=e.timestampmap,c=r/mu.ONE_SECOND_IN_TS-a+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*mu.ONE_SECOND_IN_TS;const n=t*mu.ONE_SECOND_IN_TS;let r;for(n4294967296;)i+=r;return i/mu.ONE_SECOND_IN_TS}}const A8=function(s,e){const t=s.cues;for(let i=0;i=n.adStartTime&&e<=n.adEndTime)return n}return null},k8=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 wD{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=` `,a=i,u=t;this.start_=a,e.forEach((c,d)=>{const f=this.storage_.get(u),p=a,y=p+c.duration,v=!!(f&&f.segmentSyncInfo&&f.segmentSyncInfo.isAppended),b=new IE({start:p,end:y,appended:v,segmentIndex:d});c.syncInfo=b;let S=a;const E=(c.parts||[]).map((L,N)=>{const R=S,H=S+L.duration,F=!!(f&&f.partsSyncInfo&&f.partsSyncInfo[N]&&f.partsSyncInfo[N].isAppended),$=new IE({start:R,end:H,appended:F,segmentIndex:d,partIndex:N});return S=H,r+=`Media Sequence: ${u}.${N} | Range: ${R} --> ${H} | Appended: ${F} `,L.syncInfo=$,$});n.set(u,new C8(b,E)),r+=`${TD(c.resolvedUri)} | Media Sequence: ${u} | Range: ${p} --> ${y} | Appended: ${v} `,u++,a=y}),this.end_=a,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 a=s.getMediaSequenceSync(r);if(!a||!a.isReliable)return null;const u=a.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,a=null;const u=kx(e);n=n||0;for(let c=0;c{let r=null,a=null;n=n||0;const u=kx(e);for(let c=0;c=v)&&(a=v,r={time:y,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 a=null;for(let u=0;u=p)&&(a=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 L8 extends Le.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new wD,i=new NE(t),n=new NE(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=ta("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,r){if(t!==1/0)return yv.find(({name:c})=>c==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,i,n,r);if(!a.length)return null;for(const u of a){const{syncPoint:c,strategy:d}=u,{segmentIndex:f,time:p}=c;if(f<0)continue;const y=e.segments[f],v=p,b=v+y.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+kh({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,r){const a=[];for(let u=0;uD8){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 a=this.timelines[e.timeline],u,c;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),u=e.startOfSegment,c=t.end+a.mapping;else if(a)u=t.start+a.mapping,c=t.end+a.mapping;else return!1;return r&&(r.start=u,r.end=c),(!n.start||uc){let d;u<0?d=i.start-kh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):d=i.end+kh({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[a]={time:d,accuracy:c}}}}dispose(){this.trigger("dispose"),this.off()}}class R8 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 I8=cD(dD(function(){var s=(function(){function S(){this.listeners={}}var E=S.prototype;return E.on=function(N,R){this.listeners[N]||(this.listeners[N]=[]),this.listeners[N].push(R)},E.off=function(N,R){if(!this.listeners[N])return!1;var H=this.listeners[N].indexOf(R);return this.listeners[N]=this.listeners[N].slice(0),this.listeners[N].splice(H,1),H>-1},E.trigger=function(N){var R=this.listeners[N];if(R)if(arguments.length===2)for(var H=R.length,F=0;F>7)*283)^H]=H;for(F=$=0;!N[F];F^=D||1,$=W[$]||1)for(K=$^$<<1^$<<2^$<<3^$<<4,K=K>>8^K&255^99,N[F]=K,R[K]=F,Q=M[I=M[D=M[F]]],le=Q*16843009^I*65537^D*257^F*16843008,q=M[K]*257^K*16843008,H=0;H<4;H++)E[H][F]=q=q<<24^q>>>8,L[H][K]=le=le<<24^le>>>8;for(H=0;H<5;H++)E[H]=E[H].slice(0),L[H]=L[H].slice(0);return S};let i=null;class n{constructor(E){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 L,N,R;const H=this._tables[0][4],F=this._tables[1],$=E.length;let M=1;if($!==4&&$!==6&&$!==8)throw new Error("Invalid aes key size");const W=E.slice(0),D=[];for(this._key=[W,D],L=$;L<4*$+28;L++)R=W[L-1],(L%$===0||$===8&&L%$===4)&&(R=H[R>>>24]<<24^H[R>>16&255]<<16^H[R>>8&255]<<8^H[R&255],L%$===0&&(R=R<<8^R>>>24^M<<24,M=M<<1^(M>>7)*283)),W[L]=W[L-$]^R;for(N=0;L;N++,L--)R=W[N&3?L:L-4],L<=4||N<4?D[N]=R:D[N]=F[0][H[R>>>24]]^F[1][H[R>>16&255]]^F[2][H[R>>8&255]]^F[3][H[R&255]]}decrypt(E,L,N,R,H,F){const $=this._key[1];let M=E^$[0],W=R^$[1],D=N^$[2],I=L^$[3],Q,K,q;const le=$.length/4-2;let te,V=4;const G=this._tables[1],J=G[0],ie=G[1],oe=G[2],j=G[3],X=G[4];for(te=0;te>>24]^ie[W>>16&255]^oe[D>>8&255]^j[I&255]^$[V],K=J[W>>>24]^ie[D>>16&255]^oe[I>>8&255]^j[M&255]^$[V+1],q=J[D>>>24]^ie[I>>16&255]^oe[M>>8&255]^j[W&255]^$[V+2],I=J[I>>>24]^ie[M>>16&255]^oe[W>>8&255]^j[D&255]^$[V+3],V+=4,M=Q,W=K,D=q;for(te=0;te<4;te++)H[(3&-te)+F]=X[M>>>24]<<24^X[W>>16&255]<<16^X[D>>8&255]<<8^X[I&255]^$[V++],Q=M,M=W,W=D,D=I,I=Q}}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(E){this.jobs.push(E),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(S){return S<<24|(S&65280)<<8|(S&16711680)>>8|S>>>24},u=function(S,E,L){const N=new Int32Array(S.buffer,S.byteOffset,S.byteLength>>2),R=new n(Array.prototype.slice.call(E)),H=new Uint8Array(S.byteLength),F=new Int32Array(H.buffer);let $,M,W,D,I,Q,K,q,le;for($=L[0],M=L[1],W=L[2],D=L[3],le=0;le{const N=S[L];y(N)?E[L]={bytes:N.buffer,byteOffset:N.byteOffset,byteLength:N.byteLength}:E[L]=N}),E};self.onmessage=function(S){const E=S.data,L=new Uint8Array(E.encrypted.bytes,E.encrypted.byteOffset,E.encrypted.byteLength),N=new Uint32Array(E.key.bytes,E.key.byteOffset,E.key.byteLength/4),R=new Uint32Array(E.iv.bytes,E.iv.byteOffset,E.iv.byteLength/4);new c(L,N,R,function(H,F){self.postMessage(b({source:E.source,decrypted:F}),[F.buffer])})}}));var N8=uD(I8);const O8=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},AD=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},Fx=(s,e)=>{e.activePlaylistLoader=s,s.load()},M8=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:n}}=e,r=n.activeTrack(),a=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastGroup_;if(!(a&&c&&a.id===c.id)&&(n.lastGroup_=a,n.lastTrack_=r,AD(t,n),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){u&&i.resetEverything();return}t.resyncLoader(),Fx(a.playlistLoader,n)}},P8=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},B8=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:n},mediaTypes:{[s]:r}}=e,a=r.activeTrack(),u=r.getActiveGroup(),c=r.activePlaylistLoader,d=r.lastTrack_;if(!(d&&a&&d.id===a.id)&&(r.lastGroup_=u,r.lastTrack_=a,AD(i,r),!!u)){if(u.isMainPlaylist){if(!a||!d||a.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 ${a.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){Fx(u.playlistLoader,r);return}i.track&&i.track(a),i.resetEverything(),Fx(u.playlistLoader,r)}},P0={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,n=t.activeTrack(),r=t.activeGroup(),a=(r.filter(c=>c.default)[0]||r[0]).id,u=t.tracks[a];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()}},OE={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:n,segmentLoaders:{[s]:r}}=t;e.on("loadedmetadata",()=>{const a=e.media();r.playlist(a,n),(!i.paused()||a.endList&&i.preload()!=="none")&&r.load()}),e.on("loadedplaylist",()=>{r.playlist(e.media(),n),i.paused()||r.load()}),e.on("error",P0[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:n,segmentLoaders:{[s]:r},mediaTypes:{[s]:a}}=t;e.on("loadedmetadata",()=>{const u=e.media();r.playlist(u,n),r.track(a.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",P0[s](s,t))}},F8={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:n},requestOptions:r,main:{mediaGroups:a},mediaTypes:{[s]:{groups:u,tracks:c,logger_:d}},mainPlaylistLoader:f}=e,p=ef(f.main);(!a[s]||Object.keys(a[s]).length===0)&&(a[s]={main:{default:{default:!0}}},p&&(a[s].main.default.playlists=f.main.playlists));for(const y in a[s]){u[y]||(u[y]=[]);for(const v in a[s][y]){let b=a[s][y][v],S;if(p?(d(`AUDIO group '${y}' label '${v}' is a main playlist`),b.isMainPlaylist=!0,S=null):i==="vhs-json"&&b.playlists?S=new yc(b.playlists[0],t,r):b.resolvedUri?S=new yc(b.resolvedUri,t,r):b.playlists&&i==="dash"?S=new Nx(b.playlists[0],t,r,f):S=null,b=Qi({id:v,playlistLoader:S},b),OE[s](s,b.playlistLoader,e),u[y].push(b),typeof c[v]>"u"){const E=new Le.AudioTrack({id:v,kind:O8(b),enabled:!1,language:b.language,default:b.default,label:v});c[v]=E}}}n.on("error",P0[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:n,segmentLoaders:{[s]:r},requestOptions:a,main:{mediaGroups:u},mediaTypes:{[s]:{groups:c,tracks:d}},mainPlaylistLoader:f}=e;for(const p in u[s]){c[p]||(c[p]=[]);for(const y in u[s][p]){if(!i.options_.useForcedSubtitles&&u[s][p][y].forced)continue;let v=u[s][p][y],b;if(n==="hls")b=new yc(v.resolvedUri,i,a);else if(n==="dash"){if(!v.playlists.filter(E=>E.excludeUntil!==1/0).length)return;b=new Nx(v.playlists[0],i,a,f)}else n==="vhs-json"&&(b=new yc(v.playlists?v.playlists[0]:v.resolvedUri,i,a));if(v=Qi({id:y,playlistLoader:b},v),OE[s](s,v.playlistLoader,e),c[p].push(v),typeof d[y]>"u"){const S=t.addRemoteTextTrack({id:y,kind:"subtitles",default:v.default&&v.autoselect,language:v.language,label:y},!1).track;d[y]=S}}}r.on("error",P0[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:n,tracks:r}}}=e;for(const a in i[s]){n[a]||(n[a]=[]);for(const u in i[s][a]){const c=i[s][a][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=Qi(f,d[f.instreamId])),f.default===void 0&&delete f.default,n[a].push(Qi({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}}}}},kD=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:n}}}=e,r=i.media();if(!r)return null;let a=null;r.attributes[s]&&(a=n[r.attributes[s]]);const u=Object.keys(n);if(!a)if(s==="AUDIO"&&u.length>1&&ef(e.main))for(let c=0;c"u"?a:t===null||!a?null:a.filter(c=>c.id===t.id)[0]||null},j8={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}},$8=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},H8=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{F8[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:n,segmentLoaders:{["AUDIO"]:r,main:a}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=U8(d,s),e[d].activeTrack=j8[d](d,s),e[d].onGroupChanged=M8(d,s),e[d].onGroupChanging=P8(d,s),e[d].onTrackChanged=B8(d,s),e[d].getActiveGroup=$8(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?(a.setAudio(!1),r.setAudio(!0)):a.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])},z8=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Ao,activeTrack:Ao,getActiveGroup:Ao,onGroupChanged:Ao,onTrackChanged:Ao,lastTrack_:null,logger_:ta(`MediaGroups[${e}]`)}}),s};class ME{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_=pr(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 G8=class extends Le.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new ME,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_=ta("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=pr(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,a)=>{if(r){if(a.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(a.status===429){const d=a.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 he.URL(e),i=new he.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(he.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new he.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_=he.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){he.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 ME}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&&(pr(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}};const V8=(s,e)=>{let t=null;return(...i)=>{clearTimeout(t),t=setTimeout(()=>{s.apply(null,i)},e)}},q8=10;let pl;const K8=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],W8=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},Y8=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:a,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=!!gc(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=Wb(e,t),y=u?bn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:bn.MAX_BUFFER_LOW_WATER_LINE;if(ab)&&p>=n){let S=`${d} as forwardBuffer >= bufferLowWaterLine (${p} >= ${n})`;return u&&(S+=` and next bandwidth > current bandwidth (${v} > ${b})`),c(S),!0}return c(`not ${d} as no switching criteria met`),!1};class X8 extends Le.EventTarget{constructor(e){super(),this.fastQualityChange_=V8(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:n,bandwidth:r,externVhs:a,useCueTags:u,playlistExclusionDuration:c,enableLowInitialPlaylist:d,sourceType:f,cacheEncryptionKeys:p,bufferBasedABR:y,leastPixelDiffSelector:v,captionServices:b,experimentalUseMMS:S}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:E}=e;(E===null||typeof E>"u")&&(E=1/0),pl=a,this.bufferBasedABR=!!y,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=E,this.enableLowInitialPlaylist=d,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:E,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=z8(),S&&he.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new he.ManagedMediaSource,this.usingManagedMediaSource_=!0,Le.log("Using ManagedMediaSource")):he.MediaSource&&(this.mediaSource=new he.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_=Sn(),this.hasPlayed_=!1,this.syncController_=new L8(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new N8,this.sourceUpdater_=new ED(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new R8,this.keyStatusMap_=new Map;const L={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 Nx(t,this.vhs_,Qi(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new yc(t,this.vhs_,Qi(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Px(Qi(L,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Px(Qi(L,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new w8(Qi(L,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((H,F)=>{function $(){n.off("vttjserror",M),H()}function M(){n.off("vttjsloaded",$),F()}n.one("vttjsloaded",$),n.one("vttjserror",M),n.addWebVttScript_()})}),e);const N=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new G8(this.vhs_.xhr,N),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),K8.forEach(H=>{this[H+"_"]=W8.bind(this,H)}),this.logger_=ta("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 R=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(R,()=>{const H=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-H,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),a=e&&(e.id||e.uri);if(r&&r!==a){this.logger_(`switch media ${r} -> ${a} from ${t}`);const u={renditionInfo:{id:a,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 a=(i.length?i[0].playlists:i.playlists).filter(u=>u.attributes.serviceLocation===n);a.length&&this.mediaTypes_[e].activePlaylistLoader.media(a[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=he.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(he.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 a=[];for(const u in i)if(i[u][r.label]){const c=i[u][r.label];if(c.playlists&&c.playlists.length)a.push.apply(a,c.playlists);else if(c.uri)a.push(c);else if(e.playlists.length)for(let d=0;d{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;Cx(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()),H8({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;Cx(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(sn({},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 a in i.AUDIO)for(const u in i.AUDIO[a])i.AUDIO[a][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"}),pl.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(),a=this.tech_.buffered();return Y8({buffered:a,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:q8}))});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(sn({},n))}),this.audioSegmentLoader_.on(i,n=>{this.player_.trigger(sn({},n))}),this.subtitleSegmentLoader_.on(i,n=>{this.player_.trigger(sn({},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=pl.Playlist.playlistEnd(e,i),r=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return n-r<=Fa;const u=a.end(a.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(Cp),a=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(a);if(a){if(this.main().contentSteering){const b=this.pathwayAttribute_(e),S=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(b),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(b)},S);return}let v=!1;n.forEach(b=>{if(b===e)return;const S=b.excludeUntil;typeof S<"u"&&S!==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,y=typeof c.lastRequest=="number"&&Date.now()-c.lastRequest<=p;return this.switchMedia_(c,"exclude",a||y)}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(a=>{const u=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;u&&i.push(u)}),["main","audio","subtitle"].forEach(a=>{const u=this[`${a}SegmentLoader_`];u&&(e===a||e==="all")&&i.push(u)}),i.forEach(a=>t.forEach(u=>{typeof a[u]=="function"&&a[u]()}))}setCurrentTime(e){const t=gc(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:pl.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=pl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),f=Math.max(u,c-d);return Sn([[u,f]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(r===null)return null;const a=pl.Playlist.seekable(i,r,pl.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),r=t.start(0),a=t.end(0);return r>n||i>a?e:Sn([[Math.max(i,r),Math.min(n,a)]])}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 [${BC(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=Ch(this.main(),t),n={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||F3),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||E2}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||E2,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 a=(d,f)=>d?_h(f,this.usingManagedMediaSource_):Qy(f),u={};let c;if(["video","audio"].forEach(function(d){if(n.hasOwnProperty(d)&&!a(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=(Na(this.sourceUpdater_.codecs[f]||"")[0]||{}).type,y=(Na(n[f]||"")[0]||{}).type;p&&y&&p.toLowerCase()!==y.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=Ch(this.main,n),a=[];r.audio&&!Qy(r.audio)&&!_h(r.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${r.audio}`),r.video&&!Qy(r.video)&&!_h(r.video,this.usingManagedMediaSource_)&&a.push(`video codec ${r.video}`),r.text&&r.text==="stpp.ttml.im1t"&&a.push(`text codec ${r.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=Bh(Na(e)),r=yE(n),a=n.video&&Na(n.video)[0]||null,u=n.audio&&Na(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=Ch(this.mainPlaylistLoader_.main,d),y=yE(p);if(!(!p.audio&&!p.video)){if(y!==r&&f.push(`codec count "${y}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const v=p.video&&Na(p.video)[0]||null,b=p.audio&&Na(p.audio)[0]||null;v&&a&&v.type.toLowerCase()!==a.type.toLowerCase()&&f.push(`video codec "${v.type}" !== "${a.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)),k8(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=bn.GOAL_BUFFER_LENGTH,i=bn.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,bn.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=bn.BUFFER_LOW_WATER_LINE,i=bn.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,bn.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,bn.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:n)}bufferHighWaterLine(){return bn.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){wE(this.inbandTextTracks_,"com.apple.streaming",this.tech_),a8({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();wE(this.inbandTextTracks_,e,this.tech_),s8({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(sn({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),a=[];for(const u of t.playlists){const c=u.attributes.serviceLocation;if(c&&(a.push(c),!r.has(c)))return!0}return!!(!a.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(a=>{const u=i[a],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(a=>{const u=this.mediaTypes_[a];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[a,u]of i.entries())n.get(a)||(this.mainPlaylistLoader_.updateOrDeleteClone(u),this.contentSteeringController_.excludePathway(a));for(const[a,u]of n.entries()){const c=i.get(a);if(!c){t.filter(f=>f.attributes["PATHWAY-ID"]===u["BASE-ID"]).forEach(f=>{this.mainPlaylistLoader_.addClonePathway(u,f)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(c,u)||(this.mainPlaylistLoader_.updateOrDeleteClone(u,!0),this.contentSteeringController_.addAvailablePathway(a))}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 a="usable",u=this.keyStatusMap_.has(r)&&this.keyStatusMap_.get(r)===a,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 ${a}`)):(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 ${a}`)),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:_8(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 Q8=(s,e,t)=>i=>{const n=s.main.playlists[e],r=Xb(n),a=Cp(n);if(typeof i>"u")return a;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!==a&&!r&&(i?(t(n),s.trigger({type:"renditionenabled",metadata:u})):s.trigger({type:"renditiondisabled",metadata:u})),i};class Z8{constructor(e,t,i){const{playlistController_:n}=e,r=n.fastQualityChange_.bind(n);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=Ch(n.main(),t),this.playlist=t,this.id=i,this.enabled=Q8(e.playlists,t.id,r)}}const J8=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=ef(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Xb(i)).map((i,n)=>new Z8(s,i,i.id)):[]}},PE=["seeking","seeked","pause","playing","error"];class e6 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_=ta("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),a=this.playlistController_,u=["main","subtitle","audio"],c={};u.forEach(f=>{c[f]={reset:()=>this.resetSegmentDownloads_(f),updateend:()=>this.checkSegmentDownloads_(f)},a[`${f}SegmentLoader_`].on("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].on("playlistupdate",c[f].reset),this.tech_.on(["seeked","seeking"],c[f].reset)});const d=f=>{["main","audio"].forEach(p=>{a[`${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(PE,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(PE,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=>{a[`${f}SegmentLoader_`].off("appendsdone",c[f].updateend),a[`${f}SegmentLoader_`].off("playlistupdate",c[f].reset),this.tech_.off(["seeked","seeking"],c[f].reset)}),this.checkCurrentTimeTimeout_&&he.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&he.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=he.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=UB(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,r){const a={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:a}),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:pu(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(Sn([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 ${BC(t)}. Seeking to ${r}.`),this.tech_.setCurrentTime(r),!0;const a=this.playlistController_.sourceUpdater_,u=this.tech_.buffered(),c=a.audioBuffer?a.audioBuffered():null,d=a.videoBuffer?a.videoBuffered():null,f=this.media(),p=f.partTargetDuration?f.partTargetDuration:(f.targetDuration-Ba)*2,y=[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 a=km(n,t);return a.length>0?(this.logger_(`Stopped at ${t} and seeking to ${a.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 a=!i.endList,u=typeof i.partTargetDuration=="number";return a&&(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:a}}return null}}const t6={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},CD=function(s,e){let t=0,i=0;const n=Qi(t6,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const r=function(){i&&s.currentTime(i)},a=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(Us,s,{get(){return Le.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),bn[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}bn[s]=e}})});const LD="videojs-vhs",RD=function(s,e){const t=e.media();let i=-1;for(let n=0;n{s.addQualityLevel(t)}),RD(s,e.playlists)};Us.canPlaySource=function(){return Le.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const l6=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=Bh(Na(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const n=Bc(i.video),r=Bc(i.audio),a={};for(const u in s)a[u]={},r&&(a[u].audioContentType=r),n&&(a[u].videoContentType=n),e.contentProtection&&e.contentProtection[u]&&e.contentProtection[u].pssh&&(a[u].pssh=e.contentProtection[u].pssh),typeof s[u]=="string"&&(a[u].url=s[u]);return Qi(s,a)},u6=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const n=e.reduce((r,a)=>{const u=i.contentProtection[a];return u&&u.pssh&&(r[a]={pssh:u.pssh}),r},{});return Object.keys(n).length&&t.push(n),t},[]),c6=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const n=t?i.concat([t]):i,r=u6(n,Object.keys(e)),a=[],u=[];return r.forEach(c=>{u.push(new Promise((d,f)=>{s.tech_.one("keysessioncreated",d)})),a.push(new Promise((d,f)=>{s.eme.initializeMediaKeys({keySystems:c},p=>{if(p){f(p);return}d()})}))}),Promise.race([Promise.all(a),Promise.race(u)])},d6=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const n=l6(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},ID=()=>{if(!he.localStorage)return null;const s=he.localStorage.getItem(LD);if(!s)return null;try{return JSON.parse(s)}catch{return null}},h6=s=>{if(!he.localStorage)return!1;let e=ID();e=e?Qi(e,s):s;try{he.localStorage.setItem(LD,JSON.stringify(e))}catch{return!1}return e},f6=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,ND=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},OD=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},MD=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},PD=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};Us.supportsNativeHls=(function(){if(!yt||!yt.createElement)return!1;const s=yt.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})();Us.supportsNativeDash=(function(){return!yt||!yt.createElement||!Le.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(yt.createElement("video").canPlayType("application/dash+xml"))})();Us.supportsTypeNatively=s=>s==="hls"?Us.supportsNativeHls:s==="dash"?Us.supportsNativeDash:!1;Us.isSupported=function(){return Le.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Us.xhr.onRequest=function(s){ND(Us.xhr,s)};Us.xhr.onResponse=function(s){OD(Us.xhr,s)};Us.xhr.offRequest=function(s){MD(Us.xhr,s)};Us.xhr.offResponse=function(s){PD(Us.xhr,s)};const m6=Le.getComponent("Component");class BD extends m6{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=ta("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(yt,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const r=yt.fullscreenElement||yt.webkitFullscreenElement||yt.mozFullScreenElement||yt.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_=Qi(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=ID();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=bn.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===bn.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=f6(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Us,this.options_.sourceType=nk(t),this.options_.seekTo=r=>{this.tech_.setCurrentTime(r)},this.options_.player_=this.player_,this.playlistController_=new X8(this.options_);const i=Qi({liveRangeSafeTimeDelta:Fa},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new e6(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const r=Le.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),r.error(a)});const n=this.options_.bufferBasedABR?Us.movingAverageBandwidthSelector(.55):Us.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Us.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 a=he.navigator.connection||he.navigator.mozConnection||he.navigator.webkitConnection,u=1e7;if(this.options_.useNetworkInformationApi&&a){const c=a.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 a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(r+a))},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:()=>pu(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:()=>pu(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&&h6({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{J8(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_=he.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"),c6({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=d6({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",()=>{o6(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{RD(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":DD,"mux.js":s6,"mpd-parser":n6,"m3u8-parser":r6,"aes-decrypter":a6}}version(){return this.constructor.version()}canChangeType(){return ED.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_&&he.URL.revokeObjectURL&&(he.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return vF({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return oD({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=>{ND(this.xhr,e)},this.xhr.onResponse=e=>{OD(this.xhr,e)},this.xhr.offRequest=e=>{MD(this.xhr,e)},this.xhr.offResponse=e=>{PD(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(sn({},n))})}),t.forEach(i=>{this.playbackWatcher_.on(i,n=>{this.player_.trigger(sn({},n))})})}}const B0={name:"videojs-http-streaming",VERSION:DD,canHandleSource(s,e={}){const t=Qi(Le.options,e);return!t.vhs.experimentalUseMMS&&!_h("avc1.4d400d,mp4a.40.2",!1)?!1:B0.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=Qi(Le.options,t);return e.vhs=new BD(s,e,i),e.vhs.xhr=iD(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=nk(s);if(!t)return"";const i=B0.getOverrideNative(e);return!Us.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}},p6=()=>_h("avc1.4d400d,mp4a.40.2",!0);p6()&&Le.getTech("Html5").registerSourceHandler(B0,0);Le.VhsHandler=BD;Le.VhsSourceHandler=B0;Le.Vhs=Us;Le.use||Le.registerComponent("Vhs",Us);Le.options.vhs=Le.options.vhs||{};(!Le.getPlugin||!Le.getPlugin("reloadSourceOnError"))&&Le.registerPlugin("reloadSourceOnError",i6);const g6="",xl=s=>{const e=s.startsWith("/")?s:`/${s}`;return`${g6}${e}`};async function vv(s,e){const t=await fetch(xl(s),{...e,credentials:"include",headers:{...e?.headers??{},"Content-Type":e?.headers?.["Content-Type"]??"application/json"}});return t.status===401&&(location.pathname.startsWith("/login")||(location.href="/login")),t}const kt=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},y6=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=v6},v6=Number.MAX_SAFE_INTEGER||9007199254740991;let $t=(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})({}),Re=(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})({}),z=(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 Ci={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Rt={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ac{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 x6{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 ac(e),this.fast_=new ac(t),this.defaultTTFB_=n,this.ttfb_=new ac(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new ac(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new ac(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new ac(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 b6(s,e,t){return(e=S6(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function ds(){return ds=Object.assign?Object.assign.bind():function(s){for(var e=1;e`):Sl}function FE(s,e,t){return e[s]?e[s].bind(e):E6(s,t)}const jx=Ux();function w6(s,e,t){const i=Ux();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(r=>{i[r]=FE(r,s,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Ux()}n.forEach(r=>{jx[r]=FE(r,s)})}else ds(jx,i);return i}const ns=jx;function Rl(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function A6(s){return typeof self<"u"&&s===self.ManagedMediaSource}function FD(s,e){const t=Object.keys(s),i=Object.keys(e),n=t.length,r=i.length;return!n||!r||n===r&&!t.some(a=>i.indexOf(a)===-1)}function jr(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,a="",u=0;for(;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=s[u++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=s[u++],r=s[u++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(r&63)<<0);break}}return a}function Nn(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(!kt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return tn(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,a=!1){const{elementaryStreams:u}=this,c=u[e];if(!c){u[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};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 D6 extends jD{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 a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,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 $D(s,e){const t=Object.getPrototypeOf(s);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||$D(t,e)}}function L6(s,e){const t=$D(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const jE=Math.pow(2,32)-1,R6=[].push,HD={video:1,audio:2,id3:3,text:4};function hn(s){return String.fromCharCode.apply(null,s)}function zD(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function ci(s,e){const t=GD(s,e);return t<0?4294967296+t:t}function $E(s,e){let t=ci(s,e);return t*=Math.pow(2,32),t+=ci(s,e+4),t}function GD(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function I6(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 Ai(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,u));else{const c=Ai(s.subarray(n+8,u),e.slice(1));c.length&&R6.apply(t,c)}n=u}return t}function N6(s){const e=[],t=s[0];let i=8;const n=ci(s,i);i+=4;let r=0,a=0;t===0?(r=ci(s,i),a=ci(s,i+4),i+=8):(r=$E(s,i),a=$E(s,i+8),i+=16),i+=2;let u=s.length+a;const c=zD(s,i);i+=2;for(let d=0;d>>31===1)return ns.warn("SIDX has hierarchical references (not supported)"),null;const b=ci(s,f);f+=4,e.push({referenceSize:y,subsegmentDuration:b,info:{duration:b/n,start:u,end:u+y-1}}),u+=y,f+=4,i=f}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:c,references:e}}function VD(s){const e=[],t=Ai(s,["moov","trak"]);for(let n=0;n{const r=ci(n,4),a=e[r];a&&(a.default={duration:ci(n,12),flags:ci(n,20)})}),e}function O6(s){const e=s.subarray(8),t=e.subarray(86),i=hn(e.subarray(4,8));let n=i,r;const a=i==="enca"||i==="encv";if(a){const d=Ai(e,[i])[0].subarray(i==="enca"?28:78);Ai(d,["sinf"]).forEach(p=>{const y=Ai(p,["schm"])[0];if(y){const v=hn(y.subarray(4,8));if(v==="cbcs"||v==="cenc"){const b=Ai(p,["frma"])[0];b&&(n=hn(b))}}})}const u=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Ai(t,["avcC"])[0];c&&c.length>3&&(n+="."+Rm(c[1])+Rm(c[2])+Rm(c[3]),r=Lm(u==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Ai(e,[i])[0],d=Ai(c.subarray(28),["esds"])[0];if(d&&d.length>7){let f=4;if(d[f++]!==3)break;f=Tv(d,f),f+=2;const p=d[f++];if(p&128&&(f+=2),p&64&&(f+=d[f++]),d[f++]!==4)break;f=Tv(d,f);const y=d[f++];if(y===64)n+="."+Rm(y);else break;if(f+=12,d[f++]!==5)break;f=Tv(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=Ai(t,["hvcC"])[0];if(c&&c.length>12){const d=c[1],f=["","A","B","C"][d>>6],p=d&31,y=ci(c,2),v=(d&32)>>5?"H":"L",b=c[12],S=c.subarray(6,12);n+="."+f+p,n+="."+M6(y).toString(16).toUpperCase(),n+="."+v+b;let E="";for(let L=S.length;L--;){const N=S[L];(N||E)&&(E="."+N.toString(16).toUpperCase()+E)}n+=E}r=Lm(u=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Lm(n,t)||n;break}case"vp09":{const c=Ai(t,["vpcC"])[0];if(c&&c.length>6){const d=c[4],f=c[5],p=c[6]>>4&15;n+="."+Ia(d)+"."+Ia(f)+"."+Ia(p)}break}case"av01":{const c=Ai(t,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,f=c[1]&31,p=c[2]>>>7?"H":"M",y=(c[2]&64)>>6,v=(c[2]&32)>>5,b=d===2&&y?v?12:10:y?10:8,S=(c[2]&16)>>4,E=(c[2]&8)>>3,L=(c[2]&4)>>2,N=c[2]&3;n+="."+d+"."+Ia(f)+p+"."+Ia(b)+"."+S+"."+E+L+N+"."+Ia(1)+"."+Ia(1)+"."+Ia(1)+"."+0,r=Lm("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function Lm(s,e){const t=Ai(e,["dvvC"]),i=t.length?t[0]:Ai(e,["dvcC"])[0];if(i){const n=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return s+"."+Ia(n)+"."+Ia(r)}}function M6(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Tv(s,e){const t=e+5;for(;s[e++]&128&&e{const r=i.subarray(8,24);r.some(a=>a!==0)||(ns.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${Nn(r)} -> ${Nn(t)}`),i.set(t,8))})}function B6(s){const e=[];return qD(s,t=>e.push(t.subarray(8,24))),e}function qD(s,e){Ai(s,["moov","trak"]).forEach(i=>{const n=Ai(i,["mdia","minf","stbl","stsd"])[0];if(!n)return;const r=n.subarray(8);let a=Ai(r,["enca"]);const u=a.length>0;u||(a=Ai(r,["encv"])),a.forEach(c=>{const d=u?c.subarray(28):c.subarray(78);Ai(d,["sinf"]).forEach(p=>{const y=KD(p);y&&e(y,u)})})})}function KD(s){const e=Ai(s,["schm"])[0];if(e){const t=hn(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=Ai(s,["schi","tenc"])[0];if(i)return i}}}function F6(s,e,t){const i={},n=Ai(s,["moof","traf"]);for(let r=0;ri[r].duration)){let r=1/0,a=0;const u=Ai(s,["sidx"]);for(let c=0;cp+y.info.duration||0,0);a=Math.max(a,f+d.earliestPresentationTime/d.timescale)}}a&&kt(a)&&Object.keys(i).forEach(c=>{i[c].duration||(i[c].duration=a*i[c].timescale-i[c].start)})}return i}function U6(s){const e={valid:null,remainder:null},t=Ai(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 Jr(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function HE(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return Ai(i,["moof"]).map(c=>{const d=c.byteOffset-8;Ai(c,["traf"]).map(p=>{const y=Ai(p,["tfdt"]).map(v=>{const b=v[0];let S=ci(v,4);return b===1&&(S*=Math.pow(2,32),S+=ci(v,8)),S/n})[0];return y!==void 0&&(s=y),Ai(p,["tfhd"]).map(v=>{const b=ci(v,4),S=ci(v,0)&16777215,E=(S&1)!==0,L=(S&2)!==0,N=(S&8)!==0;let R=0;const H=(S&16)!==0;let F=0;const $=(S&32)!==0;let M=8;b===r&&(E&&(M+=8),L&&(M+=4),N&&(R=ci(v,M),M+=4),H&&(F=ci(v,M),M+=4),$&&(M+=4),e.type==="video"&&(a=Dp(e.codec)),Ai(p,["trun"]).map(W=>{const D=W[0],I=ci(W,0)&16777215,Q=(I&1)!==0;let K=0;const q=(I&4)!==0,le=(I&256)!==0;let te=0;const V=(I&512)!==0;let G=0;const J=(I&1024)!==0,ie=(I&2048)!==0;let oe=0;const j=ci(W,4);let X=8;Q&&(K=ci(W,X),X+=4),q&&(X+=4);let se=K+d;for(let fe=0;fe>1&63;return t===39||t===40}else return(e&31)===6}function i1(s,e,t,i){const n=WD(s);let r=0;r+=e;let a=0,u=0,c=0;for(;r=n.length)break;c=n[r++],a+=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){ns.error(`Malformed SEI payload. ${u} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(n[f++]===181){const y=zD(n,f);if(f+=2,y===49){const v=ci(n,f);if(f+=4,v===1195456820){const b=n[f++];if(b===3){const S=n[f++],E=31&S,L=64&S,N=L?2+E*3:0,R=new Uint8Array(N);if(L){R[0]=S;for(let H=1;H16){const p=[];for(let b=0;b<16;b++){const S=n[f++].toString(16);p.push(S.length==1?"0"+S:S),(b===3||b===5||b===7||b===9)&&p.push("-")}const y=u-16,v=new Uint8Array(y);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 a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),H6([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t)}function G6(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 a=s.buffer,u=Nn(new Uint8Array(a,t+12,16));let c=null,d=null,f=0;if(r===0)f=28;else{const y=s.getUint32(28);if(!y||i<32+y*16)return{offset:t,size:e};c=[];for(let v=0;v/\(Windows.+Firefox\//i.test(navigator.userAgent),qc={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 s1(s,e){const t=qc[e];return!!t&&!!t[s.slice(0,4)]}function Fh(s,e,t=!0){return!s.split(",").some(i=>!n1(i,e,t))}function n1(s,e,t=!0){var i;const n=Rl(t);return(i=n?.isTypeSupported(Uh(s,e)))!=null?i:!1}function Uh(s,e){return`${e}/mp4;codecs=${s}`}function zE(s){if(s){const e=s.substring(0,4);return qc.video[e]}return 2}function F0(s){const e=YD();return s.split(",").reduce((t,i)=>{const r=e&&Dp(i)?9:qc.video[i];return r?(r*2+t)/(t?3:2):(qc.audio[i]+t)/(t?2:1)},0)}const Sv={};function q6(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;nq6(t.toLowerCase(),e))}function W6(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)&&(GE(s,"audio")||GE(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 GE(s,e){return s1(s,e)&&n1(s,e)}function Y6(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 VE(s){const e=Rl(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 $x(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Q6={supported:!0,powerEfficient:!0,smooth:!0},Z6={supported:!1,smooth:!1,powerEfficient:!1},XD={supported:!0,configurations:[],decodingInfoResults:[Q6]};function QD(s,e){return{supported:!1,configurations:e,decodingInfoResults:[Z6],error:s}}function J6(s,e,t,i,n,r){const a=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((y,v)=>{if(v){const b=e.groups[v];if(!b)throw new Error(`Audio track group ${v} not found`);Object.keys(b.channels).forEach(S=>{y[S]=(y[S]||0)+b.channels[S]})}return y},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(y=>Dp(y))||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&&kt(f)&&Object.keys(p).some(y=>parseInt(y)>f)}function ZD(s,e,t,i={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(XD);const r=[],a=eU(s),u=a.length,c=tU(s,e,u>0),d=c.length;for(let f=u||1*d||1;f--;){const p={type:"media-source"};if(u&&(p.video=a[f%u]),d){p.audio=c[f%d];const y=p.audio.bitrate;p.video&&y&&(p.video.bitrate-=y)}r.push(p)}if(n){const f=navigator.userAgent;if(n.split(",").some(p=>Dp(p))&&YD())return Promise.resolve(QD(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${f})`),r))}return Promise.all(r.map(f=>{const p=sU(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 eU(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),i=JD(s),n=s.width||640,r=s.height||480,a=s.frameRate||30,u=s.videoRange.toLowerCase();return t?t.map(c=>{const d={contentType:Uh(X6(c),"video"),width:n,height:r,bitrate:i,framerate:a};return u!=="sdr"&&(d.transferFunction=u),d}):[]}function tU(s,e,t){var i;const n=(i=s.audioCodec)==null?void 0:i.split(","),r=JD(s);return n&&s.audioGroups?s.audioGroups.reduce((a,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 y=parseFloat(p.channels||"");n.forEach(v=>{const b={contentType:Uh(v,"audio"),bitrate:t?iU(v,r):r};y&&(b.channels=""+y),f.push(b)})}return f},a):a},[]):[]}function iU(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 JD(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function sU(s){let e="";const{audio:t,video:i}=s;if(i){const n=$x(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=$x(t.contentType);e+=`${i?"_":""}${n}_c${t.channels}`}return e}const Hx=["NONE","TYPE-0","TYPE-1",null];function nU(s){return Hx.indexOf(s)>-1}const j0=["SDR","PQ","HLG"];function rU(s){return!!s&&j0.indexOf(s)>-1}var t0={No:"",Yes:"YES",v2:"v2"};function qE(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 WE(this._audioGroups,e)}hasSubtitleGroup(e){return WE(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 WE(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function aU(){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 oU(s,e){let t=!1,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||j0.slice(0);const n=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&aU(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const lU=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}},ys=(s,e)=>JSON.stringify(s,lU(e));function uU(s,e,t,i,n){const r=Object.keys(s),a=i?.channels,u=i?.audioCodec,c=n?.videoCodec,d=a&&parseInt(a)===2;let f=!1,p=!1,y=1/0,v=1/0,b=1/0,S=1/0,E=0,L=[];const{preferHDR:N,allowedVideoRanges:R}=oU(e,n);for(let W=r.length;W--;){const D=s[r[W]];f||(f=D.channels[2]>0),y=Math.min(y,D.minHeight),v=Math.min(v,D.minFramerate),b=Math.min(b,D.minBitrate),R.filter(Q=>D.videoRanges[Q]>0).length>0&&(p=!0)}y=kt(y)?y:0,v=kt(v)?v:0;const H=Math.max(1080,y),F=Math.max(30,v);b=kt(b)?b:t,t=Math.max(b,t),p||(e=void 0);const $=r.length>1;return{codecSet:r.reduce((W,D)=>{const I=s[D];if(D===W)return W;if(L=p?R.filter(Q=>I.videoRanges[Q]>0):[],$){if(I.minBitrate>t)return Da(D,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),W;if(!I.hasDefaultAudio)return Da(D,"no renditions with default or auto-select sound found"),W;if(u&&D.indexOf(u.substring(0,4))%5!==0)return Da(D,`audio codec preference "${u}" not found`),W;if(a&&!d){if(!I.channels[a])return Da(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),W}else if((!u||d)&&f&&I.channels[2]===0)return Da(D,"no renditions with stereo sound found"),W;if(I.minHeight>H)return Da(D,`min resolution of ${I.minHeight} > maximum of ${H}`),W;if(I.minFramerate>F)return Da(D,`min framerate of ${I.minFramerate} > maximum of ${F}`),W;if(!L.some(Q=>I.videoRanges[Q]>0))return Da(D,`no variants with VIDEO-RANGE of ${ys(L)} found`),W;if(c&&D.indexOf(c.substring(0,4))%5!==0)return Da(D,`video codec preference "${c}" not found`),W;if(I.maxScore=F0(W)||I.fragmentError>s[W].fragmentError)?W:(S=I.minIndex,E=I.maxScore,D)},void 0),videoRanges:L,preferHDR:N,minFramerate:v,minBitrate:b,minIndex:S}}function Da(s,e){ns.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function eL(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 cU(s,e,t,i){return s.slice(t,i+1).reduce((n,r,a)=>{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:a,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,a),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(y=>{c.channels[y]=(c.channels[y]||0)+p.channels[y]}))}),n},{})}function YE(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 ja(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 cu(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 fU(s,e,t,i,n){const r=e[i],u=e.reduce((y,v,b)=>{const S=v.uri;return(y[S]||(y[S]=[])).push(b),y},{})[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=XE(e,i,y=>{if(y.videoRange!==c||y.frameRate!==d||y.codecSet.substring(0,4)!==f)return!1;const v=y.audioGroups,b=t.filter(S=>!v||v.indexOf(S.groupId)!==-1);return ja(s,b,n)>-1});return p>-1?p:XE(e,i,y=>{const v=y.audioGroups,b=t.filter(S=>!v||v.indexOf(S.groupId)!==-1);return ja(s,b,n)>-1})}function XE(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:a}=this,{autoLevelEnabled:u,media:c}=a;if(!n||!c)return;const d=performance.now(),f=r?r.stats:n.stats,p=r?r.duration:n.duration,y=d-f.loading.start,v=a.minAutoLevel,b=n.level,S=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||b<=v){this.clearTimer(),this._nextAutoLevel=-1;return}if(!u)return;const E=S>-1&&S!==b,L=!!t||E;if(!L&&(c.paused||!c.playbackRate||!c.readyState))return;const N=a.mainForwardBufferInfo;if(!L&&N===null)return;const R=this.bwEstimator.getEstimateTTFB(),H=Math.abs(c.playbackRate);if(y<=Math.max(R,1e3*(p/(H*2))))return;const F=N?N.len/H:0,$=f.loading.first?f.loading.first-f.loading.start:-1,M=f.loaded&&$>-1,W=this.getBwEstimate(),D=a.levels,I=D[b],Q=Math.max(f.loaded,Math.round(p*(n.bitrate||I.averageBitrate)/8));let K=M?y-$:y;K<1&&M&&(K=Math.min(y,f.loaded*8/W));const q=M?f.loaded*1e3/K:0,le=R/1e3,te=q?(Q-f.loaded)/q:Q*8/W+le;if(te<=F)return;const V=q?q*8:W,G=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,J=this.hls.config.abrBandWidthUpFactor;let ie=Number.POSITIVE_INFINITY,oe;for(oe=b-1;oe>v;oe--){const fe=D[oe].maxBitrate,pe=!D[oe].details||G;if(ie=this.getTimeToLoadFrag(le,V,p*fe,pe),ie=te||ie>p*10)return;M?this.bwEstimator.sample(y-Math.min(R,$),f.loaded):this.bwEstimator.sampleTTFB(y);const j=D[oe].maxBitrate;this.getBwEstimate()*J>j&&this.resetEstimator(j);const X=this.findBestLevel(j,v,oe,0,F,1,1);X>-1&&(oe=X),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: ${F.toFixed(3)} s Estimated load time for current fragment: ${te.toFixed(3)} s Estimated load time for down switch fragment: ${ie.toFixed(3)} s TTFB estimate: ${$|0} ms Current BW estimate: ${kt(W)?W|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${oe} @ ${j|0} bps`),a.nextLoadLevel=a.nextAutoLevel=oe,this.clearTimer();const se=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===oe&&oe>0){const fe=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${oe>0?"and switching down":""} Fragment duration: ${n.duration.toFixed(3)} s Time to underbuffer: ${fe.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,oe>v){let pe=this.findBestLevel(this.hls.levels[v].bitrate,v,oe,0,fe,1,1);pe===-1&&(pe=v),this.hls.nextLoadLevel=this.hls.nextAutoLevel=pe,this.resetEstimator(this.hls.levels[pe].bitrate)}}};E||te>ie*2?se():this.timer=self.setInterval(se,ie*1e3),a.trigger(z.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 x6(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.FRAG_LOADING,this.onFragLoading,this),e.on(z.FRAG_LOADED,this.onFragLoaded,this),e.on(z.FRAG_BUFFERED,this.onFragBuffered,this),e.on(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(z.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.FRAG_LOADING,this.onFragLoading,this),e.off(z.FRAG_LOADED,this.onFragLoaded,this),e.off(z.FRAG_BUFFERED,this.onFragBuffered,this),e.off(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(z.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(z.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 Re.BUFFER_ADD_CODEC_ERROR:case Re.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Re.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:n,partCurrent:r}=this;if(i&&n&&i.sn===n.sn&&i.level===n.level){const a=performance.now(),u=r?r.stats:i.stats,c=a-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,a=n?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:n}=t.stats,r=n.end-n.first;kt(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===Rt.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,a=this.hls.levels[t.level],u=(a.loaded?a.loaded.bytes:0)+n.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:u,duration:c},a.realBitrate=Math.round(8*u/c)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(z.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 a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Rt.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 a=this.hls.firstLevel,u=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${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 a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[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:a}=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 E=this.findBestLevel(c,a,n,d,0,f,p);if(E>=0)return this.rebufferNotice=-1,E}let y=u?Math.min(u,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const E=this.bitrateTestDelay;E&&(y=(u?Math.min(u,r.maxLoadingDelay):r.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*y)} ms`),f=p=1)}const v=this.findBestLevel(c,a,n,d,y,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[a],S=i.loadLevelObj;return S&&b?.bitrate=t;V--){var te;const G=b[V],J=V>p;if(!G)continue;if(L.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const pe=navigator.mediaCapabilities;typeof pe?.decodingInfo=="function"&&J6(G,I,$,M,e,W)?(G.supportedPromise=ZD(G,I,pe,this.supportedCache),G.supportedPromise.then(de=>{if(!this.hls)return;G.supportedResult=de;const Ve=this.hls.levels,Ze=Ve.indexOf(G);de.error?this.warn(`MediaCapabilities decodingInfo error: "${de.error}" for level ${Ze} ${ys(de)}`):de.supported?de.decodingInfoResults.some(Je=>Je.smooth===!1||Je.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ze} not smooth or powerEfficient: ${ys(de)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ze} ${ys(de)}`),Ze>-1&&Ve.length>1&&(this.log(`Removing unsupported level ${Ze}`),this.hls.removeLevel(Ze),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(de=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${de}`)})):G.supportedResult=XD}if((F&&G.codecSet!==F||$&&G.videoRange!==$||J&&M>G.frameRate||!J&&M>0&&Mpe.smooth===!1))&&(!H||V!==Q)){le.push(V);continue}const ie=G.details,oe=(v?ie?.partTarget:ie?.averagetargetduration)||K;let j;J?j=u*e:j=a*e;const X=K&&n>=K*2&&r===0?G.averageBitrate:G.maxBitrate,se=this.getTimeToLoadFrag(q,j,X*oe,ie===void 0);if(j>=X&&(V===f||G.loadError===0&&G.fragmentError===0)&&(se<=q||!kt(se)||R&&!this.bitrateTestDelay||se${V} adjustedbw(${Math.round(j)})-bitrate=${Math.round(j-X)} ttfb:${q.toFixed(1)} avgDuration:${oe.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${se.toFixed(1)} firstSelection:${H} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${E}`)),H&&(this.firstSelection=V),V}}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 tL={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 a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function pU(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!kt(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)&&QE(t,i,r)===0||gU(r,s,Math.min(n,i))))return r;const a=tL.search(e,QE.bind(null,t,i));return a&&(a!==s||!r)?a:r}function gU(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 QE(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 yU(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function iL(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 tL.search(i,a=>a.cce?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function H0(s){switch(s.details){case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_TIMEOUT:case Re.LEVEL_LOAD_TIMEOUT:case Re.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function sL(s){return s.details.startsWith("key")}function nL(s){return sL(s)&&!!s.frag&&!s.frag.decryptdata}function ZE(s,e){const t=H0(e);return s.default[`${t?"timeout":"error"}Retry`]}function r1(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function JE(s){return ss(ss({},s),{errorRetry:null,timeoutRetry:null})}function z0(s,e,t,i){if(!s)return!1;const n=i?.code,r=e499)}function zx(s){return s===0&&navigator.onLine===!1}var Rn={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Pr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class xU extends ia{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(z.ERROR,this.onError,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(z.ERROR,this.onError,this),e.off(z.ERROR,this.onErrorOut,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===Rt.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(a=>n.indexOf(a.groupId)>=0).some(a=>{var u;return(u=a.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 Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case Re.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Lc();return}case Re.FRAG_GAP:case Re.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Rn.SendAlternateToPenaltyBox;return}case Re.LEVEL_EMPTY_ERROR:case Re.LEVEL_PARSING_ERROR:{var a;const c=t.parent===Rt.MAIN?t.level:n.loadLevel;t.details===Re.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case Re.LEVEL_LOAD_ERROR:case Re.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case Re.AUDIO_TRACK_LOAD_ERROR:case Re.AUDIO_TRACK_LOAD_TIMEOUT:case Re.SUBTITLE_LOAD_ERROR:case Re.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=n.loadLevelObj;if(c&&(r.type===Ci.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Ci.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Rn.SendAlternateToPenaltyBox,t.errorAction.flags=Pr.MoveAllAlternatesMatchingHost;return}}return;case Re.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Rn.SendAlternateToPenaltyBox,flags:Pr.MoveAllAlternatesMatchingHDCP};return;case Re.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Re.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Re.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Rn.SendAlternateToPenaltyBox,flags:Pr.MoveAllAlternatesMatchingKey};return;case Re.BUFFER_ADD_CODEC_ERROR:case Re.REMUX_ALLOC_ERROR:case Re.BUFFER_APPEND_ERROR:if(!t.errorAction){var u;t.errorAction=this.getLevelSwitchAction(t,(u=t.level)!=null?u:n.loadLevel)}return;case Re.INTERNAL_EXCEPTION:case Re.BUFFER_APPENDING_ERROR:case Re.BUFFER_FULL_ERROR:case Re.LEVEL_SWITCH_ERROR:case Re.BUFFER_STALLED_ERROR:case Re.BUFFER_SEEK_OVER_HOLE:case Re.BUFFER_NUDGE_ON_STALL:t.errorAction=Lc();return}t.type===$t.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Lc())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,n=ZE(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(z0(n,r,H0(e),e.response))return{action:Rn.RetryRequest,flags:Pr.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:a}=t.config,u=ZE(sL(e)?a:r,e),c=t.levels.reduce((f,p)=>f+p.fragmentError,0);if(n&&(e.details!==Re.FRAG_GAP&&n.fragmentError++,!nL(e)&&z0(u,c,H0(e),e.response)))return{action:Rn.RetryRequest,flags:Pr.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,a;const d=e.details;n.loadError++,d===Re.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:p,loadLevel:y,minAutoLevel:v,maxAutoLevel:b}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const S=(r=e.frag)==null?void 0:r.type,L=(S===Rt.AUDIO&&d===Re.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===Re.BUFFER_ADD_CODEC_ERROR||d===Re.BUFFER_APPEND_ERROR))&&p.some(({audioCodec:$})=>n.audioCodec!==$),R=e.sourceBufferName==="video"&&(d===Re.BUFFER_ADD_CODEC_ERROR||d===Re.BUFFER_APPEND_ERROR)&&p.some(({codecSet:$,audioCodec:M})=>n.codecSet!==$&&n.audioCodec===M),{type:H,groupId:F}=(a=e.context)!=null?a:{};for(let $=p.length;$--;){const M=($+y)%p.length;if(M!==y&&M>=v&&M<=b&&p[M].loadError===0){var u,c;const W=p[M];if(d===Re.FRAG_GAP&&S===Rt.MAIN&&e.frag){const D=p[M].details;if(D){const I=ku(e.frag,D.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(H===Ci.AUDIO_TRACK&&W.hasAudioGroup(F)||H===Ci.SUBTITLE_TRACK&&W.hasSubtitleGroup(F))continue;if(S===Rt.AUDIO&&(u=n.audioGroups)!=null&&u.some(D=>W.hasAudioGroup(D))||S===Rt.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(D=>W.hasSubtitleGroup(D))||L&&n.audioCodec===W.audioCodec||R&&n.codecSet===W.codecSet||!L&&n.codecSet!==W.codecSet)continue}f=M;break}}if(f>-1&&i.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:Rn.SendAlternateToPenaltyBox,flags:Pr.None,nextAutoLevel:f}}return{action:Rn.SendAlternateToPenaltyBox,flags:Pr.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case Rn.DoNothing:break;case Rn.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==Re.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 Pr.None:this.switchLevel(e,r);break;case Pr.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=Hx[Hx.indexOf(f)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Pr.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const d=this.hls.levels,f=d.length;for(let y=f;y--;)if(this.variantHasKey(d[y],c)){var a,u;this.log(`Banned key found in level ${y} (${d[y].bitrate}bps) or audio group "${(a=d[y].audioGroups)==null?void 0:a.join(",")}" (${(u=e.frag)==null?void 0:u.type} fragment) ${Nn(c.keyId||[])}`),d[y].fragmentError++,d[y].loadError++,this.log(`Removing level ${y} with key error (${e.error})`),this.hls.removeLevel(y)}const p=e.frag;if(this.hls.levels.length{const c=this.fragments[u];if(!c||a>=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=oc(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const a=!i.relurl;Object.keys(t).forEach(u=>{const c=i.elementaryStreams[u];if(!c)return;const d=t[u],f=a||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),Im(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]=ew(i,n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=oc(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},a=e.start,u=e.end,c=e.minEndPTS||u,d=e.maxStartPTS||a;for(let f=0;f=p&&c<=y){r.time.push({startPTS:Math.max(a,n.start(f)),endPTS:Math.min(u,n.end(f))});break}else if(ap){const v=Math.max(a,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,a=0;const{bufferPadding:u,fragments:c}=this;return Object.keys(c).forEach(d=>{const f=c[d];f&&Im(f)&&(n=f.body.start-u,r=f.body.end+u,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=f.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Im(t))}getState(e){const t=oc(e),i=this.fragments[t];return i?i.buffered?Im(i)?fn.PARTIAL:fn.OK:fn.APPENDING:fn.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a=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=oc(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:a}=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[a];this.detectEvictedFragments(a,c,u,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=oc(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(a=>{const u=this.fragments[a];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=oc(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=ew(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 Im(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 oc(s){return`${s.type}_${s.level}_${s.sn}`}function ew(s,e){return s.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Il={cbc:0,ctr:1};class TU{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 Il.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Il.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 SU(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class _U{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],a=i[2],u=i[3],c=this.invSubMix,d=c[0],f=c[1],p=c[2],y=c[3],v=new Uint32Array(256);let b=0,S=0,E=0;for(E=0;E<256;E++)E<128?v[E]=E<<1:v[E]=E<<1^283;for(E=0;E<256;E++){let L=S^S<<1^S<<2^S<<3^S<<4;L=L>>>8^L&255^99,e[b]=L,t[L]=b;const N=v[b],R=v[N],H=v[R];let F=v[L]*257^L*16843008;n[b]=F<<24|F>>>8,r[b]=F<<16|F>>>16,a[b]=F<<8|F>>>24,u[b]=F,F=H*16843009^R*65537^N*257^b*16843008,d[L]=F<<24|F>>>8,f[L]=F<<16|F>>>16,p[L]=F<<8|F>>>24,y[L]=F,b?(b=N^v[v[v[H^N]]],S^=v[v[S]]):b=S=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):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,n)}softwareDecrypt(e,t,i,n){const{currentIV:r,currentResult:a,remainderData:u}=this;if(n!==Il.cbc||t.byteLength!==16)return ns.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),u&&(e=Jr(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 _U),d.expandKey(t);const f=a;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 EU(this.subtle,t,n)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new TU(this.subtle,new Uint8Array(i),n).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ns.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 a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%AU;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(ns.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const tw=Math.pow(2,17);class kU{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 So({type:$t.NETWORK_ERROR,details:Re.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,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(b=>b[0]==="GAP")){c(sw(e));return}else e.gap=!1;const d=this.loader=r?new r(n):new a(n),f=iw(e);e.loader=d;const p=JE(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:tw};e.stats=d.stats;const v={onSuccess:(b,S,E,L)=>{this.resetLoader(e,d);let N=b.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(N.slice(0,16)),N=N.slice(16)),u({frag:e,part:null,payload:N,networkDetails:L})},onError:(b,S,E,L)=>{this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ss({url:i,data:void 0},b),error:new Error(`HTTP Error ${b.code} ${b.text}`),networkDetails:E,stats:L}))},onAbort:(b,S,E)=>{this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:b}))},onTimeout:(b,S,E)=>{this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:E,stats:b}))}};t&&(v.onProgress=(b,S,E,L)=>t({frag:e,part:null,payload:E,networkDetails:L})),d.load(f,y,v)})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((u,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(sw(e,t));return}const d=this.loader=r?new r(n):new a(n),f=iw(e,t);e.loader=d;const p=JE(n.fragLoadPolicy.default),y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:tw};t.stats=d.stats,d.load(f,y,{onSuccess:(v,b,S,E)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const L={frag:e,part:t,payload:v.data,networkDetails:E};i(L),u(L)},onError:(v,b,S,E)=>{this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ss({url:f.url,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:S,stats:E}))},onAbort:(v,b,S)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:S,stats:v}))},onTimeout:(v,b,S)=>{this.resetLoader(e,d),c(new So({type:$t.NETWORK_ERROR,details:Re.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${y.timeout}ms`),networkDetails:S,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 a=i.loading,u=n.loading;a.start?a.first+=u.first-u.start:(a.start=u.start,a.first=u.first),a.end=u.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function iw(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(kt(n)&&kt(r)){var a;let u=n,c=r;if(s.sn==="initSegment"&&CU((a=s.decryptdata)==null?void 0:a.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 sw(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:$t.MEDIA_ERROR,details:Re.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new So(i)}function CU(s){return s==="AES-128"||s==="AES-256"}class So extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class rL extends ia{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 o1{constructor(e,t,i,n=0,r=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Nm(),this.buffering={audio:Nm(),video:Nm(),audiovideo:Nm()},this.level=e,this.sn=t,this.id=i,this.size=n,this.part=r,this.partial=a}}function Nm(){return{start:0,executeStart:0,executeEnd:0,end:0}}const nw={length:0,start:()=>0,end:()=>0};class fi{static isBuffered(e,t){if(e){const i=fi.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=fi.getBuffered(e);return fi.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 y=r[p-1].end;e[f].start-yy&&(r[p-1].end=e[f].end):r.push(e[f])}else r.push(e[f])}else r=e;let a=0,u,c=t,d=t;for(let f=0;f=p&&t<=y&&(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 aw(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.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 DU(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 LU=/^(\d+)x(\d+)$/,ow=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Bs{constructor(e,t){typeof e=="string"&&(e=Bs.parseAttrList(e,t)),ds(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=LU.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(ow.lastIndex=0;(i=ow.exec(e))!==null;){const a=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(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(c||d))u=Gx(t,u);else if(!d&&!c)switch(a){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":ns.warn(`${e}: attribute ${a} is missing quotes`)}n[a]=u}return n}}const RU="com.apple.hls.interstitial";function IU(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function NU(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class oL{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 a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){ns.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ds(new Bs({}),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"]);kt(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?(ns.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(kt(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===RU}get isValid(){return!!this.id&&!this._badValueForSameId&&kt(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 OU=10;class MU{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?kt(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||OU}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 G0(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):!1}function lw(s,e){return!s&&!e?!0:!s||!e?!1:G0(s,e)}function Rc(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function l1(s){switch(s){case"AES-128":case"AES-256":return Il.cbc;case"AES-256-CTR":return Il.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function u1(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Vx(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function PU(s){const e=Vx(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function lL(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function uL(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",a=n[1];r?(i.splice(-1,1),t=u1(a)):t=PU(a)}}return t}const V0=typeof self<"u"?self:void 0;var Fs={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 i0(s){switch(s){case On.FAIRPLAY:return Fs.FAIRPLAY;case On.PLAYREADY:return Fs.PLAYREADY;case On.WIDEVINE:return Fs.WIDEVINE;case On.CLEARKEY:return Fs.CLEARKEY}}function _v(s){switch(s){case Fs.FAIRPLAY:return On.FAIRPLAY;case Fs.PLAYREADY:return On.PLAYREADY;case Fs.WIDEVINE:return On.WIDEVINE;case Fs.CLEARKEY:return On.CLEARKEY}}function ph(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[Fs.FAIRPLAY,Fs.WIDEVINE,Fs.PLAYREADY,Fs.CLEARKEY].filter(n=>!!e[n]):[];return!i[Fs.WIDEVINE]&&t&&i.push(Fs.WIDEVINE),i}const cL=(function(s){return V0!=null&&(s=V0.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function BU(s,e,t,i){let n;switch(s){case Fs.FAIRPLAY:n=["cenc","sinf"];break;case Fs.WIDEVINE:case Fs.PLAYREADY:n=["cenc"];break;case Fs.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return FU(n,e,t,i)}function FU(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 UU(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function dL(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),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const u=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(u){const c=u1(u).subarray(0,16);return lL(c),c}}return null}let lc={};class Cl{static clearKeyUriToKeyIdMap(){lc={}}static setKeyIdForUri(e,t){lc[e]=t}static addKeyIdForUri(e){const t=Object.keys(lc).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),lc[e]=i,i}constructor(e,t,i,n=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Rc(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(UD(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&G0(e.keyFormatVersions,this.keyFormatVersions)&&lw(e.iv,this.iv)&&lw(e.keyId,this.keyId)}isSupported(){if(this.method){if(Rc(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(Rc(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ns.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=$U(e)),new Cl(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=lc[this.uri];if(r&&!G0(this.keyId,r)&&Cl.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=uL(this.uri);if(i)switch(this.keyFormat){case On.WIDEVINE:if(this.pssh=i,!this.keyId){const r=G6(i.buffer);if(r.length){var n;const a=r[0];this.keyId=(n=a.kids)!=null&&n.length?a.kids[0]:null}}this.keyId||(this.keyId=uw(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=z6(r,null,i),this.keyId=dL(i);break}default:{let r=i.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=jU(t),r||(r=uw(t),r||(r=lc[this.uri])),r&&(this.keyId=r,Cl.setKeyIdForUri(this.uri,r))}return this}}function jU(s){const e=s?.[On.WIDEVINE];return e?e.keyId:null}function uw(s){const e=s?.[On.PLAYREADY];if(e){const t=uL(e.uri);if(t)return dL(t)}return null}function $U(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const cw=/#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,dw=/#EXT-X-MEDIA:(.*)/g,HU=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ev=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),zU=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 $a{static findGroup(e,t){for(let i=0;i0&&r.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(dw.lastIndex=0;(n=dw.exec(e))!==null;){const d=new Bs(n[1],i),f=d.TYPE;if(f){const p=u[f],y=r[f]||[];r[f]=y;const v=d.LANGUAGE,b=d["ASSOC-LANGUAGE"],S=d.CHANNELS,E=d.CHARACTERISTICS,L=d["INSTREAM-ID"],N={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?$a.resolve(d.URI,t):""};if(b&&(N.assocLang=b),S&&(N.channels=S),E&&(N.characteristics=E),L&&(N.instreamId=L),p!=null&&p.length){const R=$a.findGroup(p,N.groupId)||p[0];pw(N,R,"audioCodec"),pw(N,R,"textCodec")}y.push(N)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){var u;const c={url:t},d=new MU(t),f=d.fragments,p=[];let y=null,v=0,b=0,S=0,E=0,L=0,N=null,R=new bv(n,c),H,F,$,M=-1,W=!1,D=null,I;if(Ev.lastIndex=0,d.m3u8=e,d.hasVariableRefs=rw(e),((u=Ev.exec(e))==null?void 0:u[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(H=Ev.exec(e))!==null;){W&&(W=!1,R=new bv(n,c),R.playlistOffset=S,R.setStart(S),R.sn=v,R.cc=E,L&&(R.bitrate=L),R.level=i,y&&(R.initSegment=y,y.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime,y.rawProgramDateTime=null),D&&(R.setByteRange(D),D=null)));const le=H[1];if(le){R.duration=parseFloat(le);const te=(" "+H[2]).slice(1);R.title=te||null,R.tagList.push(te?["INF",le,te]:["INF",le])}else if(H[3]){if(kt(R.duration)){R.playlistOffset=S,R.setStart(S),$&&yw(R,$,d),R.sn=v,R.level=i,R.cc=E,f.push(R);const te=(" "+H[3]).slice(1);R.relurl=Gx(d,te),qx(R,N,p),N=R,S+=R.duration,v++,b=0,W=!0}}else{if(H=H[0].match(zU),!H){ns.warn("No matches on slow regex match for level playlist!");continue}for(F=1;F0&&vw(d,te,H),v=d.startSN=parseInt(V);break;case"SKIP":{d.skippedSegments&&yo(d,te,H);const J=new Bs(V,d),ie=J.decimalInteger("SKIPPED-SEGMENTS");if(kt(ie)){d.skippedSegments+=ie;for(let j=ie;j--;)f.push(null);v+=ie}const oe=J.enumeratedString("RECENTLY-REMOVED-DATERANGES");oe&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(oe.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&yo(d,te,H),d.targetduration=Math.max(parseInt(V),1);break;case"VERSION":d.version!==null&&yo(d,te,H),d.version=parseInt(V);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||yo(d,te,H),d.live=!1;break;case"#":(V||G)&&R.tagList.push(G?[V,G]:[V]);break;case"DISCONTINUITY":E++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([te]);break;case"BITRATE":R.tagList.push([te,V]),L=parseInt(V)*1e3,kt(L)?R.bitrate=L:L=0;break;case"DATERANGE":{const J=new Bs(V,d),ie=new oL(J,d.dateRanges[J.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ie.isValid||d.skippedSegments?d.dateRanges[ie.id]=ie:ns.warn(`Ignoring invalid DATERANGE tag: "${V}"`),R.tagList.push(["EXT-X-DATERANGE",V]);break}case"DEFINE":{{const J=new Bs(V,d);"IMPORT"in J?DU(d,J,a):aw(d,J,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?yo(d,te,H):f.length>0&&vw(d,te,H),d.startCC=E=parseInt(V);break;case"KEY":{const J=hw(V,t,d);if(J.isSupported()){if(J.method==="NONE"){$=void 0;break}$||($={});const ie=$[J.keyFormat];ie!=null&&ie.matches(J)||(ie&&($=ds({},$)),$[J.keyFormat]=J)}else ns.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${V}"`);break}case"START":d.startTimeOffset=fw(V);break;case"MAP":{const J=new Bs(V,d);if(R.duration){const ie=new bv(n,c);gw(ie,J,i,$),y=ie,R.initSegment=y,y.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=y.rawProgramDateTime)}else{const ie=R.byteRangeEndOffset;if(ie){const oe=R.byteRangeStartOffset;D=`${ie-oe}@${oe}`}else D=null;gw(R,J,i,$),y=R,W=!0}y.cc=E;break}case"SERVER-CONTROL":{I&&yo(d,te,H),I=new Bs(V),d.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),d.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&yo(d,te,H);const J=new Bs(V);d.partTarget=J.decimalFloatingPoint("PART-TARGET");break}case"PART":{let J=d.partList;J||(J=d.partList=[]);const ie=b>0?J[J.length-1]:void 0,oe=b++,j=new Bs(V,d),X=new D6(j,R,c,oe,ie);J.push(X),R.duration+=X.duration;break}case"PRELOAD-HINT":{const J=new Bs(V,d);d.preloadHint=J;break}case"RENDITION-REPORT":{const J=new Bs(V,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(J);break}default:ns.warn(`line parsed but not handled: ${H}`);break}}}N&&!N.relurl?(f.pop(),S-=N.duration,d.partList&&(d.fragmentHint=N)):d.partList&&(qx(R,N,p),R.cc=E,d.fragmentHint=R,$&&yw(R,$,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const Q=f.length,K=f[0],q=f[Q-1];if(S+=d.skippedSegments*d.targetduration,S>0&&Q&&q){d.averagetargetduration=S/Q;const le=q.sn;d.endSN=le!=="initSegment"?le:0,d.live||(q.endList=!0),M>0&&(VU(f,M),K&&p.unshift(K))}return d.fragmentHint&&(S+=d.fragmentHint.duration),d.totalduration=S,p.length&&d.dateRangeTagCount&&K&&hL(p,d),d.endCC=E,d}}function hL(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 a;if(((a=s[f])==null?void 0:a.sn)=u||i===0){var a;const c=(((a=t[i+1])==null?void 0:a.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 y=(t[i+1]||f[f.length-1]).sn-s.startSN;for(let v=y;v>d;v--){const b=f[v].programDateTime;if(e>=b&&ei);["video","audio","text"].forEach(i=>{const n=t.filter(r=>s1(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 pw(s,e,t){const i=e[t];i&&(s[t]=i)}function VU(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 qx(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function gw(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 yw(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 yo(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function vw(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function wv(s,e){const t=e.startPTS;if(kt(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 fL(s,e,t,i,n,r,a){i-t<=0&&(a.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(kt(f)){const L=Math.abs(f-t);s&&L>s.totalduration?a.warn(`media timestamps and playlist times differ by ${L}s for level ${e.level} ${s.url}`):kt(e.deltaPTS)?e.deltaPTS=Math.max(L,e.deltaPTS):e.deltaPTS=L,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 y=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 S=v-s.startSN,E=s.fragments;for(E[S]=e,b=S;b>0;b--)wv(E[b],E[b-1]);for(b=S;b=0;f--){const p=n[f].initSegment;if(p){i=p;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r;YU(s,e,(f,p,y,v)=>{if((!e.startCC||e.skippedSegments)&&p.cc!==f.cc){const b=f.cc-p.cc;for(let S=y;S{var p;f&&(!f.initSegment||f.initSegment.relurl===((p=i)==null?void 0:p.relurl))&&(f.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(f=>!f),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let f=e.skippedSegments;f--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=KU(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?fL(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):mL(s,e),a.length&&(e.totalduration=e.edge-a[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 KU(s,e,t){const{dateRanges:i,recentlyRemovedDateranges:n}=e,r=ds({},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 oL(i[c].attr,d);f.isValid?(r[c]=f,d||(f.tagOrder+=u)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ys(i[c].attr)}"`)}),r):i}function WU(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],u=e[n+i];a&&u&&a.index===u.index&&a.fragment.sn===u.fragment.sn?t(a,u):i--}}}function YU(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,a=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[a+d];let p=u[d];if(i&&!p&&f&&(p=e.fragments[d]=f),f&&p){t(f,p,d,u);const y=f.relurl,v=p.relurl;if(y&&XU(y,v)){e.playlistParsingError=xw(`media sequence mismatch ${p.sn}:`,s,e,f,p);return}else if(f.cc!==p.cc){e.playlistParsingError=xw(`discontinuity sequence mismatch (${f.cc}!=${p.cc})`,s,e,f,p);return}}}}function xw(s,e,t,i,n){return new Error(`${s} ${n.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${t.startSN} ${t.m3u8}`)}function mL(s,e,t=!0){const i=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,r=i>=0;let a=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?Tw(s)!==Tw(e):!1}function Tw(s){return s.replace(/\?[^?]*$/,"")}function Dh(s,e){for(let i=0,n=s.length;is.startCC)}function Sw(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function xL(s,e){const t=e.fragments;for(let i=0,n=t.length;i{const{config:a,fragCurrent:u,media:c,mediaBuffer:d,state:f}=this,p=c?c.currentTime:0,y=fi.bufferInfo(d||c,p,a.maxBufferHole),v=!y.len;if(this.log(`Media seeking to ${kt(p)?p.toFixed(3):p}, state: ${f}, ${v?"out of":"in"} buffer`),this.state===rt.ENDED)this.resetLoadingState();else if(u){const b=a.maxFragLookUpTolerance,S=u.start-b,E=u.start+u.duration+b;if(v||Ey.end){const L=p>E;(pb&&(this.lastCurrentTime=p),!this.loadingParts){const S=Math.max(y.end,p),E=this.shouldLoadParts(this.getLevelDetails(),S);E&&(this.log(`LL-Part loading ON after seeking to ${p.toFixed(2)} with buffer @${S.toFixed(2)}`),this.loadingParts=E)}}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===rt.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 kU(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new a1(e.config)}registerListeners(){const{hls:e}=this;e.on(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(z.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===rt.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=rt.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=fi.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>n&&a{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state,u=r.frag;if(this.fragContextChanged(u)){(a===rt.FRAG_LOADING||!this.fragCurrent&&a===rt.PARSING)&&(this.fragmentTracker.removeFragment(u),this.state=rt.IDLE);return}"payload"in r&&(this.log(`Loaded ${u.type} sn: ${u.sn} of ${this.playlistLabel()} ${u.level}`),this.hls.trigger(z.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===rt.STOPPED||this.state===rt.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===fn.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),u=Math.max(e.duration,a?a.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)===fn.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(z.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:a}=i,u=r.decryptdata;if(a&&a.byteLength>0&&u!=null&&u.key&&u.iv&&Rc(u.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),u.key.buffer,u.iv.buffer,l1(u.method)).catch(d=>{throw n.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:r}),d}).then(d=>{const f=self.performance.now();return n.trigger(z.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===rt.STOPPED||this.state===rt.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!==rt.STOPPED&&(this.state=rt.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 a=this.media,u=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(u.message),!a||a.mediaKeys?!1:(this.hls.trigger(z.ERROR,{type:$t.KEY_SYSTEM_ERROR,details:Re.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?JU.toString(fi.getBuffered(i)):"(detached)"})`),tn(e)){var n;if(e.type!==Rt.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(u=>!!a[u])){this.state=rt.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=rt.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),u=new o1(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(u)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let u=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=rt.KEY_LOADING,this.fragCurrent=e,u=this.keyLoader.load(e).then(y=>{if(!this.fragContextChanged(y.frag))return this.hls.trigger(z.KEY_LOADED,y),this.state===rt.KEY_LOADING&&(this.state=rt.IDLE),y}),this.hls.trigger(z.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,a.encryptedFragments,this.startFragRequested),u&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(tn(e)&&(!c||e.sn!==c.sn)){const y=this.shouldLoadParts(t.details,e.end);y!==this.loadingParts&&(this.log(`LL-Part loading ${y?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=y)}if(i=Math.max(e.start,i||0),this.loadingParts&&tn(e)){const y=a.partList;if(y&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const v=this.getNextPart(y,e,i);if(v>-1){const b=y[v];e=this.fragCurrent=b.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${b.index} (${v}/${y.length-1}) of ${this.fragInfo(e,!1,b)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=b.start+b.duration,this.state=rt.FRAG_LOADING;let S;return u?S=u.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,b,t,n)).catch(E=>this.handleFragLoadError(E)):S=this.doFragPartsLoad(e,b,t,n).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(z.FRAG_LOADING,{frag:e,part:b,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):S}else if(!e.url||this.loadedEndOfParts(y,i))return Promise.resolve(null)}}if(tn(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=a.partList)==null?void 0:d.filter(y=>y.loaded).map(y=>`[${y.start}-${y.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),kt(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=rt.FRAG_LOADING;const f=this.config.progressive&&e.type!==Rt.SUBTITLE;let p;return f&&u?p=u.then(y=>!y||this.fragContextChanged(y.frag)?null:this.fragmentLoader.load(e,n)).catch(y=>this.handleFragLoadError(y)):p=Promise.all([this.fragmentLoader.load(e,f?n:void 0),u]).then(([y])=>(!f&&n&&n(y),y)).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(z.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,a)=>{var u;const c=[],d=(u=i.details)==null?void 0:u.partList,f=p=>{this.fragmentLoader.loadPart(e,p,n).then(y=>{c[p.index]=y;const v=y.part;this.hls.trigger(z.FRAG_LOADED,y);const b=bw(i.details,e.sn,p.index+1)||yL(d,e.sn,p.index+1);if(b)f(b);else return r({frag:e,part:v,partsLoaded:c})}).catch(a)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Re.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===$t.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(z.ERROR,t)}else this.hls.trigger(z.ERROR,{type:$t.OTHER_ERROR,details:Re.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==rt.PARSING){!this.fragCurrent&&this.state!==rt.STOPPED&&this.state!==rt.ERROR&&(this.state=rt.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a);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===Rt.SUBTITLE)return!1;const a=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){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:a}=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=a>-1?bw(c,r,a):null,f=d?d.fragment:gL(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!==rt.PARSING)return;const{data1:a,data2:u}=e;let c=a;if(u&&(c=Jr(a,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(z.BUFFER_APPENDING,p),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!fi.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=fi.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),u=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-u>a&&this.flushMainBuffer(u,e.start)}getFwdBufferInfo(e,t){var i;const n=this.getLoadPosition();if(!kt(n))return null;const a=this.lastCurrentTime>n||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,a)}getFwdBufferInfoAtPos(e,t,i,n){const r=fi.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const u=Math.max(Math.min(r.nextStart,a.end)-t,n);return fi.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=Rt.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,a=i[0].start,u=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const p=r.initialLiveManifestSize;if(n=a?y:v)||c.start:e;this.log(`Setting startPosition to ${b} to match start frag at live edge. mainStart: ${y} liveSyncPosition: ${v} frag.start: ${(d=c)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=b}}else e<=a&&(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===fn.OK||i===fn.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,n,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.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=a.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,a}get primaryPrefetch(){if(_w(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(_w(this.config)&&e.type!==Rt.SUBTITLE){const i=this.hls.interstitialsManager,n=i?.bufferingItem;if(n){const a=n.event;if(a){if(a.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 a=r.length;a--;){const u=r[a].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,a=!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=pU(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=iL(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:a,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&&(a=a.concat(c),u=c.sn);let y;if(et-d||(v=this.media)!=null&&v.paused||!this.startFragRequested?0:d;y=ku(r,a,e,S)}else y=a[a.length-1];if(y){const b=y.sn-i.startSN,S=this.fragmentTracker.getState(y);if((S===fn.OK||S===fn.PARTIAL&&y.gap)&&(r=y),r&&y.sn===r.sn&&(!p||f[0].fragment.sn>y.sn||!i.live)&&y.level===r.level){const L=a[b+1];y.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&&tn(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!==rt.FRAG_LOADING_WAITING_RETRY)&&(this.state=rt.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const L=this.getCurrentContext(t.chunkMeta);L&&(t.frag=L.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 a=t.details===Re.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const u=t.errorAction;if(!u){this.state=rt.ERROR;return}const{action:c,flags:d,retryCount:f=0,retryConfig:p}=u,y=!!p,v=y&&c===Rn.RetryRequest,b=y&&!u.resolved&&d===Pr.MoveAllAlternatesMatchingHost,S=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!v&&b&&tn(n)&&!n.endList&&S&&!nL(t))this.resetFragmentErrors(e),this.treatAsGap(n),u.resolved=!0;else if((v||b)&&f=t||i&&!zx(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=rt.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===rt.PARSING||this.state===rt.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 a=!r;return a&&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(),a}return!1}resetFragmentErrors(e){e===Rt.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==rt.STOPPED&&(this.state=rt.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=fi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===rt.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==rt.STOPPED&&(this.state=rt.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 y=n?0:fL(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this);return this.hls.trigger(z.LEVEL_PTS_UPDATED,{details:r,level:i,drift:y,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(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.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=rt.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(z.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Rt.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 _w(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class TL{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=ej(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function ej(s,e){const t=new Uint8Array(e);let i=0;for(let n=0;n0)return s.subarray(t,t+i)}function oj(s,e,t,i){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const v=new Error(`invalid ADTS sampling index:${a}`);s.emit(z.ERROR,z.ERROR,{type:$t.MEDIA_ERROR,details:Re.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[a];let p=a;(u===5||u===29)&&(p-=3);const y=[u<<3|(p&14)>>1,(p&1)<<7|c<<3];return ns.log(`manifest codec:${i}, parsed codec:${d}, channels:${c}, rate:${f} (ADTS object type:${u} sampling index:${a})`),{config:y,samplerate:f,channelCount:c,codec:d,parsedCodec:d,manifestCodec:i}}function _L(s,e){return s[e]===255&&(s[e+1]&246)===240}function EL(s,e){return s[e+1]&1?7:9}function f1(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function lj(s,e){return e+5=s.length)return!1;const i=f1(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||K0(s,n)}return!1}function wL(s,e,t,i,n){if(!s.samplerate){const r=oj(e,t,i,n);if(!r)return;ds(s,r)}}function AL(s){return 1024*9e4/s}function dj(s,e){const t=EL(s,e);if(e+t<=s.length){const i=f1(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function kL(s,e,t,i,n){const r=AL(s.samplerate),a=i+n*r,u=dj(e,t);let c;if(u){const{frameLength:p,headerLength:y}=u,v=y+p,b=Math.max(0,t+v-e.length);b?(c=new Uint8Array(v-y),c.set(e.subarray(t+y,e.length),0)):c=e.subarray(t+y,t+v);const S={unit:c,pts:a};return b||s.samples.push(S),{sample:S,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:a},length:d,missing:-1}}function hj(s,e){return h1(s,e)&&Lp(s,e+6)+10<=s.length-e}function fj(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function kv(s,e=0,t=1/0){return mj(s,e,t,Uint8Array)}function mj(s,e,t,i){const n=pj(s);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=gj(s)?s.byteOffset:0,u=(a+s.byteLength)/r,c=(a+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 pj(s){return s instanceof ArrayBuffer?s:s.buffer}function gj(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function yj(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=jr(kv(s.data,1,i)),r=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;const u=jr(kv(s.data,3+i,a));let c;return n==="-->"?c=jr(kv(s.data,4+i+a)):c=fj(s.data.subarray(4+i+a)),e.mimeType=n,e.pictureType=r,e.description=u,e.data=c,e}function vj(s){if(s.size<2)return;const e=jr(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function xj(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=jr(s.data.subarray(t),!0);t+=i.length+1;const n=jr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=jr(s.data.subarray(1));return{key:s.type,info:"",data:e}}function bj(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=jr(s.data.subarray(t),!0);t+=i.length+1;const n=jr(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=jr(s.data);return{key:s.type,info:"",data:e}}function Tj(s){return s.type==="PRIV"?vj(s):s.type[0]==="W"?bj(s):s.type==="APIC"?yj(s):xj(s)}function Sj(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Lp(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}}const Om=10,_j=10;function CL(s){let e=0;const t=[];for(;h1(s,e);){const i=Lp(s,e+6);s[e+5]>>6&1&&(e+=Om),e+=Om;const n=e+i;for(;e+_j0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Fr.audioId3,duration:Number.POSITIVE_INFINITY});n{if(kt(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};let Mm=null;const Aj=[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],kj=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Cj=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Dj=[0,1,1,4];function LL(s,e,t,i,n){if(t+24>e.length)return;const r=RL(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,u=i+n*a,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 RL(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 a=s[e+2]>>1&1,u=s[e+3]>>6,c=t===3?3-i:i===3?3:4,d=Aj[c*14+n-1]*1e3,p=kj[(t===3?0:t===2?1:2)*3+r],y=u===3?1:2,v=Cj[t][i],b=Dj[i],S=v*8*b,E=Math.floor(v*d/p+a)*b;if(Mm===null){const R=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mm=R?parseInt(R[1]):0}return Mm&&Mm<=87&&i===2&&d>=224e3&&u===0&&(s[e+3]=s[e+3]|128),{sampleRate:p,channelCount:y,frameLength:E,samplesPerFrame:S}}}function g1(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function IL(s,e){return e+1{let t=0,i=5;e+=i;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[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 y=0;p===2?y+=2:(p&1&&p!==1&&(y+=2),p&4&&(y+=2));const v=(e[t+6]<<8|e[t+7])>>12-y&1,S=[2,1,2,3,3,4,4,5][p]+v,E=e[t+5]>>3,L=e[t+5]&7,N=new Uint8Array([r<<6|E<<1|L>>2,(L&3)<<6|p<<3|v<<2|c>>4,c<<4&224]),R=1536/u*9e4,H=i+n*R,F=e.subarray(t,t+f);return s.config=N,s.channelCount=S,s.samplerate=u,s.samples.push({unit:F,pts:H}),f}class Nj extends p1{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=Hh(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&m1(t)!==void 0&&OL(e,i)<=16)return!1;for(let n=e.length;i{const a=$6(r);if(Oj.test(a.schemeIdUri)){const u=ww(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:u,pts:u,type:Fr.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const u=ww(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:u,pts:u,type:Fr.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 ww(s,e){return kt(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class Pj{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new a1(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Il.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),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).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(a,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 a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}class PL{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 a=r,u=[];let c=0,d,f,p,y=-1,v=0;for(r===-1&&(y=0,v=this.getNALuType(t,0),r=0,c=1);c=0){const b={data:t.subarray(y,f),type:v};u.push(b)}else{const b=this.getLastNalUnit(e.samples);b&&(a&&c<=4-a&&b.state&&(b.data=b.data.subarray(0,b.data.byteLength-a)),f>0&&(b.data=Jr(b.data,t.subarray(0,f)),b.state=0))}c=0&&r>=0){const b={data:t.subarray(y,n),type:v,state:r};u.push(b)}if(u.length===0){const b=this.getLastNalUnit(e.samples);b&&(b.data=Jr(b.data,t))}return e.naluState=r,u}}class Lh{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&&ns.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 Bj extends PL{parsePES(e,t,i,n){const r=this.parseNALu(e,i.data,n);let a=this.VideoSample,u,c=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(d=>{var f,p;switch(d.type){case 1:{let S=!1;u=!0;const E=d.data;if(c&&E.length>4){const L=this.readSliceType(E);(L===2||L===4||L===7||L===9)&&(S=!0)}if(S){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=S;break}case 5:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:{u=!0,i1(d.data,1,i.pts,t.samples);break}case 7:{var v,b;u=!0,c=!0;const S=d.data,E=this.readSPS(S);if(!e.sps||e.width!==E.width||e.height!==E.height||((v=e.pixelRatio)==null?void 0:v[0])!==E.pixelRatio[0]||((b=e.pixelRatio)==null?void 0:b[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[S];const L=S.subarray(1,4);let N="avc1.";for(let R=0;R<3;R++){let H=L[R].toString(16);H.length<2&&(H="0"+H),N+=H}e.codec=N}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(p=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Lh(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,n=8,r;for(let a=0;a{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:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,u=!0;break;case 16:case 17:case 18:case 21:if(u=!0,c){var y;(y=a)!=null&&y.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:u=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:u=!0,i1(d.data,2,i.pts,t.samples);break;case 32:u=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ds(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),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.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=a)!=null&&p.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:u=!1;break}a&&u&&a.units.push(d)}),n&&a&&(this.pushAccessUnit(a,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 Lh(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 Lh(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(),a=t.readBits(5),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),b=t.readUByte(),S=t.readUByte(),E=t.readUByte(),L=t.readUByte(),N=[],R=[];for(let lt=0;lt0)for(let lt=i;lt<8;lt++)t.readBits(2);for(let lt=0;lt1&&t.readEG();for(let Et=0;Et0&&ye<16?(X=mt[ye-1],se=st[ye-1]):ye===255&&(X=t.readBits(16),se=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(),Ve=t.readBoolean(),Ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(pe=t.readBits(32),de=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const st=t.readBoolean(),Xe=t.readBoolean();let xt=!1;(st||Xe)&&(xt=t.readBoolean(),xt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),xt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ft=0;ft<=i;ft++){fe=t.readBoolean();const Pt=fe||t.readBoolean();let qt=!1;Pt?t.readEG():qt=t.readBoolean();const It=qt?1:t.readUEG()+1;if(st)for(let ni=0;ni>lt&1)<<31-lt)>>>0;let Ge=dt.toString(16);return a===1&&Ge==="2"&&(Ge="6"),{codecString:`hvc1.${Fe}${a}.${Ge}.${r?"H":"L"}${L}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[u,c,d,f],general_constraint_indicator_flags:[p,y,v,b,S,E],general_level_idc:L,bit_depth:K+8,bit_depth_luma_minus8:K,bit_depth_chroma_minus8:q,min_spatial_segmentation_idc:j,chroma_format_idc:H,frame_rate:{fixed:fe,fps:de/pe}},width:Je,height:Pe,pixelRatio:[X,se]}}readPPS(e){const t=new Lh(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 a=1;return r&&n?a=0:r?a=3:n&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const vn=188;class _l{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=_l.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(vn*5,t-vn)+1,n=0;for(;n1&&(a===0&&u>2||c+vn>i))return a}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:HD[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=_l.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=_l.createTrack("audio",n),this._id3Track=_l.createTrack("id3"),this._txtTrack=_l.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 a=this._videoTrack,u=this._audioTrack,c=this._id3Track,d=this._txtTrack;let f=a.pid,p=a.pesData,y=u.pid,v=c.pid,b=u.pesData,S=c.pesData,E=null,L=this.pmtParsed,N=this._pmtId,R=e.length;if(this.remainderData&&(e=Jr(this.remainderData,e),R=e.length,this.remainderData=null),R>4;let Q;if(I>1){if(Q=M+5+e[M+4],Q===M+vn)continue}else Q=M+4;switch(D){case f:W&&(p&&(r=uc(p,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,r,!1)),p={data:[],size:0}),p&&(p.data.push(e.subarray(Q,M+vn)),p.size+=M+vn-Q);break;case y:if(W){if(b&&(r=uc(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(Q,M+vn)),b.size+=M+vn-Q);break;case v:W&&(S&&(r=uc(S,this.logger))&&this.parseID3PES(c,r),S={data:[],size:0}),S&&(S.data.push(e.subarray(Q,M+vn)),S.size+=M+vn-Q);break;case 0:W&&(Q+=e[Q]+1),N=this._pmtId=Uj(e,Q);break;case N:{W&&(Q+=e[Q]+1);const K=jj(e,Q,this.typeSupported,i,this.observer,this.logger);f=K.videoPid,f>0&&(a.pid=f,a.segmentCodec=K.segmentVideoCodec),y=K.audioPid,y>0&&(u.pid=y,u.segmentCodec=K.segmentAudioCodec),v=K.id3Pid,v>0&&(c.pid=v),E!==null&&!L&&(this.logger.warn(`MPEG-TS PMT found at ${M} after unknown PID '${E}'. Backtracking to sync byte @${H} to parse all TS packets.`),E=null,M=H-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=D;break}}else F++;F>0&&Yx(this.observer,new Error(`Found ${F} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=p,u.pesData=b,c.pesData=S;const $={audioTrack:u,videoTrack:a,id3Track:c,textTrack:d};return n&&this.extractRemainingSamples($),$}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,a=i.pesData,u=t.pesData,c=n.pesData;let d;if(a&&(d=uc(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,r,d,!0),i.pesData=null)):i.pesData=a,u&&(d=uc(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=uc(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 Pj(this.observer,this.config,t);return this.decrypt(n,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Bj:e==="hevc"&&(this.videoParser=new Fj))}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,y=n.sample.unit.byteLength;if(p===-1)r=Jr(n.sample.unit,r);else{const v=y-p;n.sample.unit.set(r.subarray(0,p),v),e.samples.push(n.sample),i=n.missing}}let a,u;for(a=i,u=r.length;a0;)u+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=ds({},t,{type:this._videoTrack?Fr.emsg:Fr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Wx(s,e){return((s[e+1]&31)<<8)+s[e+2]}function Uj(s,e){return(s[e+10]&31)<<8|s[e+11]}function jj(s,e,t,i,n,r){const a={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 y=e+5,v=p;for(;v>2;){s[y]===106&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=f,a.segmentAudioCodec="ac3"));const S=s[y+1]+2;y+=S,v-=S}}break;case 194:case 135:return Yx(n,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=f,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=p+5}return a}function Yx(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(z.ERROR,z.ERROR,{type:$t.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Cv(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function uc(s,e){let t=0,i,n,r,a,u;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Jr(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&&(a=(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,a-u>60*9e4&&(e.warn(`${Math.round((a-u)/9e4)}s delta between PTS and DTS, align them`),a=u)):u=a),r=i[8];let p=r+9;if(s.size<=p)return null;s.size-=p;const y=new Uint8Array(s.size);for(let v=0,b=c.length;vS){p-=S;continue}else i=i.subarray(p),S-=p,p=0;y.set(i,t),t+=S}return n&&(n-=r+3),{data:y,pts:a,dts:u,len:n}}return null}class $j{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 gl=Math.pow(2,32)-1;class De{static init(){De.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 De.types)De.types.hasOwnProperty(e)&&(De.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]);De.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]);De.STTS=De.STSC=De.STCO=r,De.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),De.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),De.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),De.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),u=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);De.FTYP=De.box(De.types.ftyp,a,c,a,u),De.DINF=De.box(De.types.dinf,De.box(De.types.dref,n))}static box(e,...t){let i=8,n=t.length;const r=n;for(;n--;)i+=t[n].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.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 De.box(De.types.mdia,De.mdhd(e.timescale||0,e.duration||0),De.hdlr(e.type),De.minf(e))}static mfhd(e){return De.box(De.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"?De.box(De.types.minf,De.box(De.types.smhd,De.SMHD),De.DINF,De.stbl(e)):De.box(De.types.minf,De.box(De.types.vmhd,De.VMHD),De.DINF,De.stbl(e))}static moof(e,t,i){return De.box(De.types.moof,De.mfhd(e),De.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=De.trak(e[t]);return De.box.apply(null,[De.types.moov,De.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(De.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=De.trex(e[t]);return De.box.apply(null,[De.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(gl+1)),n=Math.floor(t%(gl+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 De.box(De.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(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const u=De.box(De.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 De.box(De.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,De.box(De.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),De.box(De.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 De.box(De.types.mp4a,De.audioStsd(e),De.box(De.types.esds,De.esds(e)))}static mp3(e){return De.box(De.types[".mp3"],De.audioStsd(e))}static ac3(e){return De.box(De.types["ac-3"],De.audioStsd(e),De.box(De.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return De.box(De.types.stsd,De.STSD,De.mp4a(e));if(t==="ac3"&&e.config)return De.box(De.types.stsd,De.STSD,De.ac3(e));if(t==="mp3"&&e.codec==="mp3")return De.box(De.types.stsd,De.STSD,De.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return De.box(De.types.stsd,De.STSD,De.avc1(e));if(t==="hevc"&&e.vps)return De.box(De.types.stsd,De.STSD,De.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,a=Math.floor(i/(gl+1)),u=Math.floor(i%(gl+1));return De.box(De.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,a>>24,a>>16&255,a>>8&255,a&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=De.sdtp(e),n=e.id,r=Math.floor(t/(gl+1)),a=Math.floor(t%(gl+1));return De.box(De.types.traf,De.box(De.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),De.box(De.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),De.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,De.box(De.types.trak,De.tkhd(e),De.mdia(e))}static trex(e){const t=e.id;return De.box(De.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,a=new Uint8Array(r);let u,c,d,f,p,y;for(t+=8+r,a.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,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*u);return De.box(De.types.trun,a)}static initSegment(e){De.types||De.init();const t=De.moov(e);return Jr(De.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 a=r.length;for(let b=0;b>8,i[b][S].length&255]),a),a+=2,u.set(i[b][S],a),a+=i[b][S].length}const d=De.box(De.types.hvcC,u),f=e.width,p=e.height,y=e.pixelRatio[0],v=e.pixelRatio[1];return De.box(De.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,De.box(De.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),De.box(De.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,v>>24,v>>16&255,v>>8&255,v&255])))}}De.types=void 0;De.HDLR_TYPES=void 0;De.STTS=void 0;De.STSC=void 0;De.STCO=void 0;De.STSZ=void 0;De.VMHD=void 0;De.SMHD=void 0;De.STSD=void 0;De.FTYP=void 0;De.DINF=void 0;const BL=9e4;function y1(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function Hj(s,e,t=1,i=!1){return y1(s,e,1/t,i)}function rh(s,e=!1){return y1(s,1e3,1/BL,e)}function zj(s,e=1){return y1(s,BL,1/e)}function Aw(s){const{baseTime:e,timescale:t,trackId:i}=s;return`${e/t} (${e}/${t}) trackId: ${i}`}const Gj=10*1e3,Vj=1024,qj=1152,Kj=1536;let cc=null,Dv=null;function kw(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 s0 extends ia{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,cc===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);cc=a?parseInt(a[1]):0}if(Dv===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Dv=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&&Aw(t)} > ${e&&Aw(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,a)=>{let u=a.pts,c=u-r;return c<-4294967296&&(t=!0,u=Br(u,i),c=u-r),c>0?r:u},i);return t&&this.debug("PTS rollover detected"),n}remux(e,t,i,n,r,a,u,c){let d,f,p,y,v,b,S=r,E=r;const L=e.pid>-1,N=t.pid>-1,R=t.samples.length,H=e.samples.length>0,F=u&&R>0||R>1;if((!L||H)&&(!N||F)||this.ISGenerated||u){if(this.ISGenerated){var M,W,D,I;const le=this.videoTrackConfig;(le&&(t.width!==le.width||t.height!==le.height||((M=t.pixelRatio)==null?void 0:M[0])!==((W=le.pixelRatio)==null?void 0:W[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((I=le.pixelRatio)==null?void 0:I[1]))||!le&&F||this.nextAudioTs===null&&H)&&this.resetInitSegment()}this.ISGenerated||(p=this.generateIS(e,t,r,a));const Q=this.isVideoContiguous;let K=-1,q;if(F&&(K=Wj(t.samples),!Q&&this.config.forceKeyFrameOnDiscontinuity))if(b=!0,K>0){this.warn(`Dropped ${K} out of ${R} video samples due to a missing keyframe`);const le=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(K),t.dropped+=K,E+=(t.samples[0].pts-le)/t.inputTimeScale,q=E}else K===-1&&(this.warn(`No keyframe found out of ${R} video samples`),b=!1);if(this.ISGenerated){if(H&&F){const le=this.getVideoStartPts(t.samples),V=(Br(e.samples[0].pts,le)-le)/t.inputTimeScale;S+=Math.max(0,V),E+=Math.max(0,-V)}if(H){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),p=this.generateIS(e,t,r,a)),f=this.remuxAudio(e,S,this.isAudioContiguous,a,N||F||c===Rt.AUDIO?E:void 0),F){const le=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),p=this.generateIS(e,t,r,a)),d=this.remuxVideo(t,E,Q,le)}}else F&&(d=this.remuxVideo(t,E,Q,0));d&&(d.firstKeyFrame=K,d.independent=K!==-1,d.firstKeyFramePTS=q)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(v=FL(i,r,this._initPTS,this._initDTS)),n.samples.length&&(y=UL(n,r,this._initPTS))),{audio:f,video:d,initSegment:p,independent:b,text:y,id3:v}}computeInitPts(e,t,i,n){const r=Math.round(i*t);let a=Br(e,r);if(a0?j-1:j].dts&&(N=!0)}N&&a.sort(function(j,X){const se=j.dts-X.dts,fe=j.pts-X.pts;return se||fe}),b=a[0].dts,S=a[a.length-1].dts;const H=S-b,F=H?Math.round(H/(c-1)):v||e.inputTimeScale/30;if(i){const j=b-R,X=j>F,se=j<-1;if((X||se)&&(X?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rh(j,!0)} ms (${j}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${rh(-j,!0)} ms (${j}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!se||R>=a[0].pts||cc)){b=R;const fe=a[0].pts-j;if(X)a[0].dts=b,a[0].pts=fe;else{let pe=!0;for(let de=0;defe&&pe);de++){const Ve=a[de].pts;if(a[de].dts-=j,a[de].pts-=j,de0?X.dts-a[j-1].dts:F;if(pe=j>0?X.pts-a[j-1].pts:F,Ve.stretchShortVideoTrack&&this.nextAudioTs!==null){const Je=Math.floor(Ve.maxBufferHole*r),Pe=(n?E+n*r:this.nextAudioTs+f)-X.pts;Pe>Je?(v=Pe-Ze,v<0?v=Ze:K=!0,this.log(`It is approximately ${Pe/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=Ze}else v=Ze}const de=Math.round(X.pts-X.dts);q=Math.min(q,v),te=Math.max(te,v),le=Math.min(le,pe),V=Math.max(V,pe),u.push(kw(X.key,v,fe,de))}if(u.length){if(cc){if(cc<70){const j=u[0].flags;j.dependsOn=2,j.isNonSync=0}}else if(Dv&&V-le0&&(n&&Math.abs(R-(L+N))<9e3||Math.abs(Br(S[0].pts,R)-(L+N))<20*f),S.forEach(function(V){V.pts=Br(V.pts,R)}),!i||L<0){const V=S.length;if(S=S.filter(G=>G.pts>=0),V!==S.length&&this.warn(`Removed ${S.length-V} of ${V} samples (initPTS ${N} / ${a})`),!S.length)return;r===0?L=0:n&&!b?L=Math.max(0,R-N):L=S[0].pts-N}if(e.segmentCodec==="aac"){const V=this.config.maxAudioFramesDrift;for(let G=0,J=L+N;G=V*f&&X0){M+=E;try{$=new Uint8Array(M)}catch(X){this.observer.emit(z.ERROR,z.ERROR,{type:$t.MUX_ERROR,details:Re.REMUX_ALLOC_ERROR,fatal:!1,error:X,bytes:M,reason:`fail allocating audio mdat ${M}`});return}y||(new DataView($.buffer).setUint32(0,M),$.set(De.types.mdat,4))}else return;$.set(ie,E);const j=ie.byteLength;E+=j,v.push(kw(!0,d,j,0)),F=oe}const D=v.length;if(!D)return;const I=v[v.length-1];L=F-N,this.nextAudioTs=L+c*I.duration;const Q=y?new Uint8Array(0):De.moof(e.sequenceNumber++,H/c,ds({},e,{samples:v}));e.samples=[];const K=(H-N)/a,q=this.nextAudioTs/a,te={data1:Q,data2:$,startPTS:K,endPTS:q,startDTS:K,endDTS:q,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,te}}function Br(s,e){let t;if(e===null)return s;for(e4294967296;)s+=t;return s}function Wj(s){for(let e=0;ea.pts-u.pts);const r=s.samples;return s.samples=[],{samples:r}}class Yj extends ia{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:a}=this.initData=VD(e);if(t)P6(e,t);else{const c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(i=Cw(r,ps.AUDIO,this)),a&&(n=Cw(a,ps.VIDEO,this));const u={};r&&a?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?u.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?u.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}remux(e,t,i,n,r,a){var u,c;let{initPTS:d,lastEndTime:f}=this;const p={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};kt(f)||(f=this.lastEndTime=r||0);const y=t.samples;if(!y.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(y),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 S=F6(y,b,this),E=b.audio?S[b.audio.id]:null,L=b.video?S[b.video.id]:null,N=Pm(L,1/0),R=Pm(E,1/0),H=Pm(L,0,!0),F=Pm(E,0,!0);let $=r,M=0;const W=E&&(!L||!d&&R0?this.lastEndTime=Q:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K=!!b.audio,q=!!b.video;let le="";K&&(le+="audio"),q&&(le+="video");const te=(b.audio?b.audio.encrypted:!1)||(b.video?b.video.encrypted:!1),V={data1:y,startPTS:I,startDTS:I,endPTS:Q,endDTS:Q,type:le,hasAudio:K,hasVideo:q,nb:1,dropped:0,encrypted:te};p.audio=K&&!q?V:void 0,p.video=q?V:void 0;const G=L?.sampleCount;if(G){const J=L.keyFrameIndex,ie=J!==-1;V.nb=G,V.dropped=J===0||this.isVideoContiguous?0:ie?J:G,V.independent=ie,V.firstKeyFrame=J,ie&&L.keyFrameStart&&(V.firstKeyFramePTS=(L.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(p.independent=ie),this.isVideoContiguous||(this.isVideoContiguous=ie),V.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${J}/${G} dropped: ${V.dropped} start: ${V.firstKeyFramePTS||"NA"}`)}return p.initSegment=v,p.id3=FL(i,r,d,d),n.samples.length&&(p.text=UL(n,r,d)),p}}function Pm(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 Cw(s,e,t){const i=s.codec;return i&&i.length>4?i:e===ps.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?U0(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 _o;try{_o=self.performance.now.bind(self.performance)}catch{_o=Date.now}const n0=[{demux:Mj,remux:Yj},{demux:_l,remux:s0},{demux:Rj,remux:s0},{demux:Nj,remux:s0}];n0.splice(2,0,{demux:Ij,remux:s0});class Dw{constructor(e,t,i,n,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=_o();let a=new Uint8Array(e);const{currentTransmuxState:u,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:d,discontinuity:f,trackSwitch:p,accurateTimeOffset:y,timeOffset:v,initSegmentChange:b}=n||u,{audioCodec:S,videoCodec:E,defaultInitPts:L,duration:N,initSegmentData:R}=c,H=Qj(a,t);if(H&&Rc(H.method)){const W=this.getDecrypter(),D=l1(H.method);if(W.isSync()){let I=W.softwareDecrypt(a,H.key.buffer,H.iv.buffer,D);if(i.part>-1){const K=W.flush();I=K&&K.buffer}if(!I)return r.executeEnd=_o(),Lv(i);a=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=W.webCryptoDecrypt(a,H.key.buffer,H.iv.buffer,D).then(I=>{const Q=this.push(I,null,i);return this.decryptionPromise=null,Q}),this.decryptionPromise}const F=this.needsProbing(f,p);if(F){const W=this.configureTransmuxer(a);if(W)return this.logger.warn(`[transmuxer] ${W.message}`),this.observer.emit(z.ERROR,z.ERROR,{type:$t.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!1,error:W,reason:W.message}),r.executeEnd=_o(),Lv(i)}(f||p||b||F)&&this.resetInitSegment(R,S,E,N,t),(f||b||F)&&this.resetInitialTimestamp(L),d||this.resetContiguity();const $=this.transmux(a,H,v,y,i);this.asyncResult=zh($);const M=this.currentTransmuxState;return M.contiguous=!0,M.discontinuity=!1,M.trackSwitch=!1,r.executeEnd=_o(),$}flush(e){const t=e.transmuxing;t.executeStart=_o();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:u}=n;if(i){const p=i.flush();p&&a.push(this.push(p.buffer,null,e))}const{demuxer:c,remuxer:d}=this;if(!c||!d){t.executeEnd=_o();const p=[Lv(e)];return this.asyncResult?Promise.resolve(p):p}const f=c.flush(u);return zh(f)?(this.asyncResult=!0,f.then(p=>(this.flushRemux(a,p,e),a))):(this.flushRemux(a,f,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,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===Rt.MAIN?"level":"track"} ${i.level}`);const f=this.remuxer.remux(n,r,a,u,d,c,!0,this.id);e.push({remuxResult:f,chunkMeta:i}),i.transmuxing.executeEnd=_o()}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:a,remuxer:u}=this;!a||!u||(a.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 a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:u,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,u,c,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n}=this;let r;for(let p=0,y=n0.length;p0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Lv=s=>({remuxResult:{},chunkMeta:s});function zh(s){return"then"in s&&s.then instanceof Function}class Zj{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 Jj{constructor(e,t,i,n,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=a}}let Lw=0;class jL{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Lw++,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 y=(p=this.workerContext)==null?void 0:p.objectURL;y&&self.URL.revokeObjectURL(y);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(z.ERROR,{type:$t.OTHER_ERROR,details:Re.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 a=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===z.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new d1,this.observer.on(z.FRAG_DECRYPTED,a),this.observer.on(z.ERROR,a);const u=VE(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||sj()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=rj(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=nj());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:ys(r)})}catch(f){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,f),this.terminateWorker(),this.error=null,this.transmuxer=new Dw(this.observer,u,r,"",t,e.logger)}return}}this.transmuxer=new Dw(this.observer,u,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Lw++;const t=this.hls.config,i=VE(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ys(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),aj(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,a,u,c,d,f){var p,y;d.transmuxing.start=self.performance.now();const{instanceNo:v,transmuxer:b}=this,S=a?a.start:r.start,E=r.decryptdata,L=this.frag,N=!(L&&r.cc===L.cc),R=!(L&&d.level===L.level),H=L?d.sn-L.sn:-1,F=this.part?d.part-this.part.index:-1,$=H===0&&d.id>1&&d.id===L?.stats.chunkCount,M=!R&&(H===1||H===0&&(F===1||$&&F<=0)),W=self.performance.now();(R||H||r.stats.parsing.start===0)&&(r.stats.parsing.start=W),a&&(F||!M)&&(a.stats.parsing.start=W);const D=!(L&&((p=r.initSegment)==null?void 0:p.url)===((y=L.initSegment)==null?void 0:y.url)),I=new Jj(N,M,c,R,S,D);if(!M||N||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===Rt.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${N} trackSwitch: ${R} contiguous: ${M} accurateTimeOffset: ${c} timeOffset: ${S} initSegmentChange: ${D}`);const Q=new Zj(i,n,t,u,f);this.configureTransmuxer(Q)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:v,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:I},e instanceof ArrayBuffer?[e]:[]);else if(b){const Q=b.push(e,E,d,I);zh(Q)?Q.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(Q)}}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);zh(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(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.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 Rw=100;class e7 extends c1{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Rt.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(z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(z.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(z.BUFFER_RESET,this.onBufferReset,this),e.on(z.BUFFER_CREATED,this.onBufferCreated,this),e.on(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(z.FRAG_LOADING,this.onFragLoading,this),e.on(z.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(z.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(z.BUFFER_RESET,this.onBufferReset,this),e.off(z.BUFFER_CREATED,this.onBufferCreated,this),e.off(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(z.FRAG_LOADING,this.onFragLoading,this),e.off(z.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){if(i===Rt.MAIN){const u=t.cc,c=this.fragCurrent;if(this.initPTS[u]={baseTime:n,timescale:r,trackId:a},this.log(`InitPTS for cc: ${u} found from main: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===rt.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===rt.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,a=this.getLevelDetails(),u=this.getLoadPosition(),c=iL(a,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===rt.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=rt.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Rw),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=rt.IDLE):this.state=rt.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case rt.IDLE:this.doTickIdle();break;case rt.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=rt.WAITING_INIT_PTS}break}case rt.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case rt.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:n,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=rt.FRAG_LOADING;const u=n.flush().buffer,c={frag:t,part:i,payload:u,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=rt.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,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const u=i[r],c=u.details;if(!c||this.waitForLive(u)||this.waitForCdnTuneIn(c)){this.state=rt.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,ps.AUDIO,Rt.AUDIO));const f=this.getFwdBufferInfo(d,Rt.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,c)){t.trigger(z.BUFFER_EOS,{type:"audio"}),this.state=rt.ENDED;return}const p=f.len,y=t.maxBufferLength,v=c.fragments,b=v[0].start,S=this.getLoadPosition(),E=this.flushing?S:f.end;if(this.switchingTrack&&n){const R=S;c.PTSKnown&&Rb||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=b+.05)}if(p>=y&&!this.switchingTrack&&EN.end){const H=this.fragmentTracker.getFragAtPos(E,Rt.MAIN);H&&H.end>N.end&&(N=H,this.mainFragLoading={frag:H,targetBufferTime:null})}if(L.start>N.end)return}this.loadFragment(L,u,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new jh(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!==rt.STOPPED&&(this.setInterval(Rw),this.state=rt.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(z.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:n}=this,{details:r,id:a,groupId:u,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${u}"`);return}const d=this.mainDetails;if(!d||r.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==rt.STOPPED&&(this.state=rt.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${u}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const f=n[a];let p=0;if(r.live||(i=f.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(f.details){var y;p=this.alignPlaylists(r,f.details,(y=this.levelLastLoaded)==null?void 0:y.details)}r.alignedSliding||(bL(r,d),r.alignedSliding||q0(r,d),p=r.fragmentStart)}f.details=r,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(d,p),this.hls.trigger(z.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===rt.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=rt.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:n,payload:r}=e,{config:a,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=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let y=this.transmuxer;y||(y=this.transmuxer=new jL(this.hls,Rt.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 E=n?n.index:-1,L=E!==-1,N=new o1(i.level,i.sn,i.stats.chunkCount,r.byteLength,E,L);y.push(r,b,p,"",i,n,f.totalduration,!1,N,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:S}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new TL,complete:!1};S.push(new Uint8Array(r)),this.state!==rt.STOPPED&&(this.state=rt.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===Rt.MAIN&&tn(t.frag)&&(this.mainFragLoading=t,this.state===rt.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==Rt.AUDIO){!this.audioOnly&&i.type===Rt.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(tn(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(z.AUDIO_TRACK_SWITCHED,ss({},r)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=rt.ERROR;return}switch(t.details){case Re.FRAG_GAP:case Re.FRAG_PARSING_ERROR:case Re.FRAG_DECRYPT_ERROR:case Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Rt.AUDIO,t);break;case Re.AUDIO_TRACK_LOAD_ERROR:case Re.AUDIO_TRACK_LOAD_TIMEOUT:case Re.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===rt.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Ci.AUDIO_TRACK&&(this.state=rt.IDLE);break;case Re.BUFFER_ADD_CODEC_ERROR:case Re.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case Re.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Re.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ps.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ps.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===rt.ENDED&&(this.state=rt.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,Rt.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,u=this.getCurrentContext(a);if(!u){this.resetWhenMissingContext(a);return}const{frag:c,part:d,level:f}=u,{details:p}=f,{audio:y,text:v,id3:b,initSegment:S}=r;if(this.fragContextChanged(c)||!p){this.fragmentTracker.removeFragment(c);return}if(this.state=rt.PARSING,this.switchingTrack&&y&&this.completeAudioSwitch(this.switchingTrack),S!=null&&S.tracks){const E=c.initSegment||c;if(this.unhandledEncryptionError(S,c))return;this._bufferInitSegment(f,S.tracks,E,a),n.trigger(z.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:S.tracks})}if(y){const{startPTS:E,endPTS:L,startDTS:N,endDTS:R}=y;d&&(d.elementaryStreams[ps.AUDIO]={startPTS:E,endPTS:L,startDTS:N,endDTS:R}),c.setElementaryStreamInfo(ps.AUDIO,E,L,N,R),this.bufferFragmentData(y,c,d,a)}if(b!=null&&(t=b.samples)!=null&&t.length){const E=ds({id:i,frag:c,details:p},b);n.trigger(z.FRAG_PARSING_METADATA,E)}if(v){const E=ds({id:i,frag:c,details:p},v);n.trigger(z.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,i,n){if(this.state!==rt.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=Rt.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(z.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(z.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===fn.NOT_LOADED||n===fn.PARTIAL){var r;if(!tn(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=rt.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&q0(t.details,a)}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:a,channels:u}=this.bufferedTrack;Tu({name:t,lang:i,assocLang:n,characteristics:r,audioCodec:a,channels:u},e,cu)||($0(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(z.AUDIO_TRACK_SWITCHED,ss({},e))}}class v1 extends ia{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 a=0;a=0&&f>t.partTarget&&(c+=1)}const d=i&&qE(i);return new KE(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,a=self.performance.now(),u=r.loading.first?Math.max(0,a-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){qU(i,n,this);const N=n.playlistParsingError;if(N){this.warn(N);const R=this.hls;if(!R.config.ignorePlaylistParsingErrors){var d;const{networkDetails:H}=t;R.trigger(z.ERROR,{type:$t.NETWORK_ERROR,details:Re.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:N,reason:N.message,level:t.level||void 0,parent:(d=n.fragments[0])==null?void 0:d.type,networkDetails:H,stats:r});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=r.loading.start);const p=this.hls.mainForwardBufferInfo,y=p?p.end-p.len:0,v=(n.edge-y)*1e3,b=pL(n,v);if(n.requestScheduled+b0){if(D>n.targetduration*3)this.log(`Playlist last advanced ${W.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,L=void 0;else if(i!=null&&i.tuneInGoal&&D-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${I} with playlist age: ${n.age}`),I=0;else{const Q=Math.floor(I/n.targetduration);if(E+=Q,L!==void 0){const K=Math.round(I%n.targetduration/n.partTarget);L+=K}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${W.toFixed(2)}s goal: ${I} skip sn ${Q} to part ${L}`)}n.tuneInGoal=I}if(S=this.getDeliveryDirectives(n,t.deliveryDirectives,E,L),N||!M){n.requestScheduled=a,this.loadingPlaylist(f,S);return}}else(n.canBlockReload||n.canSkipUntil)&&(S=this.getDeliveryDirectives(n,t.deliveryDirectives,E,L));S&&E!==void 0&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(b-u*2,b/2)),this.scheduleLoading(f,S,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(),a=n.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const u=a-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=qE(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=t0.No),new KE(i,n,r)}checkRetry(e){const t=e.details,i=H0(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:u}=n||{},c=!!n&&!!u&&(r===Rn.RetryRequest||!n.resolved&&r===Rn.SendAlternateToPenaltyBox);if(c){var d;if(a>=u.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=r1(u,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${a+1}/${u.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function $L(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[n]!==e[n])}function Xx(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class t7 extends v1{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(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.LEVEL_LOADING,this.onLevelLoading,this),e.on(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.LEVEL_LOADING,this.onLevelLoading,this),e.off(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(z.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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Audio track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.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(y=>!i||i.indexOf(y.groupId)!==-1);if(u.length)this.selectDefaultTrack&&!u.some(y=>y.default)&&(this.selectDefaultTrack=!1),u.forEach((y,v)=>{y.id=v});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=u;const c=this.hls.config.audioPreference;if(!r&&c){const y=ja(c,u,cu);if(y>-1)r=u[y];else{const v=ja(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(z.AUDIO_TRACKS_UPDATED,f);const p=this.trackId;if(d!==-1&&p===-1)this.setAudioTrack(d);else if(u.length&&p===-1){var a;const y=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${u.length}`);this.warn(y.message),this.hls.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:y})}}}onError(e,t){t.fatal||!t.context||t.context.type===Ci.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&&Tu(e,n,cu))return n;const r=ja(e,this.tracksInGroup,cu);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const u=fU(e,t.levels,i,a,cu);if(u===-1)return null;t.nextLoadLevel=u}if(e.channels||e.audioCodec){const a=ja(e,i);if(a>-1)return i[a]}}}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(z.AUDIO_TRACK_SWITCHING,ss({},n)),r))return;const a=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(a)}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 a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.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 Iw=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,HL="HlsJsTrackRemovedError";class s7 extends Error{constructor(e){super(e),this.name=HL}}class n7 extends ia{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(z.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=A6(Rl(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(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.BUFFER_RESET,this.onBufferReset,this),e.on(z.BUFFER_APPENDING,this.onBufferAppending,this),e.on(z.BUFFER_CODECS,this.onBufferCodecs,this),e.on(z.BUFFER_EOS,this.onBufferEos,this),e.on(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(z.FRAG_PARSED,this.onFragParsed,this),e.on(z.FRAG_CHANGED,this.onFragChanged,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.BUFFER_RESET,this.onBufferReset,this),e.off(z.BUFFER_APPENDING,this.onBufferAppending,this),e.off(z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(z.BUFFER_EOS,this.onBufferEos,this),e.off(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(z.FRAG_PARSED,this.onFragParsed,this),e.off(z.FRAG_CHANGED,this.onFragChanged,this),e.off(z.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 a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?ds(i,n.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=ds({},this.tracks[a]),this.removeBuffer(a)),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=Rl(this.appendSource);if(n){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const u=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const c=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||c&&a instanceof c,Nw(i),r7(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,a=r?r.length:0,u=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${ys(i,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${ys(n,(c,d)=>c==="initSegment"?void 0:d)}}`),!FD(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(z.MEDIA_DETACHING,{}),this.onMediaAttaching(z.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 y=this.fragmentTracker,v=f.id;if(y.hasFragments(v)||y.hasParts(v)){const E=fi.getBuffered(p);y.detectEvictedFragments(d,E,v,null,!0)}const b=Rv(d),S=[d,p];this.sourceBuffers[b]=S,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:a}=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||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&Nw(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(z.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[Rv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new i7(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 a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),u=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!n[c]);if(a||u){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var d,f;const p=t[c],{id:y,codec:v,levelCodec:b,container:S,metadata:E,supplemental:L}=p;let N=n[c];const R=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],H=R!=null&&R.buffer?R:N,F=H?.pendingCodec||H?.codec,$=H?.levelCodec;N||(N=n[c]={buffer:void 0,listeners:[],codec:v,supplemental:L,container:S,levelCodec:b,metadata:E,id:y});const M=e0(F,$),W=M?.replace(Iw,"$1");let D=e0(v,b);const I=(f=D)==null?void 0:f.replace(Iw,"$1");D&&M&&W!==I&&(c.slice(0,5)==="audio"&&(D=U0(D,this.appendSource)),this.log(`switching codec ${F} to ${D}`),D!==(N.pendingCodec||N.codec)&&(N.pendingCodec=D),N.container=S,this.appendChangeType(c,S,D))}),(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 a=this.tracks[e];if(a){const u=a.buffer;u!=null&&u.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),u.changeType(n),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};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,Rt.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var u;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&fi.isBuffered(c.buffer,n)||((u=this.fragmentTracker.getAppendedFrag(n,Rt.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:a,frag:e},this.append(a,"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:a,frag:u,part:c,chunkMeta:d,offset:f}=t,p=d.buffering[r],{sn:y,cc:v}=u,b=self.performance.now();p.start=b;const S=u.stats.buffering,E=c?c.stats.buffering:null;S.start===0&&(S.start=b),E&&E.start===0&&(E.start=b);const L=i.audio;let N=!1;r==="audio"&&L?.container==="audio/mpeg"&&(N=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const R=i.video,H=R?.buffer;if(H&&y!=="initSegment"){const M=c||u,W=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(R.ending||R.ended)){const I=M.start+M.duration*.05,Q=H.buffered,K=this.currentOp("video");!Q.length&&!K?this.blockAudio(M):!K&&!fi.isBuffered(H,I)&&this.lastVideoAppendEndI||D{var M;p.executeStart=self.performance.now();const W=(M=this.tracks[r])==null?void 0:M.buffer;W&&(N?this.updateTimestampOffset(W,F,.1,r,y,v):f!==void 0&&kt(f)&&this.updateTimestampOffset(W,f,1e-6,r,y,v)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const M=self.performance.now();p.executeEnd=p.end=M,S.first===0&&(S.first=M),E&&E.first===0&&(E.first=M);const W={};this.sourceBuffers.forEach(([D,I])=>{D&&(W[D]=fi.getBuffered(I))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(z.BUFFER_APPENDED,{type:r,frag:u,part:c,chunkMeta:d,parent:u.type,timeRanges:W})},onError:M=>{var W;const D={type:$t.MEDIA_ERROR,parent:u.type,details:Re.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:u,part:c,chunkMeta:d,error:M,err:M,fatal:!1},I=(W=this.media)==null?void 0:W.error;if(M.code===DOMException.QUOTA_EXCEEDED_ERR||M.name=="QuotaExceededError"||"quota"in M)D.details=Re.BUFFER_FULL_ERROR;else if(M.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)D.errorAction=Lc(!0);else if(M.name===HL&&this.sourceBufferCount===0)D.errorAction=Lc(!0);else{const Q=++this.appendErrors[r];this.warn(`Failed ${Q}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(Q>=this.hls.config.appendErrorMaxRetry||I)&&(D.fatal=!0)}this.hls.trigger(z.ERROR,D)}};this.log(`queuing "${r}" append sn: ${y}${c?" p: "+c.index:""} of ${u.type===Rt.MAIN?"level":"track"} ${u.level} cc: ${v}`),this.append($,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(z.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(([a])=>{a&&this.append(this.getFlushOp(a,n,r),a)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[ps.AUDIOVIDEO]?r.push("audiovideo"):(a[ps.AUDIO]&&r.push("audio"),a[ps.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(z.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(([a])=>{if(a){const u=this.tracks[a];(!t.type||t.type===a)&&(u.ending=!0,u.ended||(u.ended=!0,this.log(`${a} buffer reached EOS`)))}});const n=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var u;return a&&!((u=this.tracks[a])!=null&&u.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(z.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(z.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===Re.BUFFER_APPEND_ERROR&&t.frag){var i;const n=(i=t.errorAction)==null?void 0:i.nextAutoLevel;kt(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,a=t.levelTargetDuration,u=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(kt(u)&&u>=0){const d=Math.max(u,a),f=Math.floor(r/a)*a-d;this.flushBackBuffer(r,a,f)}const c=n.frontBufferFlushThreshold;if(kt(c)&&c>0){const d=Math.max(n.maxBufferLength,c),f=Math.max(d,a),p=Math.floor(r/a)*a+f;this.flushFrontBuffer(r,a,p)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const u=fi.getBuffered(r);if(u.length>0&&i>u.start(0)){var a;this.hls.trigger(z.BACK_BUFFER_REACHED,{bufferEnd:i});const c=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger(z.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(z.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([n,r])=>{if(r){const a=fi.getBuffered(r),u=a.length;if(u<2)return;const c=a.start(u-1),d=a.end(u-1);if(i>c||e>=c&&e<=d)return;this.hls.trigger(z.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 kt(r)?{duration:r}:null;const a=this.media.duration,u=kt(i.duration)?i.duration:0;return n>u&&n>a||!kt(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:i}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(kt(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}) ${ys(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(z.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(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.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 a=r,u=e[a];if(this.isPending(u)){const c=this.getTrackCodec(u,a),d=`${u.container};codecs=${c}`;u.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${ys(u)}`);try{const f=i.addSourceBuffer(d),p=Rv(a),y=[a,f];t[p]=y,u.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:a,mimeType:d,parent:u.id});return}this.trackSourceBuffer(a,u)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let n=e.codec;i&&(t==="video"||t==="audiovideo")&&Fh(i,"video")&&(n=W6(n,i));const r=e0(n,e.levelCodec);return r?t.slice(0,5)==="audio"?U0(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,a)=>{const u=a.removedRanges;u!=null&&u.length&&this.hls.trigger(z.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(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,i,n,r,a){const u=t-e.timestampOffset;Math.abs(u)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:n,mediaSource:r}=this,a=this.tracks[e],u=a?.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=kt(n.duration)?n.duration:1/0,d=kt(r.duration)?r.duration:1/0,f=Math.max(0,t),p=Math.min(i,c,d);p>f&&(!a.ending||a.ended)?(a.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 s7(`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(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(a=>{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 a=i.bind(this,e);n.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}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 Nw(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function r7(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function Rv(s){return s==="audio"?1:0}class x1{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(z.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(z.BUFFER_CODECS,this.onBufferCodecs,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(z.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(z.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&&kt(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,x1.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 a=Math.max(t,i);for(let u=0;u=a||c.height>=a)&&n(c,e[u+1])){r=u;break}}return r}}const a7={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},dr=a7,o7={HLS:"h"},l7=o7;class Wa{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Wa?i:new Wa(i))),this.value=e,this.params=t}}const u7="Dict";function c7(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 d7(s,e,t,i){return new Error(`failed to ${s} "${c7(e)}" as ${t}`,{cause:i})}function Ya(s,e,t){return d7("serialize",s,e,t)}class zL{constructor(e){this.description=e}}const Ow="Bare Item",h7="Boolean";function f7(s){if(typeof s!="boolean")throw Ya(s,h7);return s?"?1":"?0"}function m7(s){return btoa(String.fromCharCode(...s))}const p7="Byte Sequence";function g7(s){if(ArrayBuffer.isView(s)===!1)throw Ya(s,p7);return`:${m7(s)}:`}const y7="Integer";function v7(s){return s<-999999999999999||99999999999999912)throw Ya(s,b7);const t=e.toString();return t.includes(".")?t:`${t}.0`}const S7="String",_7=/[\x00-\x1f\x7f]+/;function E7(s){if(_7.test(s))throw Ya(s,S7);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function w7(s){return s.description||s.toString().slice(7,-1)}const A7="Token";function Mw(s){const e=w7(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ya(e,A7);return e}function Qx(s){switch(typeof s){case"number":if(!kt(s))throw Ya(s,Ow);return Number.isInteger(s)?GL(s):T7(s);case"string":return E7(s);case"symbol":return Mw(s);case"boolean":return f7(s);case"object":if(s instanceof Date)return x7(s);if(s instanceof Uint8Array)return g7(s);if(s instanceof zL)return Mw(s);default:throw Ya(s,Ow)}}const k7="Key";function Zx(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Ya(s,k7);return s}function b1(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${Zx(e)}`:`;${Zx(e)}=${Qx(t)}`).join("")}function qL(s){return s instanceof Wa?`${Qx(s.value)}${b1(s.params)}`:Qx(s)}function C7(s){return`(${s.value.map(qL).join(" ")})${b1(s.params)}`}function D7(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw Ya(s,u7);const t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([n,r])=>{r instanceof Wa||(r=new Wa(r));let a=Zx(n);return r.value===!0?a+=b1(r.params):(a+="=",Array.isArray(r.value)?a+=C7(r):a+=qL(r)),a}).join(`,${i}`)}function KL(s,e){return D7(s,e)}const La="CMCD-Object",Vs="CMCD-Request",nu="CMCD-Session",yl="CMCD-Status",L7={br:La,ab:La,d:La,ot:La,tb:La,tpb:La,lb:La,tab:La,lab:La,url:La,pb:Vs,bl:Vs,tbl:Vs,dl:Vs,ltc:Vs,mtp:Vs,nor:Vs,nrr:Vs,rc:Vs,sn:Vs,sta:Vs,su:Vs,ttfb:Vs,ttfbb:Vs,ttlb:Vs,cmsdd:Vs,cmsds:Vs,smrt:Vs,df:Vs,cs:Vs,ts:Vs,cid:nu,pr:nu,sf:nu,sid:nu,st:nu,v:nu,msd:nu,bs:yl,bsd:yl,cdn:yl,rtp:yl,bg:yl,pt:yl,ec:yl,e:yl},R7={REQUEST:Vs};function I7(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 N7(s,e){const t={};if(!s)return t;const i=Object.keys(s),n=e?I7(e):{};return i.reduce((r,a)=>{var u;const c=L7[a]||n[a]||R7.REQUEST,d=(u=r[c])!==null&&u!==void 0?u:r[c]={};return d[a]=s[a],r},t)}function O7(s){return["ot","sf","st","e","sta"].includes(s)}function M7(s){return typeof s=="number"?kt(s):s!=null&&s!==""&&s!==!1}const WL="event";function P7(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 r0=s=>Math.round(s),Jx=(s,e)=>Array.isArray(s)?s.map(t=>Jx(t,e)):s instanceof Wa&&typeof s.value=="string"?new Wa(Jx(s.value,e),s.params):(e.baseUrl&&(s=P7(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Bm=s=>r0(s/100)*100,B7=(s,e)=>{let t=s;return e.version>=2&&(s instanceof Wa&&typeof s.value=="string"?t=new Wa([s]):typeof s=="string"&&(t=[s])),Jx(t,e)},F7={br:r0,d:r0,bl:Bm,dl:Bm,mtp:Bm,nor:B7,rtp:Bm,tb:r0},YL="request",XL="response",T1=["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"],U7=["e"],j7=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Rp(s){return j7.test(s)}function $7(s){return T1.includes(s)||U7.includes(s)||Rp(s)}const QL=["d","dl","nor","ot","rtp","su"];function H7(s){return T1.includes(s)||QL.includes(s)||Rp(s)}const z7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function G7(s){return T1.includes(s)||QL.includes(s)||z7.includes(s)||Rp(s)}const V7=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function q7(s){return V7.includes(s)||Rp(s)}const K7={[XL]:G7,[WL]:$7,[YL]:H7};function ZL(s,e={}){const t={};if(s==null||typeof s!="object")return t;const i=e.version||s.v||1,n=e.reportingMode||YL,r=i===1?q7:K7[n];let a=Object.keys(s).filter(r);const u=e.filter;typeof u=="function"&&(a=a.filter(u));const c=n===XL||n===WL;c&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const d=ds({},F7,e.formatters),f={version:i,reportingMode:n,baseUrl:e.baseUrl};return a.sort().forEach(p=>{let y=s[p];const v=d[p];if(typeof v=="function"&&(y=v(y,f)),p==="v"){if(i===1)return;y=i}p=="pr"&&y===1||(c&&p==="ts"&&!kt(y)&&(y=Date.now()),M7(y)&&(O7(p)&&typeof y=="string"&&(y=new zL(y)),t[p]=y))}),t}function W7(s,e={}){const t={};if(!s)return t;const i=ZL(s,e),n=N7(i,e?.customHeaderMap);return Object.entries(n).reduce((r,[a,u])=>{const c=KL(u,{whitespace:!1});return c&&(r[a]=c),r},t)}function Y7(s,e,t){return ds(s,W7(e,t))}const X7="CMCD";function Q7(s,e={}){return s?KL(ZL(s,e),{whitespace:!1}):""}function Z7(s,e={}){if(!s)return"";const t=Q7(s,e);return encodeURIComponent(t)}function J7(s,e={}){if(!s)return"";const t=Z7(s,e);return`${X7}=${t}`}const Pw=/CMCD=[^&#]+/;function e9(s,e,t){const i=J7(e,t);if(!i)return s;if(Pw.test(s))return s.replace(Pw,i);const n=s.includes("?")?"&":"?";return`${s}${n}${i}`}class t9{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:dr.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:a}=n,u=this.hls.levels[r.level],c=this.getObjectType(r),d={d:(a||r).duration*1e3,ot:c};(c===dr.VIDEO||c===dr.AUDIO||c==dr.MUXED)&&(d.br=u.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const f=a?this.getNextPart(a):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(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHED,this.onMediaDetached,this),e.on(z.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHED,this.onMediaDetached,this),e.off(z.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:l7.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ds(t,this.createData());const i=t.ot===dr.INIT||t.ot===dr.VIDEO||t.ot===dr.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((a,u)=>(n.includes(u)&&(a[u]=t[u]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Y7(e.headers,t,r)):e.url=e9(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:a}=n;for(let u=r.length-1;u>=0;u--){const c=r[u];if(c.index===i&&c.fragment.sn===a)return r[u+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return dr.TIMED_TEXT;if(e.sn==="initSegment")return dr.INIT;if(t==="audio")return dr.AUDIO;if(t==="main")return this.hls.audioTracks.length?dr.VIDEO:dr.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===dr.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===dr.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:fi.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,a,u){t(r),this.loader.load(r,a,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,a,u){t(r),this.loader.load(r,a,u)}}}}const i9=3e5;class s9 extends ia{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(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.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===Rn.SendAlternateToPenaltyBox&&i.flags===Pr.MoveAllAlternatesMatchingHost){const n=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:u,pathwayId:c,type:d}=t.context;u&&n?a=this.getPathwayForGroupId(u,d,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&n&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a),t.details===Re.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: ${a} levels: ${n&&n.length} priorities: ${ys(r)} penalized: ${ys(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]>i9&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,vL(t),this.hls.trigger(z.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:a,"BASE-ID":u,"URI-REPLACEMENT":c}=r;if(t.some(f=>f.pathwayId===a))return;const d=this.getLevelsForPathway(u).map(f=>{const p=new Bs(f.attrs);p["PATHWAY-ID"]=a;const y=p.AUDIO&&`${p.AUDIO}_clone_${a}`,v=p.SUBTITLES&&`${p.SUBTITLES}_clone_${a}`;y&&(i[p.AUDIO]=y,p.AUDIO=y),v&&(n[p.SUBTITLES]=v,p.SUBTITLES=v);const b=JL(f.uri,p["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),S=new jh({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 E=1;E{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":S,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":L}=b;if(S)try{this.uri=new self.URL(S,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${S}`);return}this.scheduleRefresh(this.uri||y.url),E&&this.clonePathways(E);const N={steeringManifest:b,url:n.toString()};this.hls.trigger(z.STEERING_MANIFEST_LOADED,N),L&&this.updatePathwayPriority(L)},onError:(f,p,y,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 S=this.loader;if(typeof S?.getResponseHeader=="function"){const E=S.getResponseHeader("Retry-After");E&&(b=parseFloat(E)*1e3)}this.log(`Steering manifest ${p.url} rate limited`);return}this.scheduleRefresh(this.uri||p.url,b)},onTimeout:(f,p,y)=>{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 Bw(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const u=ds({},a);return u.details=void 0,u.attrs=new Bs(u.attrs),u.url=u.attrs.URI=JL(a.url,a.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 JL(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let u;e&&(u=a?.[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 Ic extends ia{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=Ic.CDMCleanupPromise?[Ic.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 a=Object.keys(this.keySystemAccessPromises);a.length||(a=ph(this.config));const u=a.map(_v).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(u)}this.keyFormatPromise.then(a=>{const u=i0(a);if(i!=="sinf"||u!==Fs.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${u}`);return}let c;try{const v=hn(new Uint8Array(n)),b=u1(JSON.parse(v).sinf),S=KD(b);if(!S)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(S.subarray(8,24))}catch(v){this.warn(`${r} Failed to parse sinf: ${v}`);return}const d=Nn(c),{keyIdToKeySessionPromise:f,mediaKeySessions:p}=this;let y=f[d];for(let v=0;vthis.generateRequestWithPreferredKeySession(b,i,n,"encrypted-event-key-match")),y.catch(L=>this.handleError(L));break}}y||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${p.length}.`))}).catch(a=>this.handleError(a))}},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(z.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(z.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(z.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(z.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(z.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(z.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(z.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(z.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(z.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t?.[e];if(n)return n.licenseUrl;if(e===Fs.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=(a,u,c)=>!!a&&c.indexOf(a)===u,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,u)=>{const c=d=>{const f=d.shift();this.getMediaKeysPromise(f,n,r).then(p=>a({keySystem:f,mediaKeys:p})).catch(p=>{d.length?c(d):p instanceof Mr?u(p):u(new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.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 cL===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=BU(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],u=(n=a)==null?void 0:n.keySystemAccess;if(!u){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ys(r)}`),u=this.requestMediaKeySystemAccess(e,r);const c=a=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(y=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,f.then(v=>v?this.setMediaKeysServerCertificate(y,e,v):y)));return p.catch(y=>{this.error(`Failed to create media-keys for "${e}"}: ${y}`)}),p})}return u.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Nn(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=Fm(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 ${Nn(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})=>_v(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=_v(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=ph(this.config),i=e.map(i0).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 a.catch(u=>{if(u instanceof Mr){const c=ss({},u.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const d=new Mr(c,u.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Mr){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Nn(i.keyId||[])})`:""}`),this.hls.trigger(z.ERROR,e.data)}else this.error(e.message),this.hls.trigger(z.ERROR,{type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Fm(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=i0(e.keyFormat),r=n?[n]:ph(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=ph(this.config)),e.length===0)throw new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ys({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,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));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 a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const b=a.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=Fm(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 d1,f=e._onmessage=b=>{const S=e.mediaKeysSession;if(!S){d.emit("error",new Error("invalid state"));return}const{messageType:E,message:L}=b;this.log(`"${E}" message event for session "${S.sessionId}" message size: ${L.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,L).catch(N=>{d.eventNames().length?d.emit("error",N):this.handleError(N)}):E==="license-release"?e.keySystem===Fs.FAIRPLAY&&this.updateKeySession(e,Vx("acknowledged")).then(()=>this.removeSession(e)).catch(N=>this.handleError(N)):this.warn(`unhandled media key message type "${E}"`)},p=(b,S)=>{S.keyStatus=b;let E;b.startsWith("usable")?d.emit("resolved"):b==="internal-error"||b==="output-restricted"||b==="output-downscaled"?E=Fw(b,S.decryptdata):b==="expired"?E=new Error(`key expired (keyId: ${u})`):b==="released"?E=new Error("key released"):b==="status-pending"||this.warn(`unhandled key status change "${b}" (keyId: ${u})`),E&&(d.eventNames().length?d.emit("error",E):this.handleError(E))},y=e._onkeystatuseschange=b=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const E=this.getKeyStatuses(e);if(!Object.keys(E).some(H=>E[H]!=="status-pending"))return;if(E[u]==="expired"){this.log(`Expired key ${ys(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let N=E[u];if(N)p(N,e);else{var R;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(R=e.keyStatusTimeouts)[u]||(R[u]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const F=this.getKeyStatus(e.decryptdata);if(F&&F!=="status-pending")return this.log(`No status for keyId ${u} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${F} from other session.`),p(F,e);this.log(`key status for ${u} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),N="internal-error",p(N,e)},1e3)),this.log(`No status for keyId ${u} (${ys(E)}).`)}};Qn(e.mediaKeysSession,"message",f),Qn(e.mediaKeysSession,"keystatuseschange",y);const v=new Promise((b,S)=>{d.on("error",S),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 Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.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===Fs.PLAYREADY&&r.length===16){const u=Nn(r);t[u]=i,lL(r)}const a=Nn(r);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=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((a,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:(y,v,b,S)=>{a(y.data)},onError:(y,v,b,S)=>{u(new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:ss({url:c.url,data:void 0},y)},`"${e}" certificate request failed (${r}). Status: ${y.code} (${y.text})`))},onTimeout:(y,v,b)=>{u(new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(y,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(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.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,y=r.length;p in key message");return Vx(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(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||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 a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);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,a,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 Mr({type:$t.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:u,response:{url:a,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${a}). 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,a,e,t).then(({xhr:c,licenseChallenge:d})=>{e.keySystem==Fs.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,Qn(i,"encrypted",this.onMediaEncrypted),Qn(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(yr(e,"encrypted",this.onMediaEncrypted),yr(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,Cl.clearKeyUriToKeyIdMap();const r=n.length;Ic.CDMCleanupPromise=Promise.all(n.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(z.ERROR,{type:$t.OTHER_ERROR,details:Re.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(z.ERROR,{type:$t.OTHER_ERROR,details:Re.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).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: ${Nn(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:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));const{drmSystemOptions:u}=this.config;return(UU(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(z.ERROR,{type:$t.OTHER_ERROR,details:Re.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(z.ERROR,{type:$t.OTHER_ERROR,details:Re.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}Ic.CDMCleanupPromise=void 0;function Fm(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Nn(s.keyId)}function n9(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 Mr 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 Fw(s,e){const t=s==="output-restricted",i=t?Re.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Re.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Mr({type:$t.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class r9{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(z.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(z.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(z.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,a=i-this.lastDroppedFrames,u=t-this.lastDecodedFrames,c=1e3*a/r,d=this.hls;if(d.trigger(z.FPS_DROP,{currentDropped:a,currentDecoded:u,totalDroppedFrames:i}),c>0&&a>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(z.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 eR(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 tR(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){ns.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){ns.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function vc(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 eb(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=o9(s.cues,e,t);for(let a=0;as[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,a=s.length;r=e&&u.endTime<=t)i.push(u);else if(u.startTime>t)return i}return i}function a0(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=a0(this.media.textTracks);for(let r=0;r-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.LEVEL_LOADING,this.onLevelLoading,this),e.on(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(z.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.LEVEL_LOADING,this.onLevelLoading,this),e.off(z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(z.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;a0(i.textTracks).forEach(a=>{vc(a)})}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,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${i} and group:${n} not found in active group ${a?.groupId}`);return}const u=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.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(a=>n?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(f=>!i||i.indexOf(f.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(f=>f.default)&&(this.selectDefaultTrack=!1),a.forEach((f,p)=>{f.id=p});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const u=this.hls.config.subtitlePreference;if(!r&&u){this.selectDefaultTrack=!1;const f=ja(u,a);if(f>-1)r=a[f];else{const p=ja(u,this.tracks);r=this.tracks[p]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(z.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=ja(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),a=e.details,u=a?.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&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(z.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=a0(e.textTracks),i=this.currentTrack;let n;if(i&&(n=t.filter(r=>Xx(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||!kt(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(z.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:a,groupId:u="",name:c,type:d,url:f}=n;this.hls.trigger(z.SUBTITLE_TRACK_SWITCH,{id:a,groupId:u,name:c,type:d,url:f});const p=this.switchParams(n.url,i?.details,n.details);this.loadPlaylist(p)}}function u9(){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 Rh(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const Nc=.025;let W0=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function c9(s,e,t){return`${s.identifier}-${t+1}-${Rh(e)}`}class d9{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 Iv(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=Iv(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=kt(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 Iv(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 h9(this)}}function Iv(s,e){return s-e.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function mc(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class f9{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(z.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=n;const a=()=>{this.hasDetails=!0};r.once(z.LEVEL_LOADED,a),r.once(z.AUDIO_TRACK_LOADED,a),r.once(z.SUBTITLE_TRACK_LOADED,a),r.on(z.MEDIA_ATTACHING,(u,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(z.BUFFER_APPENDED,()=>{const f=this.bufferedEnd;this.reachedPlayout(f)&&(this._bufferedEosTime=f,r.trigger(z.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=iR(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=fi.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=fi.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: ${mc(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Uw=.033;class m9 extends ia{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)):[];a.length&&a.sort((d,f)=>{const p=d.cue.pre,y=d.cue.post,v=f.cue.pre,b=f.cue.post;if(p&&!v)return-1;if(v&&!p||y&&!b)return 1;if(b&&!y)return-1;if(!p&&!v&&!y&&!b){const S=d.startTime,E=f.startTime;if(S!==E)return S-E}return d.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=a,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,a=this.parseSchedule(n,e);(i||t.length||r?.length!==a.length||a.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=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const n=[],r=Object.keys(e);for(let a=0;a!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,d=0;if(e.forEach((f,p)=>{const y=f.cue.pre,v=f.cue.post,b=e[p-1]||null,S=f.appendInPlace,E=v?r:f.startOffset,L=f.duration,N=f.timelineOccupancy===W0.Range?L:0,R=f.resumptionOffset,H=b?.startTime===E,F=E+f.cumulativeDuration;let $=S?F+L:E+R;if(y||!v&&E<=0){const W=d;d+=N,f.timelineStart=F;const D=a;a+=L,i.push({event:f,start:F,end:$,playout:{start:D,end:a},integrated:{start:W,end:d}})}else if(E<=r){if(!H){const I=E-c;if(I>Uw){const Q=c,K=d;d+=I;const q=a;a+=I;const le={previousEvent:e[p-1]||null,nextEvent:f,start:Q,end:Q+I,playout:{start:q,end:a},integrated:{start:K,end:d}};i.push(le)}else I>0&&b&&(b.cumulativeDuration+=I,i[i.length-1].end=E)}v&&($=F),f.timelineStart=F;const W=d;d+=N;const D=a;a+=L,i.push({event:f,start:F,end:$,playout:{start:D,end:a},integrated:{start:W,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),a===p?u.cumulativeDuration=r:(r=0,a=p),!f&&u.snapOptions.in&&(u.resumeAnchor=ku(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+1Nc?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(a=>{const u=t[a].details,c=u.edge;if(i>=c)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`),!1;const d=ku(null,u.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${u.fragStart}-${u.fragmentEnd})`),!0;const f=a==="audio"?.175:0;return Math.abs(d.start-i){const E=y.data,L=E?.ASSETS;if(!Array.isArray(L)){const N=this.assignAssetListError(e,Re.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),b.url,v,S);this.hls.trigger(z.ERROR,N);return}e.assetListResponse=E,this.hls.trigger(z.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:S})},onError:(y,v,b,S)=>{const E=this.assignAssetListError(e,Re.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${y.code} ${y.text} (${v.url})`),v.url,S,b);this.hls.trigger(z.ERROR,E)},onTimeout:(y,v,b)=>{const S=this.assignAssetListError(e,Re.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${v.url})`),v.url,y,b);this.hls.trigger(z.ERROR,S)}};return u.load(c,f,p),this.hls.trigger(z.ASSET_LIST_LOADING,{event:e}),u}assignAssetListError(e,t,i,n,r,a){return e.error=i,{type:$t.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:i,networkDetails:a,stats:r}}}function jw(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function Um(s,e){return`[${s}] Advancing timeline position to ${e}`}class g9 extends ia{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 a=n<=-.01;this.timelinePos=i,this.bufferedPos=i;const u=this.playingItem;if(!u){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-n)&&this.updateSchedule(!0),this.checkBuffer(),a&&i=u.end){var c;const v=this.findItemIndex(u);let b=this.schedule.findItemIndexAtTime(i);if(b===-1&&(b=v+(a?-1:1),this.log(`seeked ${a?"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),!a&&b>v){const S=this.schedule.findJumpRestrictedIndex(v+1,b);if(S>v){this.setSchedulePosition(S);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(a&&i=f+p){var y;(y=u.event)!=null&&y.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 a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,n)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,u=r.events||[],c=r.items||[],d=r.durations,f=i.map(S=>S.identifier),p=!!(u.length||f.length);(p||n)&&this.log(`INTERSTITIALS_UPDATED (${u.length}): ${u} Schedule: ${c.map(S=>ca(S))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let y=null,v=null;a&&(y=this.updateItem(a,this.timelinePos),this.itemsMatch(a,y)?this.playingItem=y: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(S=>{S.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(S=>{if(S.interstitial.appendInPlace){const E=S.assetItem.timelineStart,L=S.timelineOffset-E;if(L)try{S.timelineOffset=E}catch(N){Math.abs(L)>Nc&&this.warn(`${N} ("${S.assetId}" ${S.timelineOffset}->${E})`)}}}),p||n){if(this.hls.trigger(z.INTERSTITIALS_UPDATED,{events:u.slice(0),schedule:c.slice(0),durations:d,removedIds:f}),this.isInterstitial(a)&&f.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(y,a),b&&v!==y&&this.trimInPlace(v,b),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new p9(e),this.schedule=new m9(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(z.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(z.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(z.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(z.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(z.BUFFER_APPENDED,this.onBufferAppended,this),e.on(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(z.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(z.MEDIA_ENDED,this.onMediaEnded,this),e.on(z.ERROR,this.onError,this),e.on(z.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(z.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(z.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(z.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(z.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(z.BUFFER_APPENDED,this.onBufferAppended,this),e.off(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(z.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(z.MEDIA_ENDED,this.onMediaEnded,this),e.off(z.ERROR,this.onError,this),e.off(z.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){yr(e,"play",this.onPlay),yr(e,"pause",this.onPause),yr(e,"seeking",this.onSeeking),yr(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Qn(i,"seeking",this.onSeeking),Qn(i,"timeupdate",this.onTimeupdate),Qn(i,"play",this.onPlay),Qn(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,y,v,b,S)=>{if(p){let E=p[y].start;const L=p.event;if(L){if(y==="playout"||L.timelineOccupancy!==W0.Point){const N=i(v);N?.interstitial===L&&(E+=N.assetItem.startOffset+N[S])}}else{const N=b==="bufferedPos"?a():e[b];E+=N-p.start}return E}return 0},r=(p,y)=>{var v;if(p!==0&&y!=="primary"&&(v=e.schedule)!=null&&v.length){var b;const S=e.schedule.findItemIndexAtTime(p),E=(b=e.schedule.items)==null?void 0:b[S];if(E){const L=E[y].start-E.start;return p+L}}return p},a=()=>{const p=e.bufferedPos;return p===Number.MAX_VALUE?u("primary"):Math.max(p,0)},u=p=>{var y,v;return(y=e.primaryDetails)!=null&&y.live?e.primaryDetails.edge:((v=e.schedule)==null?void 0:v.durations[p])||0},c=(p,y)=>{var v,b;const S=e.effectivePlayingItem;if(S!=null&&(v=S.event)!=null&&v.restrictions.skip||!e.schedule)return;e.log(`seek to ${p} "${y}"`);const E=e.effectivePlayingItem,L=e.schedule.findItemIndexAtTime(p,y),N=(b=e.schedule.items)==null?void 0:b[L],R=e.getBufferingPlayer(),H=R?.interstitial,F=H?.appendInPlace,$=E&&e.itemsMatch(E,N);if(E&&(F||$)){const M=i(e.playingAsset),W=M?.media||e.primaryMedia;if(W){const D=y==="primary"?W.currentTime:n(E,y,e.playingAsset,"timelinePos","currentTime"),I=p-D,Q=(F?D:W.currentTime)+I;if(Q>=0&&(!M||F||Q<=M.duration)){W.currentTime=Q;return}}}if(N){let M=p;if(y!=="primary"){const D=N[y].start,I=p-D;M=N.start+I}const W=!e.isInterstitial(N);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(W||N.event.appendInPlace)){const D=e.media||(F?R?.media:null);D&&(D.currentTime=M)}else if(E){const D=e.findItemIndex(E);if(L>D){const Q=e.schedule.findJumpRestrictedIndex(D+1,L);if(Q>D){e.setSchedulePosition(Q);return}}let I=0;if(W)e.timelinePos=M,e.checkBuffer();else{const Q=N.event.assetList,K=p-(N[y]||N).start;for(let q=Q.length;q--;){const le=Q[q];if(le.duration&&K>=le.startOffset&&K{const p=e.effectivePlayingItem;if(e.isInterstitial(p))return p;const y=t();return e.isInterstitial(y)?y:null},f={get bufferedEnd(){const p=t(),y=e.bufferingItem;if(y&&y===p){var v;return n(y,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-y.playout.start||((v=e.bufferingAsset)==null?void 0:v.startOffset)||0}return 0},get currentTime(){const p=d(),y=e.effectivePlayingItem;return y&&y===p?n(y,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-y.playout.start:0},set currentTime(p){const y=d(),v=e.effectivePlayingItem;v&&v===y&&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 y=(p=d())==null?void 0:p.event.assetList;return y?y.map(v=>e.getAssetPlayer(v.identifier)):[]},get playingIndex(){var p;const y=(p=d())==null?void 0:p.event;return y&&e.effectivePlayingAsset?y.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 a()},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,y=p?.event;if(y&&!y.restrictions.skip){const v=e.findItemIndex(p);if(y.appendInPlace){const b=p.playout.start+p.event.duration;c(b+.001,"playout")}else e.advanceAfterAssetEnded(y,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||!kt(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} ${ys(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 a=this.hls,u=e!==a,c=u&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource;let f;if(a.media)c&&(r=a.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 ${ys(r)}`);else if(!this.detachedData||a.media===t){const b=this.playerQueue;b.length>1&&b.forEach(S=>{if(u&&S.interstitial.appendInPlace!==c){const E=S.interstitial;this.clearInterstitial(S.interstitial,null),E.appendInPlace=!1,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const p=r&&"mediaSource"in r&&((n=r.mediaSource)==null?void 0:n.readyState)!=="closed",y=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(y===r&&v){const b=u&&e.assetId===v.assetIdAtEnd;y.overrides={duration:v.duration,endOfStream:!u||b,cueRemoval:!u}}e.attachMedia(y)}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(Um("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){const a=this.timelinePos=r>0?r:0,u=e.findItemIndexAtTime(a);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=Nv(i,n);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const u=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];u&&this.bufferedToItem(u)}}advanceAfterAssetEnded(e,t,i){const n=Nv(e,i);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,u=r.length;if(a>=u){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&ca(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,u=this.playingLastItem;if(this.isInterstitial(a)){const f=a.event,p=this.playingAsset,y=p?.identifier,v=y?this.getAssetPlayer(y):null;if(v&&y&&(!this.eventItemsMatch(a,r)||t!==void 0&&y!==f.assetList[t].identifier)){var c;const b=f.findAssetIndex(p);if(this.log(`INTERSTITIAL_ASSET_ENDED ${b+1}/${f.assetList.length} ${mc(p)}`),this.endedAsset=p,this.playingAsset=null,this.hls.trigger(z.INTERSTITIAL_ASSET_ENDED,{asset:p,assetListIndex:b,event:f,schedule:n.slice(0),scheduleIndex:e,player:v}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),b);return}this.retreiveMediaSource(y,r),v.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&v.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${ca(a)}`),f.hasPlayed=!0,this.hls.trigger(z.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 S=this.findItemIndex(r);this.advanceSchedule(S,b,t,a,u)}return}}this.advanceSchedule(e,n,t,a,u)}advanceSchedule(e,t,i,n,r){const a=this.schedule;if(!a)return;const u=t[e]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(f=>{const p=f.interstitial,y=a.findEventIndex(p.identifier);(ye+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=a.findAssetIndex(f,this.timelinePos);const b=Nv(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 y=this.preloadAssets(f,i);if(this.eventItemsMatch(u,p||n)||(this.waitingItem=u,this.log(`INTERSTITIAL_STARTED ${ca(u)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger(z.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(y||(y=this.getAssetPlayer(v.identifier)),y===null||y.destroyed){const b=f.assetList.length;this.warn(`asset ${i+1}/${b} player destroyed ${f}`),y=this.createAssetPlayer(f,v,i),y.loadSource()}if(!this.eventItemsMatch(u,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(y,i,t,e,c),this.shouldPlay&&jw(y.media)}else u?(this.resumePrimary(u,e,n),this.shouldPlay&&jw(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(a.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 ${ca(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let u=this.timelinePos;(u=e.end)&&(u=this.getPrimaryResumption(e,t),this.log(Um("resumePrimary",u)),this.timelinePos=u),this.attachPrimary(u,e)}if(!i)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ca(e)}`),this.hls.trigger(z.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.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:fi.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(Um("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(z.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(z.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=ss(ss({},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=ss(ss({},this.altSelection),{},{audio:i});return}const r=ss(ss({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=ss(ss({},this.altSelection),{},{subtitles:i});return}const r=ss(ss({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=YE(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=YE(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,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,n=fi.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${ca(e)} (was ${ca(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=fi.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 a=this.playingItem,u=this.findItemIndex(a);let c=n.findItemIndexAtTime(e);if(this.bufferedPos=r.end||(d=y.event)!=null&&d.appendInPlace&&e+.01>=y.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(y);else{const v=this.primaryDetails;this.primaryLive&&v&&e>v.edge-v.targetduration&&y.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 a=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 ${ca(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,p)=>{const y=this.getAssetPlayer(f.identifier);y&&(p===d&&y.loadSource(),y.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(z.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 a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const u=this.primaryMedia;u&&this.bufferAssetPlayer(a,u)}}}preloadAssets(e,t){const i=e.assetUrl,n=e.assetList.length,r=n===0&&!e.assetListLoader,a=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var u;const y=this.playingItem;!this.isInterstitial(y)&&(y==null||(u=y.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 y=f-c;y>0&&(d=Math.round(y*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(!a&&n){for(let d=t;d{this.hls.trigger(z.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i1){const F=t.duration;F&&H{if(H.live){var F;const W=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:$t.OTHER_ERROR,details:Re.INTERSTITIAL_ASSET_ITEM_ERROR,error:W},I=((F=this.schedule)==null?void 0:F.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,I,i,W.message);return}const $=H.edge-H.fragmentStart,M=t.duration;(S||M===null||$>M)&&(S=!1,this.log(`Interstitial asset "${p}" duration change ${M} > ${$}`),t.duration=$,this.updateSchedule())};b.on(z.LEVEL_UPDATED,(H,{details:F})=>E(F)),b.on(z.LEVEL_PTS_UPDATED,(H,{details:F})=>E(F)),b.on(z.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const L=(H,F)=>{const $=this.getAssetPlayer(p);if($&&F.tracks){$.off(z.BUFFER_CODECS,L),$.tracks=F.tracks;const M=this.primaryMedia;this.bufferingAsset===$.assetItem&&M&&!$.media&&this.bufferAssetPlayer($,M)}};b.on(z.BUFFER_CODECS,L);const N=()=>{var H;const F=this.getAssetPlayer(p);if(this.log(`buffered to end of asset ${F}`),!F||!this.schedule)return;const $=this.schedule.findEventIndex(e.identifier),M=(H=this.schedule.items)==null?void 0:H[$];this.isInterstitial(M)&&this.advanceAssetBuffering(M,t)};b.on(z.BUFFERED_TO_END,N);const R=H=>()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;this.shouldPlay=!0;const $=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,$,H)};return b.once(z.MEDIA_ENDED,R(i)),b.once(z.PLAYOUT_LIMIT_REACHED,R(1/0)),b.on(z.ERROR,(H,F)=>{if(!this.schedule)return;const $=this.getAssetPlayer(p);if(F.details===Re.BUFFER_STALLED_ERROR){if($!=null&&$.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(F,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${F.error} ${e}`)}),b.on(z.DESTROYING,()=>{if(!this.getAssetPlayer(p)||!this.schedule)return;const F=new Error(`Asset player destroyed unexpectedly ${p}`),$={fatal:!0,type:$t.OTHER_ERROR,details:Re.INTERSTITIAL_ASSET_ITEM_ERROR,error:F};this.handleAssetItemError($,e,this.schedule.findEventIndex(e.identifier),i,F.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${mc(t)}`),this.hls.trigger(z.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&&ca(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:a,assetItem:u,assetId:c}=e,d=a.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} ${mc(u)}`),this.hls.trigger(z.INTERSTITIAL_ASSET_STARTED,{asset:u,assetListIndex:t,event:a,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:a}=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=a;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&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(p&&!FD(p,e.tracks)){const y=new Error(`Asset ${mc(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(p)}')`),v={fatal:!0,type:$t.OTHER_ERROR,details:Re.INTERSTITIAL_ASSET_ITEM_ERROR,error:y},b=r.findAssetIndex(a);this.handleAssetItemError(v,r,u,b,y.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),a=e.assetList[r];if(a){const u=this.getAssetPlayer(a.identifier);if(u){const c=u.currentTime||n-a.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!S.error))t.error=b;else for(let S=n;S{const L=parseFloat(S.DURATION);this.createAsset(r,E,f,c+f,L,S.URI),f+=L}),r.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${d}) ${r}`);const p=this.waitingItem,y=p?.event.identifier===a;this.updateSchedule();const v=(n=this.bufferingItem)==null?void 0:n.event;if(y){var b;const S=this.schedule.findEventIndex(a),E=(b=this.schedule.items)==null?void 0:b[S];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==S){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(E)}this.setSchedulePosition(S)}else if(v?.identifier===a){const S=r.assetList[0];if(S){const E=this.getAssetPlayer(S.identifier);if(v.appendInPlace){const L=this.primaryMedia;E&&L&&this.bufferAssetPlayer(E,L)}else E&&E.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case Re.ASSET_LIST_PARSING_ERROR:case Re.ASSET_LIST_LOAD_ERROR:case Re.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case Re.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 $w=500;class y9 extends c1{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",Rt.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(z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(z.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(z.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(z.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(z.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=rt.IDLE,this.setInterval($w),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)||(tn(i)&&(this.fragPrevious=i),this.state=rt.IDLE),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const u=i.start;for(let d=0;d=r[d].start&&u<=r[d].end){a=r[d];break}const c=i.start+i.duration;a?a.end=c:(a={start:u,end:c},r.push(a)),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(a=>{for(let u=0;unew jh(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new jh(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Rt.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!==rt.STOPPED&&this.setInterval($w)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:n,levels:r}=this,{details:a,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 [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(i=c.details)!=null&&i.live){if(a.deltaUpdateFailed)return;const p=this.mainDetails;if(!p){this.startFragRequested=!1;return}const y=p.fragments[0];if(!c.details)a.hasProgramDateTime&&p.hasProgramDateTime?(q0(a,p),d=a.fragmentStart):y&&(d=y.start,Kx(a,d));else{var f;d=this.alignPlaylists(a,c.details,(f=this.levelLastLoaded)==null?void 0:f.details),d===0&&y&&(d=y.start,Kx(a,d))}p&&!this.startFragRequested&&this.setStartPosition(p,d)}c.details=a,this.levelLastLoaded=c,u===n&&(this.hls.trigger(z.SUBTITLE_TRACK_UPDATED,{details:a,id:u,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===rt.IDLE&&(ku(null,a.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&&Rc(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,l1(n.method)).catch(u=>{throw r.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:t}),u}).then(u=>{const c=performance.now();r.trigger(z.FRAG_DECRYPTED,{frag:t,payload:u,stats:{tstart:a,tdecrypt:c}})}).catch(u=>{this.warn(`${u.name}: ${u.message}`),this.state=rt.IDLE})}}doTick(){if(!this.media){this.state=rt.IDLE;return}if(this.state===rt.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(),a=fi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:u,len:c}=a,d=i.details,f=this.hls.maxBufferLength+d.levelTargetDuration;if(c>f)return;const p=d.fragments,y=p.length,v=d.edge;let b=null;const S=this.fragPrevious;if(uv-N?0:N;b=ku(S,p,Math.max(p[0].start,u),R),!b&&S&&S.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 x9={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},sR=s=>String.fromCharCode(x9[s]||s),da=15,vo=100,b9={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},T9={17:2,18:4,21:6,22:8,23:10,19:13,20:15},S9={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},_9={25:2,26:4,29:6,30:8,31:10,27:13,28:15},E9=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class w9{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;ns.log(`${this.time} [${e}] ${i}`)}}}const ru=function(e){const t=[];for(let i=0;ivo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=vo)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=sR(e);if(this.pos>=vo){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 = "+ys(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+ys(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 Hw{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 Ov(i),this.nonDisplayedMemory=new Ov(i),this.lastOutputScreen=new Ov(i),this.currRollUpRow=this.displayedMemory.rows[da-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[da-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: "+ys(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 zw{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=D9(),this.logger=void 0;const n=this.logger=new w9;this.channels=[null,new Hw(e,t,n),new Hw(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"["+ru([t[i],t[i+1]])+"] -> ("+ru([n,r])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(C9(n,r,c)){jm(null,null,c),this.logger.log(3,()=>"Repeated command ("+ru([n,r])+") is dropped");continue}jm(n,r,this.cmdHistory),a=this.parseCmd(n,r),a||(a=this.parseMidrow(n,r)),a||(a=this.parsePAC(n,r)),a||(a=this.parseBackgroundAttributes(n,r))}else jm(null,null,c);if(!a&&(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?")}!a&&!u&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ru([n,r])+" orig: "+ru([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,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.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 ("+ru([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 a=e<=23?1:2;t>=64&&t<=95?i=a===1?b9[e]:S9[e]:i=a===1?T9[e]:_9[e];const u=this.channels[a];return u?(u.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!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 a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+sR(a)+"' in channel "+i),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+ru(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 a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=E9[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const u=e<=23?1:2;return this.channels[u].setBkgData(a),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");$=I,this.hasBeenReset=!0}})),Object.defineProperty(f,"positionAlign",r({},p,{get:function(){return M},set:function(I){const Q=n(I);if(!Q)throw new SyntaxError("An invalid or illegal string was specified.");M=Q,this.hasBeenReset=!0}})),Object.defineProperty(f,"size",r({},p,{get:function(){return W},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");W=I,this.hasBeenReset=!0}})),Object.defineProperty(f,"align",r({},p,{get:function(){return D},set:function(I){const Q=n(I);if(!Q)throw new SyntaxError("An invalid or illegal string was specified.");D=Q,this.hasBeenReset=!0}})),f.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class L9{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rR(s){function e(i,n,r,a){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(a||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 R9{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 aR(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const a=n[r].split(t);if(a.length!==2)continue;const u=a[0],c=a[1];e(u,c)}}const tb=new S1(0,0,""),$m=tb.align==="middle"?"middle":"center";function I9(s,e,t){const i=s;function n(){const u=rR(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 R9;aR(u,function(y,v){let b;switch(y){case"region":for(let S=t.length-1;S>=0;S--)if(t[S].id===v){d.set(y,t[S].region);break}break;case"vertical":d.alt(y,v,["rl","lr"]);break;case"line":b=v.split(","),d.integer(y,b[0]),d.percent(y,b[0])&&d.set("snapToLines",!1),d.alt(y,b[0],["auto"]),b.length===2&&d.alt("lineAlign",b[1],["start",$m,"end"]);break;case"position":b=v.split(","),d.percent(y,b[0]),b.length===2&&d.alt("positionAlign",b[1],["start",$m,"end","line-left","line-right","auto"]);break;case"size":d.percent(y,v);break;case"align":d.alt(y,v,["start",$m,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let f=d.get("line","auto");f==="auto"&&tb.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",$m);let p=d.get("position","auto");p==="auto"&&tb.position===50&&(p=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=p}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=n(),a(),r(s,e)}function oR(s){return s.replace(//gi,` `)}class N9{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new L9,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,a=0;for(r=oR(r);a")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{I9(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&&(a=!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 O9=/\r\n|\n\r|\n|\r/g,Mv=function(e,t,i=0){return e.slice(i,i+t.length)===t},M9=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(!kt(t)||!kt(i)||!kt(n)||!kt(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=3600*1e3*r,t};function _1(s,e,t){return Rh(s.toString())+Rh(e.toString())+Rh(t)}const P9=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(;(a=r)!=null&&a.new;){var a;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function B9(s,e,t,i,n,r,a){const u=new N9,c=jr(new Uint8Array(s)).trim().replace(O9,` `).split(` `),d=[],f=e?zj(e.baseTime,e.timescale):0;let p="00:00.000",y=0,v=0,b,S=!0;u.oncue=function(E){const L=t[i];let N=t.ccOffset;const R=(y-f)/9e4;if(L!=null&&L.new&&(v!==void 0?N=t.ccOffset=L.start:P9(t,i,R)),R){if(!e){b=new Error("Missing initPTS for VTT MPEGTS");return}N=R-t.presentationOffset}const H=E.endTime-E.startTime,F=Br((E.startTime+N-v)*9e4,n*9e4)/9e4;E.startTime=Math.max(F,0),E.endTime=Math.max(F+H,0);const $=E.text.trim();E.text=decodeURIComponent(encodeURIComponent($)),E.id||(E.id=_1(E.startTime,E.endTime,$)),E.endTime>0&&d.push(E)},u.onparsingerror=function(E){b=E},u.onflush=function(){if(b){a(b);return}r(d)},c.forEach(E=>{if(S)if(Mv(E,"X-TIMESTAMP-MAP=")){S=!1,E.slice(16).split(",").forEach(L=>{Mv(L,"LOCAL:")?p=L.slice(6):Mv(L,"MPEGTS:")&&(y=parseInt(L.slice(7)))});try{v=M9(p)/1e3}catch(L){b=L}return}else E===""&&(S=!1);u.parse(E+` `)}),u.flush()}const Pv="stpp.ttml.im1t",lR=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,uR=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,F9={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gw(s,e,t,i){const n=Ai(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(u=>jr(u)),a=Hj(e.baseTime,1,e.timescale);try{r.forEach(u=>t(U9(u,a)))}catch(u){i(u)}}function U9(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},a=Object.keys(r).reduce((p,y)=>(p[y]=n.getAttribute(`ttp:${y}`)||r[y],p),{}),u=n.getAttribute("xml:space")!=="preserve",c=Vw(Bv(n,"styling","style")),d=Vw(Bv(n,"layout","region")),f=Bv(n,"body","[begin]");return[].map.call(f,p=>{const y=cR(p,u);if(!y||!p.hasAttribute("begin"))return null;const v=Uv(p.getAttribute("begin"),a),b=Uv(p.getAttribute("dur"),a);let S=Uv(p.getAttribute("end"),a);if(v===null)throw qw(p);if(S===null){if(b===null)throw qw(p);S=v+b}const E=new S1(v-e,S-e,y);E.id=_1(E.startTime,E.endTime,E.text);const L=d[p.getAttribute("region")],N=c[p.getAttribute("style")],R=j9(L,N,c),{textAlign:H}=R;if(H){const F=F9[H];F&&(E.lineAlign=F),E.align=H}return ds(E,R),E}).filter(p=>p!==null)}function Bv(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Vw(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function cR(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?cR(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function j9(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((u,c)=>{const d=Fv(e,i,c)||Fv(s,i,c)||Fv(n,i,c);return d&&(u[c]=d),u},{})}function Fv(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function qw(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Uv(s,e){if(!s)return null;let t=rR(s);return t===null&&(lR.test(s)?t=$9(s,e):uR.test(s)&&(t=H9(s,e))),t}function $9(s,e){const t=lR.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 H9(s,e){const t=uR.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 Hm{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 z9{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(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(z.FRAG_LOADING,this.onFragLoading,this),e.on(z.FRAG_LOADED,this.onFragLoaded,this),e.on(z.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(z.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(z.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(z.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(z.FRAG_LOADING,this.onFragLoading,this),e.off(z.FRAG_LOADED,this.onFragLoaded,this),e.off(z.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(z.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(z.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(z.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Hm(this,"textTrack1"),t=new Hm(this,"textTrack2"),i=new Hm(this,"textTrack3"),n=new Hm(this,"textTrack4");this.cea608Parser1=new zw(1,e,t),this.cea608Parser2=new zw(3,i,n)}addCues(e,t,i,n,r){let a=!1;for(let u=r.length;u--;){const c=r[u],d=G9(c[0],c[1],t,i);if(d>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,d/(i-t)>.5))return}if(a||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(z.CUES_PARSED,{type:"captions",cues:u,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r,trackId:a}){const{unparsedVttFrags:u}=this;i===Rt.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:r,trackId:a}),u.length&&(this.unparsedVttFrags=[],u.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(z.FRAG_LOADED,c):this.hls.trigger(z.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{vc(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===Pv);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if($L(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,u=a?a0(a.textTracks):null;if(this.tracks.forEach((c,d)=>{let f;if(u){let p=null;for(let y=0;yd!==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 a=this.tracks.map(u=>({label:u.name,kind:u.type.toLowerCase(),default:u.default,subtitleTrack:u}));this.hls.trigger(z.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}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]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.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===Rt.MAIN){var i,n;const{cea608Parser1:r,cea608Parser2:a,lastSn:u}=this,{cc:c,sn:d}=t.frag,f=(i=(n=t.part)==null?void 0:n.index)!=null?i:-1;r&&a&&(d!==u+1||d===u&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===Rt.SUBTITLE)if(n.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){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===Pv?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Gw(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(z.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{i.logger.log(`Failed to parse IMSC1: ${n}`),i.trigger(z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,u=r.length-1;if(!r[i.cc]&&u===-1){a.push(e);return}const c=this.hls,d=(t=i.initSegment)!=null&&t.data?Jr(i.initSegment.data,new Uint8Array(n)).buffer:n;B9(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(z.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const p=f.message==="Missing initPTS for VTT MPEGTS";p?a.push(e):this._fallbackToIMSC1(i,n),c.logger.log(`Failed to parse VTT cue: ${f}`),!(p&&u>i.cc)&&c.trigger(z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Gw(t,this.initPTS[e.cc],()=>{i.textCodec=Pv,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=>tR(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(z.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===Rt.SUBTITLE&&this.onFragLoaded(z.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===Rt.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;reb(u[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:u}=this;Object.keys(u).forEach(c=>eb(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=oR(d.trim()),b=_1(e,t,v);s!=null&&(p=s.cues)!=null&&p.getCueById(b)||(a=new f(e,t,v),a.id=b,a.line=y+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((y,v)=>y.line==="auto"||v.line==="auto"?0:y.line>8&&v.line>8?v.line-y.line:y.line-v.line),n.forEach(y=>tR(s,y))),n}};function K9(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const W9=/(\d+)-(\d+)\/(\d+)/;class Yw{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||Z9,this.controller=new self.AbortController,this.stats=new t1}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=Y9(e,this.controller.signal),a=e.responseType==="arraybuffer",u=a?"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&&kt(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(zh(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(p=>{var y;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:S,statusText:E}=p;throw new J9(E||"fetch, bad network response",S,p)}n.loading.first=v,n.total=Q9(p.headers)||n.total;const b=(y=this.callbacks)==null?void 0:y.onProgress;return b&&kt(t.highWaterMark)?this.loadProgressively(p,n,e,t.highWaterMark,b):a?p.arrayBuffer():e.responseType==="json"?p.json():p.text()}).then(p=>{var y,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 S=p[u];S&&(n.loaded=n.total=S);const E={url:b.url,data:p,code:b.status},L=(y=this.callbacks)==null?void 0:y.onProgress;L&&!kt(t.highWaterMark)&&L(n,e,p,b),(v=this.callbacks)==null||v.onSuccess(E,n,e,b)}).catch(p=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=p&&p.code||0,b=p?p.message:null;(y=this.callbacks)==null||y.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 a=new TL,u=e.body.getReader(),c=()=>u.read().then(d=>{if(d.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=d.value,p=f.length;return t.loaded+=p,p=n&&r(t,i,a.flush().buffer,e)):r(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function Y9(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ds({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function X9(s){const e=W9.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Q9(s){const e=s.get("Content-Range");if(e){const i=X9(e);if(kt(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function Z9(s,e){return new self.Request(s.url,e)}class J9 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const e$=/^age:\s*[\d.]+\s*$/im;class hR{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 t1,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(a=>{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(a=>{var u;(u=this.callbacks)==null||u.onError({code:i.status,text:a.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:a}=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&&kt(r)?r:a,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 a,u;i.loading.end=Math.max(self.performance.now(),i.loading.first);const S=t.responseType==="arraybuffer"?b.byteLength:b.length;i.loaded=i.total=S,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(a=this.callbacks)==null?void 0:a.onProgress;E&&E(i,e,b,t);const L={url:t.responseURL,data:b,code:d};(u=this.callbacks)==null||u.onSuccess(L,i,e,t);return}}const p=r.loadPolicy.errorRetry,y=i.retry,v={url:e.url,data:void 0,code:d};if(z0(p,y,!1,v))this.retry(p);else{var c;ns.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(z0(e,t,!0))this.retry(e);else{var i;ns.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=r1(e,i.retry),i.retry++,ns.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&&e$.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 t$={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},i$=ss(ss({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:hR,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mU,bufferController:n7,capLevelController:x1,errorController:xU,fpsController:r9,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:cL,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:t$},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},s$()),{},{subtitleStreamController:y9,subtitleTrackController:l9,timelineController:z9,audioStreamController:e7,audioTrackController:t7,emeController:Ic,cmcdController:t9,contentSteeringController:s9,interstitialsController:g9});function s$(){return{cueHandler:q9,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 n$(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=ib(s),n=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const u=`${a==="level"?"playlist":a}LoadPolicy`,c=e[u]===void 0,d=[];r.forEach(f=>{const p=`${a}Loading${f}`,y=e[p];if(y!==void 0&&c){d.push(p);const v=i[u].default;switch(e[u]={default:v},f){case"TimeOut":v.maxLoadTimeMs=y,v.maxTimeToFirstByteMs=y;break;case"MaxRetry":v.errorRetry.maxNumRetry=y,v.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":v.errorRetry.retryDelayMs=y,v.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":v.errorRetry.maxRetryDelayMs=y,v.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${u}": ${ys(e[u])}`)}),ss(ss({},i),e)}function ib(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(ib):Object.keys(s).reduce((e,t)=>(e[t]=ib(s[t]),e),{}):s}function r$(s,e){const t=s.loader;t!==Yw&&t!==hR?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):K9()&&(s.loader=Yw,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const o0=2,a$=.1,o$=.05,l$=100;class u$ extends rL{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(z.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.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(l$),this.mediaSource=t.mediaSource;const i=this.media=t.media;Qn(i,"playing",this.onMediaPlaying),Qn(i,"waiting",this.onMediaWaiting),Qn(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(yr(i,"playing",this.onMediaPlaying),yr(i,"waiting",this.onMediaWaiting),yr(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 a=this.media;if(!a)return;const{seeking:u}=a,c=this.seeking&&!u,d=!this.seeking&&u,f=a.paused&&!u||a.ended||a.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&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(z.MEDIA_ENDED,{stalled:!1}));return}if(!fi.getBuffered(a).length){this.nudgeRetry=0;return}const p=fi.bufferInfo(a,e,0),y=p.nextStart||0,v=this.fragmentTracker;if(u&&v&&this.hls){const $=Xw(this.hls.inFlightFragments,e),M=p.len>o0,W=!y||$||y-e>o0&&!v.getPartialFragment(e);if(M||W)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)&&!y)return;const M=Math.max(y,p.start||0)-e,D=!!(b!=null&&b.live)?b.targetduration*2:o0,I=zm(e,v);if(M>0&&(M<=D||I)){a.paused||this._trySkipBufferHole(I);return}}const S=r.detectStallWithCurrentTimeMs,E=self.performance.now(),L=this.waiting;let N=this.stalled;if(N===null)if(L>0&&E-L=S||L)&&this.hls){var H;if(((H=this.mediaSource)==null?void 0:H.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-(b?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(z.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(p),!this.media||!this.hls)return}const F=fi.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(F,R,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(z.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=fi.bufferedInfo(fi.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=fi.timeRangesToArray(n),u=fi.bufferedInfo(a,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 y=zm(e,this.fragmentTracker);y&&"fragment"in y?y=y.fragment:y||(y=void 0);const v=fi.bufferInfo(this.media,e,0);this.hls.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,frag:y,buffer:v.len,bufferInfo:v})}}}}}_tryFixBufferStall(e,t,i){var n,r;const{fragmentTracker:a,media:u}=this,c=(n=this.hls)==null?void 0:n.config;if(!u||!a||!c)return;const d=(r=this.hls)==null?void 0:r.latestLevelDetails,f=zm(i,a);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,Rt.MAIN),a=i.getFragAtPos(n,Rt.MAIN);if(r&&a)return a.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 a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ys(e)})`);this.warn(a.message),t.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.BUFFER_STALLED_ERROR,fatal:!1,error:a,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 a=n.currentTime,u=fi.bufferInfo(n,a,0),c=a0&&u.len<1&&n.readyState<3,y=c-a;if(y>0&&(f||p)){if(y>r.maxBufferHole){let b=!1;if(a===0){const S=i.getAppendedFrag(0,Rt.MAIN);S&&c"u"))return self.VTTCue||self.TextTrackCue}function jv(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,ys(n?ss({type:n},i):i))}return r}const Gm=(()=>{const s=sb();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class d${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(z.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(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(z.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(z.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&&vc(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;tGm&&(p=Gm),p-f<=0&&(p=f+c$);for(let v=0;vf.type===Fr.audioId3&&c:n==="video"?d=f=>f.type===Fr.emsg&&u:d=f=>f.type===Fr.audioId3&&c||f.type===Fr.emsg&&u,eb(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:a}=this.hls.config;if(!r)return;const u=sb();if(i&&n&&!a){const{fragmentStart:S,fragmentEnd:E}=e;let L=this.assetCue;L?(L.startTime=S,L.endTime=E):u&&(L=this.assetCue=jv(u,S,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),L&&(L.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(L),L.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 y;if((y=c.cues)!=null&&y.length){const S=Object.keys(p).filter(E=>!f.includes(E));for(let E=S.length;E--;){var v;const L=S[E],N=(v=p[L])==null?void 0:v.cues;delete p[L],N&&Object.keys(N).forEach(R=>{const H=N[R];if(H){H.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(H)}catch{}}})}}else p=this.dateRangeCuesAppended={}}const b=e.fragments[e.fragments.length-1];if(!(f.length===0||!kt(b?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let S=0;S{if(K!==L.id){const q=d[K];if(q.class===L.class&&q.startDate>L.startDate&&(!Q||L.startDate.01&&(K.startTime=N,K.endTime=$);else if(u){let q=L.attr[Q];NU(Q)&&(q=UD(q));const te=jv(u,N,$,{key:Q,data:q},Fr.dateRange);te&&(te.id=E,this.id3Track.addCue(te),H[Q]=te,a&&(Q==="X-ASSET-LIST"||Q==="X-ASSET-URL")&&te.addEventListener("enter",this.onEventCueEnter))}}p[E]={cues:H,dateRange:L,durationKnown:F}}}}}class h${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:a}=this.config;if(!r||a===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,a)),y=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,v=Math.min(p,Math.max(1,y));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:a,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:a*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,a=n-i.totalduration,u=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,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(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(z.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(z.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===Re.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 f$ extends v1{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(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(z.FRAG_BUFFERED,this.onFragBuffered,this),e.on(z.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(z.FRAG_BUFFERED,this.onFragBuffered,this),e.off(z.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={},a={};let u=!1,c=!1,d=!1;t.levels.forEach(f=>{const p=f.attrs;let{audioCodec:y,videoCodec:v}=f;y&&(f.audioCodec=y=U0(y,i)||void 0),v&&(v=f.videoCodec=Y6(v));const{width:b,height:S,unknownCodecs:E}=f,L=E?.length||0;if(u||(u=!!(b&&S)),c||(c=!!v),d||(d=!!y),L||y&&!this.isAudioSupported(y)||v&&!this.isVideoSupported(v)){this.log(`Some or all CODECS not supported "${p.CODECS}"`);return}const{CODECS:N,"FRAME-RATE":R,"HDCP-LEVEL":H,"PATHWAY-ID":F,RESOLUTION:$,"VIDEO-RANGE":M}=p,D=`${`${F||"."}-`}${f.bitrate}-${$}-${R}-${N}-${M}-${H}`;if(r[D])if(r[D].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const I=a[D]+=1;f.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const Q=this.createLevel(f);r[D]=Q,n.push(Q)}else r[D].addGroupId("audio",p.AUDIO),r[D].addGroupId("text",p.SUBTITLES);else{const I=this.createLevel(f);r[D]=I,a[D]=1,n.push(I)}}),this.filterAndSortMediaOptions(n,t,u,c,d)}createLevel(e){const t=new jh(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=QD(n,[])}return t}isAudioSupported(e){return Fh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Fh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,n,r){var a;let u=[],c=[],d=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((i||n)&&r&&(d=d.filter(({videoCodec:N,videoRange:R,width:H,height:F})=>(!!N||!!(H&&F))&&rU(R))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let N="no level with compatible codecs found in manifest",R=N;t.levels.length&&(R=`one or more CODECS in variant not supported: ${ys(t.levels.map(F=>F.attrs.CODECS).filter((F,$,M)=>M.indexOf(F)===$))}`,this.warn(R),N+=` (${R})`);const H=new Error(N);this.hls.trigger(z.ERROR,{type:$t.MEDIA_ERROR,details:Re.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:H,reason:R})}}),f.end=performance.now();return}t.audioTracks&&(u=t.audioTracks.filter(N=>!N.audioCodec||this.isAudioSupported(N.audioCodec)),Zw(u)),t.subtitles&&(c=t.subtitles,Zw(c));const p=d.slice(0);d.sort((N,R)=>{if(N.attrs["HDCP-LEVEL"]!==R.attrs["HDCP-LEVEL"])return(N.attrs["HDCP-LEVEL"]||"")>(R.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&N.height!==R.height)return N.height-R.height;if(N.frameRate!==R.frameRate)return N.frameRate-R.frameRate;if(N.videoRange!==R.videoRange)return j0.indexOf(N.videoRange)-j0.indexOf(R.videoRange);if(N.videoCodec!==R.videoCodec){const H=zE(N.videoCodec),F=zE(R.videoCodec);if(H!==F)return F-H}if(N.uri===R.uri&&N.codecSet!==R.codecSet){const H=F0(N.codecSet),F=F0(R.codecSet);if(H!==F)return F-H}return N.averageBitrate!==R.averageBitrate?N.averageBitrate-R.averageBitrate:0});let y=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==p.length)){for(let N=0;NH&&H===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=F)}break}const b=r&&!n,S=this.hls.config,E=!!(S.audioStreamController&&S.audioTrackController),L={levels:d,audioTracks:u,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:n,altAudio:E&&!b&&u.some(N=>!!N.url)};f.end=performance.now(),this.hls.trigger(z.MANIFEST_PARSED,L)}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(z.ERROR,{type:$t.OTHER_ERROR,details:Re.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,a=t[e],u=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&n&&r===u)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${u?" with Pathway "+u:""} from level ${i}${r?" with Pathway "+r:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(z.LEVEL_SWITCHING,c);const d=a.details;if(!d||d.live){const f=this.switchParams(a.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===Ci.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Rt.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,a=t.levelInfo;if(!a){var u;this.warn(`Invalid level index ${n}`),(u=t.deliveryDirectives)!=null&&u.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.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"],a=e.details,u=a?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${u&&a.live?" age "+u.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(z.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,a)=>a!==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));vL(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(z.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(z.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Zw(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function fR(){return self.SourceBuffer||self.WebKitSourceBuffer}function mR(){if(!Rl())return!1;const e=fR();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function m$(){if(!mR())return!1;const s=Rl();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Uh(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Uh(e,"audio"))))}function p$(){var s;const e=fR();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const g$=100;class y$ extends c1{constructor(e,t,i){super(e,t,i,"stream-controller",Rt.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||!kt(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(n,r,Rt.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(z.LEVEL_LOADING,this.onLevelLoading,this),e.on(z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(z.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(z.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(z.BUFFER_CREATED,this.onBufferCreated,this),e.on(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(z.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(z.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(z.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(z.BUFFER_CREATED,this.onBufferCreated,this),e.off(z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(z.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(g$),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=rt.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=rt.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case rt.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=rt.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=rt.IDLE;break}break}case rt.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===rt.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 a=i[r],u=this.getMainFwdBufferInfo();if(u===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(u,c)){const S={};this.altAudio===2&&(S.type="video"),this.hls.trigger(z.BUFFER_EOS,S),this.state=rt.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=a.details;if(!d||this.state===rt.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=rt.WAITING_LEVEL,this.startFragRequested=!1;return}const f=u.len,p=this.getMaxBufferLength(a.maxBitrate);if(f>=p)return;this.backtrackFragment&&this.backtrackFragment.start>u.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:u.end;let v=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&tn(v)&&this.fragmentTracker.getState(v)!==fn.OK){var b;const E=((b=this.backtrackFragment)!=null?b:v).sn-d.startSN,L=d.fragments[E-1];L&&v.cc===L.cc&&(v=L,this.fragmentTracker.removeFragment(L))}else this.backtrackFragment&&u.len&&(this.backtrackFragment=null);if(v&&this.isLoopLoading(v,y)){if(!v.gap){const E=this.audioOnly&&!this.altAudio?ps.AUDIO:ps.VIDEO,L=(E===ps.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,E,Rt.MAIN)}v=this.getNextFragmentLoopLoading(v,d,u,Rt.MAIN,p)}v&&(v.initSegment&&!v.initSegment.data&&!this.bitrateTest&&(v=v.initSegment),this.loadFragment(v,a,y))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);n===fn.NOT_LOADED||n===fn.PARTIAL?tn(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,Rt.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=a-t.maxFragLookUpTolerance&&r<=u;if(n!==null&&i.duration>n&&(r{this.hls&&this.hls.trigger(z.AUDIO_TRACK_SWITCHED,t)}),i.trigger(z.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(z.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=$0(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,a=!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 a=!0}a&&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===Rt.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===rt.PARSED&&(this.state=rt.IDLE);return}const u=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*u.total/(u.buffering.end-u.loading.first)),tn(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const a=this.media;a&&(!this._hasEnoughToStart&&fi.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=rt.ERROR;return}switch(t.details){case Re.FRAG_GAP:case Re.FRAG_PARSING_ERROR:case Re.FRAG_DECRYPT_ERROR:case Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Rt.MAIN,t);break;case Re.LEVEL_LOAD_ERROR:case Re.LEVEL_LOAD_TIMEOUT:case Re.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===rt.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Ci.LEVEL&&(this.state=rt.IDLE);break;case Re.BUFFER_ADD_CODEC_ERROR:case Re.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Re.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 Re.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=rt.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ps.AUDIO||!this.altAudio){const i=(t===ps.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,Rt.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=rt.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(z.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===rt.STOPPED||this.state===rt.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:u,part:c,level:d}=a,{video:f,text:p,id3:y,initSegment:v}=n,{details:b}=d,S=this.altAudio?void 0:n.audio;if(this.fragContextChanged(u)){this.fragmentTracker.removeFragment(u);return}if(this.state=rt.PARSING,v){const E=v.tracks;if(E){const H=u.initSegment||u;if(this.unhandledEncryptionError(v,u))return;this._bufferInitSegment(d,E,H,r),i.trigger(z.FRAG_PARSING_INIT_SEGMENT,{frag:H,id:t,tracks:E})}const L=v.initPTS,N=v.timescale,R=this.initPTS[u.cc];if(kt(L)&&(!R||R.baseTime!==L||R.timescale!==N)){const H=v.trackId;this.initPTS[u.cc]={baseTime:L,timescale:N,trackId:H},i.trigger(z.INIT_PTS_FOUND,{frag:u,id:t,initPTS:L,timescale:N,trackId:H})}}if(f&&b){S&&f.type==="audiovideo"&&this.logMuxedErr(u);const E=b.fragments[u.sn-1-b.startSN],L=u.sn===b.startSN,N=!E||u.cc>E.cc;if(n.independent!==!1){const{startPTS:R,endPTS:H,startDTS:F,endDTS:$}=f;if(c)c.elementaryStreams[f.type]={startPTS:R,endPTS:H,startDTS:F,endDTS:$};else if(f.firstKeyFrame&&f.independent&&r.id===1&&!N&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),W=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,D=f.firstKeyFramePTS?f.firstKeyFramePTS:R;if(!L&&Wo0&&(u.gap=!0);u.setElementaryStreamInfo(f.type,R,H,F,$),this.backtrackFragment&&(this.backtrackFragment=u),this.bufferFragmentData(f,u,c,r,L||N)}else if(L||N)u.gap=!0;else{this.backtrack(u);return}}if(S){const{startPTS:E,endPTS:L,startDTS:N,endDTS:R}=S;c&&(c.elementaryStreams[ps.AUDIO]={startPTS:E,endPTS:L,startDTS:N,endDTS:R}),u.setElementaryStreamInfo(ps.AUDIO,E,L,N,R),this.bufferFragmentData(S,u,c,r)}if(b&&y!=null&&y.samples.length){const E={id:t,frag:u,details:b,samples:y.samples};i.trigger(z.FRAG_PARSING_METADATA,E)}if(b&&p){const E={id:t,frag:u,details:b,samples:p.samples};i.trigger(z.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${tn(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,n){if(this.state!==rt.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:u}=t;if(r){const d=e.audioCodec;let f=e0(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 y=r.metadata;y&&"channelCount"in y&&(y.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=Rt.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${f||""}/${d||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=Rt.MAIN;const d=a.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.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(z.BUFFER_CODECS,t),!this.hls)return;c.forEach(d=>{const p=t[d].initSegment;p!=null&&p.byteLength&&this.hls.trigger(z.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,Rt.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=rt.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(fi.isBuffered(e,i)?t=this.getAppendedFrag(i):fi.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(z.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(z.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 kt(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(kt(t)){const i=this.getLevelDetails(),n=this.currentFrag||(i?ku(null,i.fragments,t):null);if(n){const r=n.programDateTime;if(r!==null){const a=r+(t-n.start)*1e3;return new Date(a)}}}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 v$ extends ia{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=Re.KEY_LOAD_ERROR,i,n,r){return new So({type:$t.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;a.setKeyFormat(u);const c=i0(u);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=ph(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,Re.KEY_LOAD_ERROR,d))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,Re.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));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: "+Nn(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,Re.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 a=B6(t.initSegment.data);if(a.length){let u=a[0];u.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Nn(u)}`),Cl.setKeyIdForUri(e.decryptdata.uri,u)):(u=Cl.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Nn(u)}`)),e.decryptdata.keyId=u}}if(!e.decryptdata.keyId&&!tn(t))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}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((a,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:(y,v,b,S)=>{const{frag:E,keyInfo:L}=b,N=$v(L.decryptdata);if(!E.decryptdata||L!==this.keyIdToKeyInfo[N])return u(this.createKeyLoadError(E,Re.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),S));L.decryptdata.key=E.decryptdata.key=new Uint8Array(y.data),E.keyLoader=null,L.loader=null,a({frag:E,keyInfo:L})},onError:(y,v,b,S)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Re.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),b,ss({url:c.url,data:void 0},y)))},onTimeout:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Re.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),b))},onAbort:(y,v,b)=>{this.resetLoader(v),u(this.createKeyLoadError(t,Re.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 a=$v(i.decryptdata)||n;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function $v(s){if(s.keyFormat!==On.FAIRPLAY){const e=s.keyId;if(e)return Nn(e)}return s.uri}function Jw(s){const{type:e}=s;switch(e){case Ci.AUDIO_TRACK:return Rt.AUDIO;case Ci.SUBTITLE_TRACK:return Rt.SUBTITLE;default:return Rt.MAIN}}function Hv(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class x${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(z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(z.LEVEL_LOADING,this.onLevelLoading,this),e.on(z.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(z.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(z.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(z.LEVEL_LOADING,this.onLevelLoading,this),e.off(z.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(z.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(z.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}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:Ci.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:n,pathwayId:r,url:a,deliveryDirectives:u,levelInfo:c}=t;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:Ci.LEVEL,url:a,deliveryDirectives:u,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ci.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a,track:u}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:Ci.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:u})}onLevelsUpdated(e,t){const i=this.loaders[Ci.LEVEL];if(i){const n=i.context;n&&!t.levels.some(r=>r===n.levelOrTrack)&&(i.abort(),delete this.loaders[Ci.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===Ci.MANIFEST?r=i.manifestLoadPolicy.default:r=ds({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),kt((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Ci.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Ci.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Ci.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const f=d.partTarget,p=d.targetduration;if(f&&p){const y=Math.max(f*3,p*.8)*1e3;r=ds({},r,{maxTimeToFirstByteMs:Math.min(y,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},u={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(d,f,p,y)=>{const v=this.getInternalLoader(p);this.resetInternalLoader(p.type);const b=d.data;f.parsing.start=performance.now(),$a.isMediaPlaylist(b)||p.type!==Ci.MANIFEST?this.handleTrackOrLevelPlaylist(d,f,p,y||null,v):this.handleMasterPlaylist(d,f,p,y)},onError:(d,f,p,y)=>{this.handleNetworkError(f,p,!1,d,y)},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,a=e.data,u=Hv(e,i),c=$a.parseMasterPlaylist(a,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:y,startTimeOffset:v,variableList:b}=c;this.variableList=b,f.forEach(N=>{const{unknownCodecs:R}=N;if(R){const{preferManagedMediaSource:H}=this.hls.config;let{audioCodec:F,videoCodec:$}=N;for(let M=R.length;M--;){const W=R[M];Fh(W,"audio",H)?(N.audioCodec=F=F?`${F},${W}`:W,qc.audio[F.substring(0,4)]=2,R.splice(M,1)):Fh(W,"video",H)&&(N.videoCodec=$=$?`${$},${W}`:W,qc.video[$.substring(0,4)]=2,R.splice(M,1))}}});const{AUDIO:S=[],SUBTITLES:E,"CLOSED-CAPTIONS":L}=$a.parseMasterPlaylistMedia(a,u,c);S.length&&!S.some(R=>!R.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"),S.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Bs({}),bitrate:0,url:""})),r.trigger(z.MANIFEST_LOADED,{levels:f,audioTracks:S,subtitles:E,captions:L,contentSteering:d,url:u,stats:t,networkDetails:n,sessionData:p,sessionKeys:y,startTimeOffset:v,variableList:b})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:u,level:c,type:d}=i,f=Hv(e,i),p=kt(c)?c:kt(u)?u:0,y=Jw(i),v=$a.parseLevelPlaylist(e.data,f,p,y,0,this.variableList);if(d===Ci.MANIFEST){const b={attrs:new Bs({}),bitrate:0,details:v,name:"",url:f};v.requestScheduled=t.loading.start+pL(v,0),a.trigger(z.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(z.ERROR,{type:$t.NETWORK_ERROR,details:Re.MANIFEST_PARSING_ERROR,fatal:t.type===Ci.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 a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Ci.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ci.AUDIO_TRACK||e.type===Ci.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const u=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=Re.UNKNOWN,d=!1;const f=this.getInternalLoader(e);switch(e.type){case Ci.MANIFEST:c=i?Re.MANIFEST_LOAD_TIMEOUT:Re.MANIFEST_LOAD_ERROR,d=!0;break;case Ci.LEVEL:c=i?Re.LEVEL_LOAD_TIMEOUT:Re.LEVEL_LOAD_ERROR,d=!1;break;case Ci.AUDIO_TRACK:c=i?Re.AUDIO_TRACK_LOAD_TIMEOUT:Re.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Ci.SUBTITLE_TRACK:c=i?Re.SUBTITLE_TRACK_LOAD_TIMEOUT:Re.SUBTITLE_LOAD_ERROR,d=!1;break}f&&this.resetInternalLoader(e.type);const p={type:$t.NETWORK_ERROR,details:c,fatal:d,url:e.url,loader:f,context:e,error:u,networkDetails:t,stats:r};if(n){const y=t?.url||e.url;p.response=ss({url:y,data:void 0},n)}this.hls.trigger(z.ERROR,p)}handlePlaylistLoaded(e,t,i,n,r,a){const u=this.hls,{type:c,level:d,levelOrTrack:f,id:p,groupId:y,deliveryDirectives:v}=n,b=Hv(t,n),S=Jw(n);let E=typeof n.level=="number"&&S===Rt.MAIN?d:void 0;const L=e.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${e.url}`),!u.config.ignorePlaylistParsingErrors){u.trigger(z.ERROR,{type:$t.NETWORK_ERROR,details:Re.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:L,reason:L.message,response:t,context:n,level:E,parent:S,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const N=e.playlistParsingError=new Error("No Segments found in Playlist");u.trigger(z.ERROR,{type:$t.NETWORK_ERROR,details:Re.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:N,reason:N.message,response:t,context:n,level:E,parent:S,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Ci.MANIFEST:case Ci.LEVEL:if(E){if(!f)E=0;else if(f!==u.levels[E]){const N=u.levels.indexOf(f);N>-1&&(E=N)}}u.trigger(z.LEVEL_LOADED,{details:e,levelInfo:f||u.levels[0],level:E||0,id:p||0,stats:i,networkDetails:r,deliveryDirectives:v,withoutMultiVariant:c===Ci.MANIFEST});break;case Ci.AUDIO_TRACK:u.trigger(z.AUDIO_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break;case Ci.SUBTITLE_TRACK:u.trigger(z.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:p||0,groupId:y||"",stats:i,networkDetails:r,deliveryDirectives:v});break}}}class Ur{static get version(){return $h}static isMSESupported(){return mR()}static isSupported(){return m$()}static getMediaSource(){return Rl()}static get Events(){return z}static get MetadataSchema(){return Fr}static get ErrorTypes(){return $t}static get ErrorDetails(){return Re}static get DefaultConfig(){return Ur.defaultConfig?Ur.defaultConfig:i$}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 d1,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=w6(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=n$(Ur.DefaultConfig,e,t);this.userConfig=e,i.progressive&&r$(i,t);const{abrController:n,bufferController:r,capLevelController:a,errorController:u,fpsController:c}=i,d=new u(this),f=this.abrController=new n(this),p=new bU(this),y=i.interstitialsController,v=y?this.interstitialsController=new y(this,Ur):null,b=this.bufferController=new r(this,p),S=this.capLevelController=new a(this),E=new c(this),L=new x$(this),N=i.contentSteeringController,R=N?new N(this):null,H=this.levelController=new f$(this,R),F=new d$(this),$=new v$(this.config,this.logger),M=this.streamController=new y$(this,p,$),W=this.gapController=new u$(this,p);S.setStreamController(M),E.setStreamController(M);const D=[L,H,M];v&&D.splice(1,0,v),R&&D.splice(1,0,R),this.networkControllers=D;const I=[f,b,W,S,E,F,p];this.audioTrackController=this.createController(i.audioTrackController,D);const Q=i.audioStreamController;Q&&D.push(this.audioStreamController=new Q(this,p,$)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const K=i.subtitleStreamController;K&&D.push(this.subtititleStreamController=new K(this,p,$)),this.createController(i.timelineController,I),$.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(h$,I),this.coreComponents=I,D.push(d);const q=d.onErrorOut;typeof q=="function"&&this.on(z.ERROR,q,d),this.on(z.MANIFEST_LOADED,L.onManifestLoaded,L)}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===z.ERROR;this.trigger(z.ERROR,{type:$t.OTHER_ERROR,details:Re.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(z.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(z.ERROR,{type:$t.OTHER_ERROR,details:Re.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(z.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(z.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(z.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,n=this._url=e1.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(z.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={[Rt.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Rt.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Rt.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=u9()),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){nU(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 a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=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=eL(t);return ZD(e,i,navigator.mediaCapabilities)}}Ur.defaultConfig=void 0;function eA(s,e){const t=s.includes("?")?"&":"?";return`${s}${t}v=${e}`}function pR({src:s,muted:e=g0,className:t}){const i=_.useRef(null),[n,r]=_.useState(!1),[a,u]=_.useState(null),[c,d]=_.useState(1),f=_.useMemo(()=>eA(s,c),[s,c]);return _.useEffect(()=>{let p=!1,y=null,v=null,b=null;const S=i.current;if(!S)return;const E=S;r(!1),u(null),y0(E,{muted:e});const L=()=>{v&&window.clearTimeout(v),b&&window.clearInterval(b),v=null,b=null},N=()=>{p||(L(),d($=>$+1))};async function R(){const $=Date.now();for(;!p&&Date.now()-$<9e4;){try{const M=eA(s,Date.now()),W=await fetch(M,{cache:"no-store"});if(W.status===403)return{ok:!1,reason:"private"};if(W.status===404)return{ok:!1,reason:"offline"};if(W.ok&&(await W.text()).includes("#EXTINF"))return{ok:!0}}catch{}await new Promise(M=>setTimeout(M,500))}return{ok:!1}}async function H(){const $=await R();if(!p){if(!$.ok){if($.reason==="private"||$.reason==="offline"){u($.reason),r(!0);return}window.setTimeout(()=>{p||N()},800);return}if(E.canPlayType("application/vnd.apple.mpegurl")){E.pause(),E.removeAttribute("src"),E.load(),E.src=f,E.load(),E.play().catch(()=>{});let M=Date.now(),W=-1;const D=()=>{E.currentTime>W+.01&&(W=E.currentTime,M=Date.now())},I=()=>{v||(v=window.setTimeout(()=>{v=null,!p&&Date.now()-M>3500&&N()},800))};return E.addEventListener("timeupdate",D),E.addEventListener("waiting",I),E.addEventListener("stalled",I),E.addEventListener("error",I),b=window.setInterval(()=>{p||!E.paused&&Date.now()-M>6e3&&N()},2e3),()=>{E.removeEventListener("timeupdate",D),E.removeEventListener("waiting",I),E.removeEventListener("stalled",I),E.removeEventListener("error",I)}}if(!Ur.isSupported()){r(!0);return}y=new Ur({lowLatencyMode:!0,liveSyncDurationCount:2,maxBufferLength:8}),y.on(Ur.Events.ERROR,(M,W)=>{if(y&&W.fatal){if(W.type===Ur.ErrorTypes.NETWORK_ERROR){y.startLoad();return}if(W.type===Ur.ErrorTypes.MEDIA_ERROR){y.recoverMediaError();return}N()}}),y.loadSource(f),y.attachMedia(E),y.on(Ur.Events.MANIFEST_PARSED,()=>{E.play().catch(()=>{})})}}let F;return(async()=>{const $=await H();typeof $=="function"&&(F=$)})(),()=>{p=!0,L();try{F?.()}catch{}try{y?.destroy()}catch{}}},[s,e,f]),n?g.jsx("div",{className:"text-xs text-gray-400 italic",children:a==="private"?"Private":a==="offline"?"Offline":"–"}):g.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(()=>{}))}})}function b$(){const s=Le;if(s.__gearControlRegistered)return;s.__gearControlRegistered=!0;const e=Le.getComponent("MenuButton"),t=Le.getComponent("MenuItem");class i extends t{_onSelect;constructor(a,u){super(a,u),this._onSelect=u?.onSelect,this.on("click",()=>this._onSelect?.())}}class n extends e{constructor(a,u){super(a,u),this.controlText("Settings");const d=this.el().querySelector(".vjs-icon-placeholder");d&&(d.innerHTML=` `),this.player().on("gear:refresh",()=>this.update())}update(){try{super.update?.()}catch{}const a=this.player(),u=String(a.options_?.__gearQuality??"auto"),c=String(a.options_?.__autoAppliedQuality??""),d=this.items||[];for(const f of d){const p=f?.options_?.__kind,y=f?.options_?.__value;p==="quality"&&f.selected?.(String(y)===u)}try{for(const f of d){if(f?.options_?.__kind!=="quality"||String(f?.options_?.__value)!=="auto")continue;const y=f.el?.()?.querySelector?.(".vjs-menu-item-text");y&&(u==="auto"&&c&&c!=="auto"?y.textContent=`Auto (${c})`:y.textContent="Auto")}}catch{}}createItems(){const a=this.player(),u=[],c=a.options_?.gearQualities||["auto","1080p","720p","480p"],d=String(a.options_?.__gearQuality??"auto");for(const f of c){const p=f==="auto"?"Auto":f==="2160p"?"4K":f;u.push(new i(a,{label:p,selectable:!0,selected:d===f,__kind:"quality",__value:f,onSelect:()=>{a.options_.__gearQuality=f,a.trigger({type:"gear:quality",quality:f}),a.trigger("gear:refresh")}}))}return u}}if(Le.getComponent("Component"),Le.registerComponent("GearMenuButton",n),!s.__gearControlCssInjected){s.__gearControlCssInjected=!0;const r=document.createElement("style");r.textContent=` #player-root .vjs-gear-menu .vjs-icon-placeholder { display: inline-flex; align-items: center; justify-content: center; } /* ✅ Menübreite nicht aufblasen */ #player-root .vjs-gear-menu .vjs-menu { min-width: 0 !important; width: fit-content !important; } /* ✅ die UL auch nicht breit ziehen */ #player-root .vjs-gear-menu .vjs-menu-content { width: fit-content !important; min-width: 0 !important; padding: 2px 0 !important; } /* ✅ Items kompakter */ #player-root .vjs-gear-menu .vjs-menu-content .vjs-menu-item { padding: 4px 10px !important; line-height: 1.1 !important; } /* ✅ Gear-Button als Anker */ #player-root .vjs-gear-menu { position: relative !important; } /* ✅ Popup wirklich über dem Gear-Icon zentrieren */ #player-root .vjs-gear-menu .vjs-menu { position: absolute !important; left: 0% !important; right: 0% !important; transform: translateX(-50%) !important; transform-origin: 50% 100% !important; z-index: 9999 !important; } /* ✅ Manche Skins setzen am UL noch Layout/Width – neutralisieren */ #player-root .vjs-gear-menu .vjs-menu-content { width: max-content !important; min-width: 0 !important; } /* ✅ Menü horizontal zentrieren über dem Gear-Icon */ #player-root .vjs-gear-menu .vjs-menu { z-index: 9999 !important; } `,document.head.appendChild(r)}}const fr=s=>(s||"").replaceAll("\\","/").split("/").pop()||"",E1=s=>s.startsWith("HOT ")?s.slice(4):s,T$=s=>(s||"").trim().toLowerCase(),S$=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 a=r.toLowerCase();i.has(a)||(i.add(a),n.push(r))}return n.sort((r,a)=>r.localeCompare(a,void 0,{sensitivity:"base"})),n};function _$(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 E$(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 tA(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 iA=(...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 w$(s){if(!s||!Number.isFinite(s))return"—";const e=s>=10?0:2;return`${s.toFixed(e)} fps`}function A$(s){return!s||!Number.isFinite(s)?"—":`${Math.round(s)}p`}function k$(s){const e=fr(s||""),t=E1(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]),a=Number(n[2]),u=Number(n[3]),c=Number(n[4]),d=Number(n[5]),f=Number(n[6]);return[r,a,u,c,d,f].every(p=>Number.isFinite(p))?new Date(u,r-1,a,c,d,f):null}const C$=s=>{const e=fr(s||""),t=E1(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},D$=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 xo(...s){return s.filter(Boolean).join(" ")}function L$(s){const[e,t]=_.useState(!1);return _.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 Vm(s){!s||s.__absTimelineShimInstalled||(s.__absTimelineShimInstalled=!0,s.__origCurrentTime=s.currentTime.bind(s),s.__origDuration=s.duration.bind(s),s.__setRelativeTime=e=>{try{s.__origCurrentTime(Math.max(0,e||0))}catch{}},s.currentTime=function(e){const t=Number(this.__timeOffsetSec??0)||0;if(typeof e=="number"&&Number.isFinite(e)){const n=Math.max(0,e);return typeof this.__serverSeekAbs=="function"?(this.__serverSeekAbs(n),n):this.__origCurrentTime(Math.max(0,n-t))}const i=Number(this.__origCurrentTime()??0)||0;return Math.max(0,t+i)},s.duration=function(){const e=Number(this.__fullDurationSec??0)||0;if(e>0)return e;const t=Number(this.__timeOffsetSec??0)||0,i=Number(this.__origDuration()??0)||0;return Math.max(0,t+i)})}function zv(s){const e=typeof s=="number"&&Number.isFinite(s)&&s>0?Math.round(s):0,t=[2160,1440,1080,720,480,360,240],i=u=>`${u}p`,n=u=>Array.from(new Set(u));if(!e)return["auto",...t.map(i)];const r=t.filter(u=>u<=e+8),a=Array.from(new Set([...r,e])).sort((u,c)=>c-u);return n(["auto",...a.map(i)])}function R$({job:s,expanded:e,onClose:t,onToggleExpand:i,modelKey:n,modelsByKey:r,isHot:a=!1,isFavorite:u=!1,isLiked:c=!1,isWatching:d=!1,onKeep:f,onDelete:p,onToggleHot:y,onToggleFavorite:v,onToggleLike:b,onToggleWatch:S,onStopJob:E,startMuted:L=MM}){const N=_.useMemo(()=>fr(s.output?.trim()||"")||s.id,[s.output,s.id]),R=_.useMemo(()=>fr(s.output?.trim()||""),[s.output]),H=_.useMemo(()=>fr(s.output?.trim()||""),[s.output]),F=_.useMemo(()=>E$(D$(s)),[s]),$=s,[M,W]=_.useState(()=>Number(s?.meta?.durationSeconds)||Number(s?.durationSeconds)||0),[D,I]=_.useState(()=>s.status==="running"),[Q,K]=_.useState(()=>({h:0,fps:null})),q=s.status==="running",[le,te]=_.useState(!1),V=q&&le,G=_.useMemo(()=>(H||"").replace(/\.[^.]+$/,""),[H]),J=_.useMemo(()=>q?s.id:G||s.id,[q,s.id,G]);_.useEffect(()=>{if(q||M>0)return;const Y=fr(s.output?.trim()||"");if(!Y)return;let ae=!0;const _e=new AbortController;return(async()=>{try{const Me=xl(`/api/record/done/meta?file=${encodeURIComponent(Y)}`),Ce=await vv(Me,{signal:_e.signal,cache:"no-store"});if(!Ce.ok)return;const $e=await Ce.json(),tt=Number($e?.durationSeconds||$e?.meta?.durationSeconds||0)||0;if(!ae||tt<=0)return;W(tt);const ut=ft.current;if(ut&&!ut.isDisposed?.())try{ut.__fullDurationSec=tt,ut.trigger?.("durationchange"),ut.trigger?.("timeupdate")}catch{}}catch{}})(),()=>{ae=!1,_e.abort()}},[q,M,s.output]);const ie=R.startsWith("HOT "),oe=_.useMemo(()=>{const Y=(n||"").trim();return Y||C$(s.output)},[n,s.output]),j=_.useMemo(()=>E1(R),[R]),X=_.useMemo(()=>{const Y=Number(M||0)||0;return Y>0?_$(Y*1e3):"—"},[M]),se=_.useMemo(()=>{const Y=k$(s.output);if(Y)return tA(Y);const ae=$.startedAt??$.endedAt??$.createdAt??$.fileCreatedAt??$.ctime??null,_e=ae?new Date(ae):null;return tA(_e&&Number.isFinite(_e.getTime())?_e:null)},[s.output,$.startedAt,$.endedAt,$.createdAt,$.fileCreatedAt,$.ctime]),fe=_.useMemo(()=>T$((n||oe||"").trim()),[n,oe]),pe=_.useMemo(()=>{const Y=r?.[fe];return S$(Y?.tags)},[r,fe]),de=_.useMemo(()=>xl(`/api/record/preview?id=${encodeURIComponent(J)}&file=preview.jpg`),[J]),Ve=_.useMemo(()=>xl(`/api/record/preview?id=${encodeURIComponent(J)}&file=thumbs.webp`),[J]),Ze=_.useMemo(()=>xl(`/api/record/preview?id=${encodeURIComponent(J)}&play=1&file=index_hq.m3u8`),[J]),[Je,Pe]=_.useState(de);_.useEffect(()=>{Pe(de)},[de]);const Fe=_.useMemo(()=>iA(Q.h,$.videoHeight,$.height,$.meta?.height),[Q.h,$.videoHeight,$.height,$.meta?.height]),qe=_.useMemo(()=>iA(Q.fps,$.fps,$.frameRate,$.meta?.fps,$.meta?.frameRate),[Q.fps,$.fps,$.frameRate,$.meta?.fps,$.meta?.frameRate]),[dt,Ge]=_.useState(null),At=_.useMemo(()=>A$(dt??Fe),[dt,Fe]),lt=_.useMemo(()=>w$(qe),[qe]);_.useEffect(()=>{const Y=ae=>ae.key==="Escape"&&t();return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[t]);const bt=_.useMemo(()=>{const Y=`/api/record/preview?id=${encodeURIComponent(J)}&file=index_hq.m3u8&play=1`;return xl(q?`${Y}&t=${Date.now()}`:Y)},[J,q]);_.useEffect(()=>{if(!q){te(!1);return}let Y=!0;const ae=new AbortController;return te(!1),(async()=>{for(let Me=0;Me<120&&Y&&!ae.signal.aborted;Me++){try{const Ce=await vv(bt,{method:"GET",cache:"no-store",signal:ae.signal,headers:{"cache-control":"no-cache"}});if(Ce.ok){const $e=await Ce.text(),tt=$e.includes("#EXTM3U"),ut=/#EXTINF:/i.test($e)||/\.ts(\?|$)/i.test($e)||/\.m4s(\?|$)/i.test($e);if(tt&&ut){Y&&te(!0);return}}}catch{}await new Promise(Ce=>setTimeout(Ce,500))}})(),()=>{Y=!1,ae.abort()}},[q,bt]);const nt=_.useCallback(Y=>{const ae=String(Y.quality||"auto").trim(),_e=typeof Y.startSec=="number"&&Number.isFinite(Y.startSec)&&Y.startSec>0?Math.floor(Y.startSec):0,Me=new URLSearchParams;Y.file&&Me.set("file",Y.file),Y.id&&Me.set("id",Y.id);const Ce=tt=>{const ut=String(tt).match(/(\d{3,4})p/i);return ut?Number(ut[1]):0},$e=typeof Fe=="number"&&Number.isFinite(Fe)&&Fe>0?Math.round(Fe):0;if(ae&&ae!=="auto"){Me.set("quality",ae);const tt=Ce(ae);_e===0&&$e&&tt&&tt<$e-8&&Me.set("stream","1")}return _e>0&&Me.set("t",String(_e)),xl(`/api/record/video?${Me.toString()}`)},[Fe]),[wt,ht]=_.useState("auto"),[Et,ye]=_.useState("auto"),mt=_.useRef(wt);_.useEffect(()=>{mt.current=wt},[wt]);const st=_.useRef(Et);_.useEffect(()=>{st.current=Et},[Et]);const Xe=_.useMemo(()=>{if(q)return{src:"",type:""};if(!D)return{src:"",type:""};const Y=fr(s.output?.trim()||"");if(Y){const ae=Y.toLowerCase().split(".").pop(),_e=ae==="mp4"?"video/mp4":ae==="ts"?"video/mp2t":"application/octet-stream";return{src:nt({file:Y,quality:Et}),type:_e}}return{src:nt({id:s.id,quality:Et}),type:"video/mp4"}},[q,D,s.output,s.id,Et,nt]),xt=_.useRef(null),ft=_.useRef(null),Pt=_.useRef(null),qt=_.useRef(!1),[It,ni]=_.useState(!1),[Gt,yi]=_.useState(0),Zt=_.useCallback(()=>{const Y=ft.current;if(!Y||Y.isDisposed?.())return;const ae=typeof Y.videoHeight=="function"?Y.videoHeight():0;typeof ae=="number"&&ae>0&&Number.isFinite(ae)&&Ge(ae)},[]),Jt=_.useMemo(()=>fr(s.output?.trim()||"")||s.id,[s.output,s.id]),di=_.useMemo(()=>{const Y=typeof Fe=="number"&&Number.isFinite(Fe)&&Fe>0?Math.round(Fe):0;return Y?`${Y}p`:"auto"},[Fe]),Zi=_.useRef("");_.useEffect(()=>{if(Zi.current!==Jt){Zi.current=Jt,ht(di),ye(di),Ge(null);const Y=ft.current;if(Y&&!Y.isDisposed?.())try{Y.options_.__gearQuality=di,Y.options_.__autoAppliedQuality=di,Y.trigger?.("gear:refresh")}catch{}}},[Jt,di]),_.useEffect(()=>{if(q){I(!0);return}const Y=fr(s.output?.trim()||"");if(!Y){I(!0);return}let ae=!0;const _e=new AbortController;return I(!1),(async()=>{for(let Me=0;Me<80&&ae&&!_e.signal.aborted;Me++){try{const Ce=xl(`/api/record/done/meta?file=${encodeURIComponent(Y)}`),$e=await vv(Ce,{signal:_e.signal,cache:"no-store"});if($e.ok){const tt=await $e.json(),ut=!!tt?.metaExists,Qe=Number(tt?.durationSeconds||0)||0,at=Number(tt?.height||0)||0,pt=Number(tt?.fps||0)||0;if(Qe>0){W(Qe);const Mt=ft.current;if(Mt&&!Mt.isDisposed?.())try{Mt.__fullDurationSec=Qe,Mt.trigger?.("durationchange"),Mt.trigger?.("timeupdate")}catch{}}if(at>0&&K({h:at,fps:pt>0?pt:null}),ut){I(!0);return}}}catch{}await new Promise(Ce=>setTimeout(Ce,250))}ae&&I(!0)})(),()=>{ae=!1,_e.abort()}},[q,Jt,s.output]);const[,Di]=_.useState(0);_.useEffect(()=>{if(typeof window>"u")return;const Y=window.visualViewport;if(!Y)return;const ae=()=>Di(_e=>_e+1);return ae(),Y.addEventListener("resize",ae),Y.addEventListener("scroll",ae),window.addEventListener("resize",ae),window.addEventListener("orientationchange",ae),()=>{Y.removeEventListener("resize",ae),Y.removeEventListener("scroll",ae),window.removeEventListener("resize",ae),window.removeEventListener("orientationchange",ae)}},[]);const[Mi,Ki]=_.useState(56),[As,xe]=_.useState(null),B=!e,Z=L$("(min-width: 640px)"),re=B&&Z,Te="player_window_v1",Ke=420,vt=280,Tt=12,Li=320,bi=200;_.useEffect(()=>{if(!It)return;const Y=ft.current;if(!Y||Y.isDisposed?.())return;const ae=Y.el();if(!ae)return;const _e=ae.querySelector(".vjs-control-bar");if(!_e)return;const Me=()=>{const $e=Math.round(_e.getBoundingClientRect().height||0);$e>0&&Ki($e)};Me();let Ce=null;return typeof ResizeObserver<"u"&&(Ce=new ResizeObserver(Me),Ce.observe(_e)),window.addEventListener("resize",Me),()=>{window.removeEventListener("resize",Me),Ce?.disconnect()}},[It,e]);const ji=_.useCallback((Y,ae,_e)=>{if(q)return;Vm(Y);const Me=!!Y.paused?.(),Ce=Number(Y.currentTime?.()??0)||0,$e=Ce>0?Math.floor(Ce/2)*2:0,tt=Ce-$e;Y.__timeOffsetSec=$e,qt.current=!0,ye(_e),Y.options_.__autoAppliedQuality=_e;const ut=nt({file:ae,quality:_e,startSec:$e}),Qe=Number(M||0)||0;Qe>0&&(Y.__fullDurationSec=Qe);try{const pt=Y.__onLoadedMetaQSwitch;pt&&Y.off("loadedmetadata",pt)}catch{}const at=()=>{if(Zt(),!(Number(Y.__fullDurationSec)>0))try{const pt=Number(Y.__origDuration?.()??0)||0;pt>0&&(Y.__fullDurationSec=$e+pt)}catch{}try{Y.__setRelativeTime?.(tt)}catch{}try{Y.trigger?.("timeupdate")}catch{}try{Y.trigger?.("gear:refresh")}catch{}if(!Me){const pt=Y.play?.();pt&&typeof pt.catch=="function"&&pt.catch(()=>{})}};Y.__onLoadedMetaQSwitch=at,Y.one("loadedmetadata",at);try{Y.src({src:ut,type:"video/mp4"})}catch{}try{Y.load?.()}catch{}},[q,nt,Zt,M]);_.useEffect(()=>{const Y=ft.current;if(!Y||Y.isDisposed?.())return;Vm(Y);const ae=_e=>{const Me=String(_e?.quality??"auto").trim();if(q)return;const Ce=fr(s.output?.trim()||"");if(Ce){if(ht(Me),Me==="auto"){try{Y.options_.__gearQuality="auto",Y.options_.__autoAppliedQuality=st.current||di,Y.trigger?.("gear:refresh")}catch{}return}try{Y.options_.__gearQuality=Me,Y.options_.__autoAppliedQuality=Me,Y.trigger?.("gear:refresh")}catch{}ji(Y,Ce,Me)}};return Y.on("gear:quality",ae),()=>{try{Y.off("gear:quality",ae)}catch{}}},[Gt,s.output,q,ji,di]),_.useEffect(()=>{if(!It||q||wt!=="auto")return;const Y=ft.current;if(!Y||Y.isDisposed?.())return;Vm(Y);const ae=fr(s.output?.trim()||"");if(!ae)return;const _e=()=>(Y.options_?.gearQualities||zv(dt??Fe)).filter(zt=>zt&&zt!=="auto"),Me=Xt=>{const zt=String(Xt).match(/(\d{3,4})p/i);return zt?Number(zt[1]):0},Ce=Xt=>[...Xt].sort((zt,ui)=>Me(ui)-Me(zt)),$e=(Xt,zt)=>{const ui=Ce(zt),un=Me(Xt);for(let Ps=0;Ps0&&Es{const ui=Ce(zt),un=Me(Xt);for(let Ps=ui.length-1;Ps>=0;Ps--)if(Me(ui[Ps])>un+8)return ui[Ps];return ui[0]||Xt};let ut=0,Qe=0,at=0;const pt=()=>{ut=Date.now()};Y.on("waiting",pt),Y.on("stalled",pt);const Mt=()=>{try{const Xt=Number(Y.__origCurrentTime?.()??0)||0,zt=Y.buffered?.();if(!zt||zt.length<=0)return 0;const ui=zt.end(zt.length-1);return Math.max(0,(Number(ui)||0)-Xt)}catch{return 0}},Nt=()=>{const Xt=Date.now();if(Xt-Qe<8e3)return;const zt=_e();if(!zt.length)return;const ui=st.current&&st.current!=="auto"?st.current:zt[0],un=Mt(),Ps=Xt-ut<2500;if(un<4||Ps){const Es=$e(ui,zt);if(Es&&Es!==ui){Qe=Xt,at=0;try{Y.options_.__autoAppliedQuality=Es,Y.trigger?.("gear:refresh")}catch{}ji(Y,ae,Es)}return}if(un>20&&Xt-ut>2e4){if(at||(at=Xt),Xt-at>2e4){const Es=tt(ui,zt);if(Es&&Es!==ui){Qe=Xt,at=Xt;try{Y.options_.__autoAppliedQuality=Es,Y.trigger?.("gear:refresh")}catch{}ji(Y,ae,Es)}}}else at=0},Ft=window.setInterval(Nt,2e3);return Nt(),()=>{window.clearInterval(Ft);try{Y.off("waiting",pt)}catch{}try{Y.off("stalled",pt)}catch{}}},[It,q,wt,s.output,dt,Fe,ji]),_.useEffect(()=>ni(!0),[]),_.useEffect(()=>{let Y=document.getElementById("player-root");Y||(Y=document.createElement("div"),Y.id="player-root");let ae=null;if(Z){const _e=Array.from(document.querySelectorAll("dialog[open]"));ae=_e.length?_e[_e.length-1]:null}ae=ae??document.body,ae.appendChild(Y),Y.style.position="relative",Y.style.zIndex="2147483647",xe(Y)},[Z]),_.useEffect(()=>{const Y=ft.current;if(!Y||Y.isDisposed?.()||q)return;Vm(Y);const ae=fr(s.output?.trim()||"");if(!ae)return;const _e=Number(M||0)||0;return _e>0&&(Y.__fullDurationSec=_e),Y.__serverSeekAbs=Me=>{const Ce=Math.max(0,Number(Me)||0),$e=mt.current==="auto"?String(st.current||"auto").trim():String(mt.current||"auto").trim(),tt=zt=>{const ui=String(zt).match(/(\d{3,4})p/i);return ui?Number(ui[1]):0},ut=typeof Fe=="number"&&Number.isFinite(Fe)&&Fe>0?Math.round(Fe):0,Qe=tt($e);if(!($e!=="auto"&&ut>0&&Qe>0&&Qe0||un.includes("t=")||un.includes("start=")){Y.__timeOffsetSec=0;const Es=nt({file:ae,quality:$e}),zr=()=>{Zt();try{Y.__origCurrentTime?.(Ce);try{Y.trigger?.("timeupdate")}catch{}}catch{try{Y.currentTime?.(Ce)}catch{}}if(!zt){const pn=Y.play?.();pn&&typeof pn.catch=="function"&&pn.catch(()=>{})}};try{Y.one("loadedmetadata",zr)}catch{}try{Y.src({src:Es,type:"video/mp4"})}catch{}try{Y.load?.()}catch{}return}try{Y.__origCurrentTime?.(Ce);try{Y.trigger?.("timeupdate")}catch{}}catch{try{Y.currentTime?.(Ce)}catch{}}return}const pt=!!Y.paused?.(),Mt=Math.floor(Ce/2)*2,Nt=Ce-Mt;Y.__timeOffsetSec=Mt;const Ft=nt({file:ae,quality:$e,startSec:Mt}),Xt=()=>{Zt(),Y.__setRelativeTime?.(Nt);try{Y.trigger?.("timeupdate")}catch{}if(!pt){const zt=Y.play?.();zt&&typeof zt.catch=="function"&&zt.catch(()=>{})}};try{Y.one("loadedmetadata",Xt)}catch{}try{Y.src({src:Ft,type:"video/mp4"})}catch{}try{Y.load?.()}catch{}},()=>{try{delete Y.__serverSeekAbs}catch{}}},[Gt,s.output,q,nt,Zt,Fe]),_.useLayoutEffect(()=>{if(!It||!xt.current||ft.current||q||!D)return;const Y=document.createElement("video");Y.className="video-js vjs-big-play-centered w-full h-full",Y.setAttribute("playsinline","true"),xt.current.appendChild(Y),Pt.current=Y,b$();const ae=zv(Fe),_e=(()=>{const Ce=typeof Fe=="number"&&Number.isFinite(Fe)&&Fe>0?Math.round(Fe):0;return Ce?`${Ce}p`:"auto"})();ht(_e),ye(_e);const Me=Le(Y,{autoplay:!0,muted:L,controls:!0,preload:"metadata",playsinline:!0,responsive:!0,fluid:!1,fill:!0,liveui:!1,html5:{vhs:{lowLatencyMode:!0}},inactivityTimeout:0,gearQualities:ae,__gearQuality:_e,__autoAppliedQuality:_e,controlBar:{skipButtons:{backward:10,forward:10},volumePanel:{inline:!1},children:["skipBackward","playToggle","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","spacer","playbackRateMenuButton","GearMenuButton","fullscreenToggle"]},playbackRates:[.5,1,1.25,1.5,2]});ft.current=Me,yi(Ce=>Ce+1),Me.one("loadedmetadata",()=>{Zt();try{const Ce=typeof Me.videoHeight=="function"?Me.videoHeight():0,$e=zv(Ce);Me.options_.gearQualities=$e;const tt=String(Me.options_.__gearQuality??"auto"),ut=typeof Ce=="number"&&Number.isFinite(Ce)&&Ce>0?`${Math.round(Ce)}p`:"auto",Qe=$e.includes(tt)?tt:$e.includes(ut)?ut:"auto";if(Me.options_.__gearQuality=Qe,ht(Qe),Qe!=="auto")ye(Qe),Me.options_.__autoAppliedQuality=Qe;else{const at=String(st.current||"auto"),pt=at!=="auto"?at:ut!=="auto"?ut:"auto";ye(pt),Me.options_.__autoAppliedQuality=pt}Me.trigger("gear:refresh")}catch{}});try{const Ce=Me.getChild("controlBar")?.getChild("GearMenuButton");Ce?.el&&Ce.el().classList.add("vjs-gear-menu")}catch{}return Me.userActive(!0),Me.on("userinactive",()=>Me.userActive(!0)),()=>{try{ft.current&&(ft.current.dispose(),ft.current=null)}finally{Pt.current&&(Pt.current.remove(),Pt.current=null)}}},[It,L,q,D,Fe,Zt]),_.useEffect(()=>{const Y=ft.current;if(!Y||Y.isDisposed?.())return;const ae=Y.el();ae&&ae.classList.toggle("is-live-download",!!V)},[V]);const ai=_.useCallback(()=>{const Y=ft.current;if(!(!Y||Y.isDisposed?.())){try{Y.pause(),Y.reset?.()}catch{}try{Y.src({src:"",type:"video/mp4"}),Y.load?.()}catch{}}},[]);_.useEffect(()=>{if(!It)return;if(!q&&!D){ai();return}const Y=ft.current;if(!Y||Y.isDisposed?.())return;if(qt.current){qt.current=!1;return}const ae=Y.currentTime()||0;if(Y.muted(L),!Xe.src){try{Y.pause(),Y.reset?.(),Y.error(null)}catch{}return}Y.__timeOffsetSec=0;const _e=Number(M||0)||0;Y.__fullDurationSec=_e;const Me=String(Y.currentSrc?.()||"");if(Me&&Me===Xe.src){const $e=Y.play?.();$e&&typeof $e.catch=="function"&&$e.catch(()=>{});return}Y.src({src:Xe.src,type:Xe.type});const Ce=()=>{const $e=Y.play?.();$e&&typeof $e.catch=="function"&&$e.catch(()=>{})};Y.one("loadedmetadata",()=>{if(Y.isDisposed?.())return;Zt();try{const tt=Number(M||0)||0;tt>0&&(Y.__fullDurationSec=tt)}catch{}try{Y.playbackRate(1)}catch{}const $e=/mpegurl/i.test(Xe.type);if(ae>0&&!$e)try{const tt=Number(Y.__timeOffsetSec??0)||0,ut=Math.max(0,ae-tt);Y.__setRelativeTime?.(ut)}catch{}try{Y.trigger?.("timeupdate")}catch{}Ce()}),Ce()},[It,q,D,Xe.src,Xe.type,L,Zt,M,ai]),_.useEffect(()=>{if(!It)return;const Y=ft.current;if(!Y||Y.isDisposed?.())return;const ae=()=>{s.status==="running"&&te(!1)};return Y.on("error",ae),()=>{try{Y.off("error",ae)}catch{}}},[It,s.status]),_.useEffect(()=>{const Y=ft.current;!Y||Y.isDisposed?.()||queueMicrotask(()=>Y.trigger("resize"))},[e]),_.useEffect(()=>{const Y=ae=>{const Me=(ae.detail?.file??"").trim();if(!Me)return;const Ce=fr(s.output?.trim()||"");Ce&&Ce===Me&&ai()};return window.addEventListener("player:release",Y),()=>window.removeEventListener("player:release",Y)},[s.output,ai]),_.useEffect(()=>{const Y=ae=>{const Me=(ae.detail?.file??"").trim();if(!Me)return;const Ce=fr(s.output?.trim()||"");Ce&&Ce===Me&&(ai(),t())};return window.addEventListener("player:close",Y),()=>window.removeEventListener("player:close",Y)},[s.output,ai,t]);const Fi=()=>{if(typeof window>"u")return{w:0,h:0,ox:0,oy:0,bottomInset:0};const Y=window.visualViewport;if(Y&&Number.isFinite(Y.width)&&Number.isFinite(Y.height)){const Ce=Math.floor(Y.width),$e=Math.floor(Y.height),tt=Math.floor(Y.offsetLeft||0),ut=Math.floor(Y.offsetTop||0),Qe=Math.max(0,Math.floor(window.innerHeight-(Y.height+Y.offsetTop)));return{w:Ce,h:$e,ox:tt,oy:ut,bottomInset:Qe}}const ae=document.documentElement,_e=ae?.clientWidth||window.innerWidth,Me=ae?.clientHeight||window.innerHeight;return{w:_e,h:Me,ox:0,oy:0,bottomInset:0}},li=_.useCallback((Y,ae)=>{if(typeof window>"u")return Y;const{w:_e,h:Me}=Fi(),Ce=_e-Tt*2,$e=Me-Tt*2;let tt=Y.w,ut=Y.h;ae&&Number.isFinite(ae)&&ae>.1?(tt=Math.max(Li,tt),ut=tt/ae,utCe&&(tt=Ce,ut=tt/ae),ut>$e&&(ut=$e,tt=ut*ae)):(tt=Math.max(Li,Math.min(tt,Ce)),ut=Math.max(bi,Math.min(ut,$e)));const Qe=Math.max(Tt,Math.min(Y.x,_e-tt-Tt)),at=Math.max(Tt,Math.min(Y.y,Me-ut-Tt));return{x:Qe,y:at,w:tt,h:ut}},[]),$s=_.useCallback(()=>{if(typeof window>"u")return{x:Tt,y:Tt,w:Ke,h:vt};try{const tt=window.localStorage.getItem(Te);if(tt){const ut=JSON.parse(tt);if(typeof ut.x=="number"&&typeof ut.y=="number"&&typeof ut.w=="number"&&typeof ut.h=="number")return li({x:ut.x,y:ut.y,w:ut.w,h:ut.h},ut.w/ut.h)}}catch{}const{w:Y,h:ae}=Fi(),_e=Ke,Me=vt,Ce=Math.max(Tt,Y-_e-Tt),$e=Math.max(Tt,ae-Me-Tt);return li({x:Ce,y:$e,w:_e,h:Me},_e/Me)},[li]),[$i,Hi]=_.useState(()=>$s()),ii=re&&$i.w<380,Ht=_.useCallback(Y=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Te,JSON.stringify(Y))}catch{}},[]),Kt=_.useRef($i);_.useEffect(()=>{Kt.current=$i},[$i]),_.useEffect(()=>{re&&Hi($s())},[re,$s]),_.useEffect(()=>{if(!re)return;const Y=()=>Hi(ae=>li(ae,ae.w/ae.h));return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[re,li]);const Ui=_.useRef(null);_.useEffect(()=>{const Y=ft.current;if(!(!Y||Y.isDisposed?.()))return Ui.current!=null&&cancelAnimationFrame(Ui.current),Ui.current=requestAnimationFrame(()=>{Ui.current=null;try{Y.trigger("resize")}catch{}}),()=>{Ui.current!=null&&(cancelAnimationFrame(Ui.current),Ui.current=null)}},[re,$i.w,$i.h]);const[rs,mn]=_.useState(!1),[_n,je]=_.useState(!1),gt=_.useRef(null),Ct=_.useRef(null),Vt=_.useRef(null),Bt=_.useCallback(Y=>{const{w:ae,h:_e}=Fi(),Me=Tt,Ce=ae-Y.w-Tt,$e=_e-Y.h-Tt,ut=Y.x+Y.w/2{const ae=Vt.current;if(!ae)return;const _e=Y.clientX-ae.sx,Me=Y.clientY-ae.sy,Ce=ae.start,$e=li({x:Ce.x+_e,y:Ce.y+Me,w:Ce.w,h:Ce.h});Ct.current={x:$e.x,y:$e.y},gt.current==null&&(gt.current=requestAnimationFrame(()=>{gt.current=null;const tt=Ct.current;tt&&Hi(ut=>({...ut,x:tt.x,y:tt.y}))}))},[li]),Ut=_.useCallback(()=>{Vt.current&&(je(!1),gt.current!=null&&(cancelAnimationFrame(gt.current),gt.current=null),Vt.current=null,window.removeEventListener("pointermove",mi),window.removeEventListener("pointerup",Ut),Hi(Y=>{const ae=Bt(li(Y));return queueMicrotask(()=>Ht(ae)),ae}))},[mi,Bt,li,Ht]),zi=_.useCallback(Y=>{if(!re||rs||Y.button!==0)return;Y.preventDefault(),Y.stopPropagation();const ae=Kt.current;Vt.current={sx:Y.clientX,sy:Y.clientY,start:ae},je(!0),window.addEventListener("pointermove",mi),window.addEventListener("pointerup",Ut)},[re,rs,mi,Ut]),Si=_.useRef(null),Ss=_.useRef(null),ks=_.useRef(null),Ys=_.useCallback(Y=>{const ae=ks.current;if(!ae)return;const _e=Y.clientX-ae.sx,Me=Y.clientY-ae.sy,Ce=ae.ratio,$e=ae.dir.includes("w"),tt=ae.dir.includes("e"),ut=ae.dir.includes("n"),Qe=ae.dir.includes("s");let at=ae.start.w,pt=ae.start.h,Mt=ae.start.x,Nt=ae.start.y;const{w:Ft,h:Xt}=Fi(),zt=24,ui=ae.start.x+ae.start.w,un=ae.start.y+ae.start.h,Ps=Math.abs(Ft-Tt-ui)<=zt,Es=Math.abs(Xt-Tt-un)<=zt,zr=xs=>{xs=Math.max(Li,xs);let Xs=xs/Ce;return Xs{xs=Math.max(bi,xs);let Xs=xs*Ce;return Xs=Math.abs(Me)){const Xs=tt?ae.start.w+_e:ae.start.w-_e,{newW:sa,newH:Ol}=zr(Xs);at=sa,pt=Ol}else{const Xs=Qe?ae.start.h+Me:ae.start.h-Me,{newW:sa,newH:Ol}=pn(Xs);at=sa,pt=Ol}$e&&(Mt=ae.start.x+(ae.start.w-at)),ut&&(Nt=ae.start.y+(ae.start.h-pt))}else if(tt||$e){const xs=tt?ae.start.w+_e:ae.start.w-_e,{newW:Xs,newH:sa}=zr(xs);at=Xs,pt=sa,$e&&(Mt=ae.start.x+(ae.start.w-at)),Nt=Es?ae.start.y+(ae.start.h-pt):ae.start.y}else if(ut||Qe){const xs=Qe?ae.start.h+Me:ae.start.h-Me,{newW:Xs,newH:sa}=pn(xs);at=Xs,pt=sa,ut&&(Nt=ae.start.y+(ae.start.h-pt)),Ps?Mt=ae.start.x+(ae.start.w-at):Mt=ae.start.x}const Za=li({x:Mt,y:Nt,w:at,h:pt},Ce);Ss.current=Za,Si.current==null&&(Si.current=requestAnimationFrame(()=>{Si.current=null;const xs=Ss.current;xs&&Hi(xs)}))},[li]),En=_.useCallback(()=>{ks.current&&(mn(!1),Si.current!=null&&(cancelAnimationFrame(Si.current),Si.current=null),ks.current=null,window.removeEventListener("pointermove",Ys),window.removeEventListener("pointerup",En),Ht(Kt.current))},[Ys,Ht]),as=_.useCallback(Y=>ae=>{if(!re||ae.button!==0)return;ae.preventDefault(),ae.stopPropagation();const _e=Kt.current;ks.current={dir:Y,sx:ae.clientX,sy:ae.clientY,start:_e,ratio:_e.w/_e.h},mn(!0),window.addEventListener("pointermove",Ys),window.addEventListener("pointerup",En)},[re,Ys,En]),[Cs,Mn]=_.useState(!1),[hs,Wi]=_.useState(!1);_.useEffect(()=>{const Y=window.matchMedia?.("(hover: hover) and (pointer: fine)"),ae=()=>Mn(!!Y?.matches);return ae(),Y?.addEventListener?.("change",ae),()=>Y?.removeEventListener?.("change",ae)},[]);const Yi=re&&(hs||_n||rs),[_s,Zn]=_.useState(!1);if(_.useEffect(()=>{s.status!=="running"&&Zn(!1)},[s.id,s.status]),!It||!As)return null;const Pn="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",wn=String(s.phase??"").toLowerCase(),vs=wn==="stopping"||wn==="remuxing"||wn==="moving",Ji=!E||!q||vs||_s,Tr=g.jsx("div",{className:"flex items-center gap-1 min-w-0",children:q?g.jsxs(g.Fragment,{children:[g.jsx(oi,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:Ji,title:vs||_s?"Stoppe…":"Stop","aria-label":vs||_s?"Stoppe…":"Stop",onClick:async Y=>{if(Y.preventDefault(),Y.stopPropagation(),!Ji)try{Zn(!0),await E?.(s.id)}finally{Zn(!1)}},className:xo("shadow-none shrink-0",re&&ii&&"px-2"),children:g.jsx("span",{className:"whitespace-nowrap",children:vs||_s?"Stoppe…":re&&ii?"Stop":"Stoppen"})}),g.jsx(za,{job:s,variant:"overlay",collapseToMenu:!0,busy:vs||_s,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:S?Y=>S(Y):void 0,onToggleFavorite:v?Y=>v(Y):void 0,onToggleLike:b?Y=>b(Y):void 0,order:["watch","favorite","like","details"],className:"gap-1 min-w-0 flex-1"})]}):g.jsx(za,{job:s,variant:"overlay",collapseToMenu:!0,isHot:a||ie,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:S?Y=>S(Y):void 0,onToggleFavorite:v?Y=>v(Y):void 0,onToggleLike:b?Y=>b(Y):void 0,onToggleHot:y?async Y=>{ai(),await new Promise(_e=>setTimeout(_e,150)),await y(Y),await new Promise(_e=>setTimeout(_e,0));const ae=ft.current;if(ae&&!ae.isDisposed?.()){const _e=ae.play?.();_e&&typeof _e.catch=="function"&&_e.catch(()=>{})}}:void 0,onKeep:f?async Y=>{ai(),t(),await new Promise(ae=>setTimeout(ae,150)),await f(Y)}:void 0,onDelete:p?async Y=>{ai(),t(),await new Promise(ae=>setTimeout(ae,150)),await p(Y)}:void 0,order:["watch","favorite","like","hot","keep","delete","details"],className:"gap-1 min-w-0 flex-1"})}),Ds=e||re,Ee="env(safe-area-inset-bottom)",Ie=`calc(${Mi}px + env(safe-area-inset-bottom))`,Ue=q?Ee:Ie,it=q?"calc(8px + env(safe-area-inset-bottom))":`calc(${Mi+8}px + env(safe-area-inset-bottom))`,St=re?"top-4":"top-2",ei=e&&Z,Yt=g.jsx("div",{className:xo("relative overflow-visible",e||re?"flex-1 min-h-0":"aspect-video"),onMouseEnter:()=>{!re||!Cs||Wi(!0)},onMouseLeave:()=>{!re||!Cs||Wi(!1)},children:g.jsxs("div",{className:xo("relative w-full h-full",re&&"vjs-mini"),children:[q?g.jsxs("div",{className:"absolute inset-0 bg-black",children:[g.jsx(pR,{src:Ze,muted:L,className:"w-full h-full object-contain"}),g.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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]})]}):g.jsx("div",{ref:xt,className:"absolute inset-0"}),g.jsx("div",{className:xo("absolute inset-x-2 z-30",St),children:g.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-2",children:[g.jsx("div",{className:"min-w-0 pointer-events-auto overflow-visible",children:ei?null:Tr}),re?g.jsxs("button",{type:"button","aria-label":"Player-Fenster verschieben",title:"Ziehen zum Verschieben",onPointerDown:zi,onClick:Y=>{Y.preventDefault(),Y.stopPropagation()},className:xo(Pn,"px-3 gap-1 cursor-grab active:cursor-grabbing select-none",Yi?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none -translate-y-1",_n&&"scale-[0.98] opacity-90"),children:[g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"}),g.jsx("span",{className:"h-1 w-1 rounded-full bg-black/35 dark:bg-white/35"})]}):null,g.jsxs("div",{className:"shrink-0 flex items-center gap-1 pointer-events-auto",children:[g.jsx("button",{type:"button",className:Pn,onClick:i,"aria-label":e?"Minimieren":"Maximieren",title:e?"Minimieren":"Maximieren",children:e?g.jsx(RO,{className:"h-5 w-5"}):g.jsx(NO,{className:"h-5 w-5"})}),g.jsx("button",{type:"button",className:Pn,onClick:t,"aria-label":"Schließen",title:"Schließen",children:g.jsx(p0,{className:"h-5 w-5"})})]})]})}),g.jsx("div",{className:xo("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:Ue}}),g.jsxs("div",{className:xo("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:it},children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white",children:oe}),g.jsx("div",{className:"truncate text-[11px] text-white/80",children:g.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0 align-middle",children:[g.jsx("span",{className:"truncate",children:j||N}),a||ie?g.jsx("span",{className:"shrink-0 rounded bg-amber-500/25 px-1.5 py-0.5 font-semibold text-white",children:"HOT"}):null]})})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 text-[11px] text-white",children:[At!=="—"?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:At}):null,q?null:g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:X}),F!=="—"?g.jsx("span",{className:"rounded bg-black/40 px-1.5 py-0.5 font-medium",children:F}):null]})]})]})}),Ri=g.jsx("div",{className:"w-[360px] shrink-0 border-r border-white/10 bg-black/40 text-white",children:g.jsxs("div",{className:"h-full p-4 flex flex-col gap-3 overflow-y-auto",children:[g.jsx("div",{className:"rounded-lg overflow-hidden ring-1 ring-white/10 bg-black/30",children:g.jsx("div",{className:"relative aspect-video",children:g.jsx("img",{src:Je,alt:"Vorschau",className:"absolute inset-0 h-full w-full object-cover",loading:"lazy",onError:()=>{Je!==Ve&&Pe(Ve)}})})}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("div",{className:"text-lg font-semibold truncate",children:oe}),g.jsx("div",{className:"text-xs text-white/70 break-all",children:j||N})]}),g.jsx("div",{className:"pointer-events-auto",children:g.jsxs("div",{className:"flex items-center justify-center gap-2 flex-wrap",children:[q?g.jsx(oi,{variant:"primary",color:"red",size:"sm",rounded:"md",disabled:Ji,title:vs||_s?"Stoppe…":"Stop","aria-label":vs||_s?"Stoppe…":"Stop",onClick:async Y=>{if(Y.preventDefault(),Y.stopPropagation(),!Ji)try{Zn(!0),await E?.(s.id)}finally{Zn(!1)}},className:"shadow-none",children:vs||_s?"Stoppe…":"Stoppen"}):null,g.jsx(za,{job:s,variant:"table",collapseToMenu:!1,busy:vs||_s,isHot:a||ie,isFavorite:u,isLiked:c,isWatching:d,onToggleWatch:S?Y=>S(Y):void 0,onToggleFavorite:v?Y=>v(Y):void 0,onToggleLike:b?Y=>b(Y):void 0,onToggleHot:y?async Y=>{ai(),await new Promise(_e=>setTimeout(_e,150)),await y(Y),await new Promise(_e=>setTimeout(_e,0));const ae=ft.current;if(ae&&!ae.isDisposed?.()){const _e=ae.play?.();_e&&typeof _e.catch=="function"&&_e.catch(()=>{})}}:void 0,onKeep:f?async Y=>{ai(),t(),await new Promise(ae=>setTimeout(ae,150)),await f(Y)}:void 0,onDelete:p?async Y=>{ai(),t(),await new Promise(ae=>setTimeout(ae,150)),await p(Y)}:void 0,order:q?["watch","favorite","like","details"]:["watch","favorite","like","hot","details","keep","delete"],className:"flex items-center justify-start gap-1"})]})}),g.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-2 text-sm",children:[g.jsx("div",{className:"text-white/60",children:"Status"}),g.jsx("div",{className:"font-medium",children:s.status}),g.jsx("div",{className:"text-white/60",children:"Auflösung"}),g.jsx("div",{className:"font-medium",children:At}),g.jsx("div",{className:"text-white/60",children:"FPS"}),g.jsx("div",{className:"font-medium",children:lt}),g.jsx("div",{className:"text-white/60",children:"Laufzeit"}),g.jsx("div",{className:"font-medium",children:X}),g.jsx("div",{className:"text-white/60",children:"Größe"}),g.jsx("div",{className:"font-medium",children:F}),g.jsx("div",{className:"text-white/60",children:"Datum"}),g.jsx("div",{className:"font-medium",children:se}),g.jsx("div",{className:"col-span-2",children:pe.length?g.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(Y=>g.jsx("span",{className:"rounded bg-white/10 px-2 py-0.5 text-xs text-white/90",children:Y},Y))}):g.jsx("span",{className:"text-white/50",children:"—"})})]})]})}),Ti=g.jsx(fa,{edgeToEdgeMobile:!0,noBodyPadding:!0,className:xo("relative flex flex-col shadow-2xl ring-1 ring-black/10 dark:ring-white/10","w-full",Ds?"h-full":"h-[220px] max-h-[40vh]",e?"rounded-2xl":re?"rounded-lg":"rounded-none"),bodyClassName:"flex flex-col flex-1 min-h-0 p-0",children:g.jsxs("div",{className:"flex flex-1 min-h-0",children:[ei?Ri:null,Yt]})}),{w:Bn,h:An,ox:Fn,oy:Ls,bottomInset:ve}=Fi(),we={left:Fn+16,top:Ls+16,width:Math.max(0,Bn-32),height:Math.max(0,An-32)},ke=e?we:re?{left:$i.x,top:$i.y,width:$i.w,height:$i.h}:void 0;return Oc.createPortal(g.jsxs(g.Fragment,{children:[g.jsx("style",{children:` /* Live-Download: Progress/Seek-Bar ausblenden */ .is-live-download .vjs-progress-control { display: none !important; } `}),e||re?g.jsxs("div",{className:xo("fixed z-[2147483647]",!rs&&!_n&&"transition-[left,top,width,height] duration-300 ease-[cubic-bezier(.2,.9,.2,1)]"),style:{...ke,willChange:rs?"left, top, width, height":void 0},children:[Ti,re?g.jsxs("div",{className:"pointer-events-none absolute inset-0",children:[g.jsx("div",{className:"pointer-events-auto absolute -left-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:as("w")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 bottom-2 top-2 w-3 cursor-ew-resize",onPointerDown:as("e")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -top-1 h-3 cursor-ns-resize",onPointerDown:as("n")}),g.jsx("div",{className:"pointer-events-auto absolute left-2 right-2 -bottom-1 h-3 cursor-ns-resize",onPointerDown:as("s")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -top-1 h-4 w-4 cursor-nwse-resize",onPointerDown:as("nw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -top-1 h-4 w-4 cursor-nesw-resize",onPointerDown:as("ne")}),g.jsx("div",{className:"pointer-events-auto absolute -left-1 -bottom-1 h-4 w-4 cursor-nesw-resize",onPointerDown:as("sw")}),g.jsx("div",{className:"pointer-events-auto absolute -right-1 -bottom-1 h-4 w-4 cursor-nwse-resize",onPointerDown:as("se")})]}):null]}):g.jsx("div",{className:`\r fixed z-[2147483647] inset-x-0 w-full\r shadow-2xl\r 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\r `,style:{bottom:`calc(${ve}px + env(safe-area-inset-bottom))`},children:Ti})]}),As)}function gR({jobId:s,thumbTick:e,autoTickMs:t=1e4,blur:i=!1,alignStartAt:n,alignEndAt:r=null,alignEveryMs:a,fastRetryMs:u,fastRetryMax:c,fastRetryWindowMs:d,className:f}){const p=i?"blur-md":"",y=_.useRef(null),v=_.useRef(!0),[b,S]=_.useState(!1),E=_.useRef(!1),[L,N]=_.useState(0),[R,H]=_.useState(!1),F=_.useRef(null),$=_.useRef(0),M=_.useRef(!1),W=_.useRef(!1),D=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(V instanceof Date)return V.getTime();const G=Date.parse(String(V??""));return Number.isFinite(G)?G:NaN};_.useEffect(()=>{const V=()=>{v.current=!document.hidden};return v.current=!document.hidden,document.addEventListener("visibilitychange",V),()=>document.removeEventListener("visibilitychange",V)},[]),_.useEffect(()=>()=>{F.current&&window.clearTimeout(F.current)},[]),_.useEffect(()=>{const V=y.current;if(!V)return;const G=new IntersectionObserver(J=>{const ie=J[0],oe=!!(ie&&(ie.isIntersecting||ie.intersectionRatio>0));oe!==E.current&&(E.current=oe,S(oe))},{root:null,threshold:0,rootMargin:"300px 0px"});return G.observe(V),()=>G.disconnect()},[]),_.useEffect(()=>{typeof e!="number"&&b&&v.current&&(W.current||(W.current=!0,N(V=>V+1)))},[b,e]),_.useEffect(()=>{if(typeof e=="number"||!b||!v.current)return;const V=Number(a??t??1e4);if(!Number.isFinite(V)||V<=0)return;const G=n?D(n):NaN,J=r?D(r):NaN;if(Number.isFinite(G)){let oe;const j=()=>{if(!v.current)return;const X=Date.now();if(Number.isFinite(J)&&X>=J)return;const fe=Math.max(0,X-G)%V,pe=fe===0?V:V-fe;oe=window.setTimeout(()=>{E.current&&v.current&&(N(de=>de+1),j())},pe)};return j(),()=>{oe&&window.clearTimeout(oe)}}const ie=window.setInterval(()=>{E.current&&v.current&&N(oe=>oe+1)},V);return()=>window.clearInterval(ie)},[e,t,b,n,r,a]);const I=typeof e=="number"?e:L,Q=_.useRef(0),[K,q]=_.useState(0);_.useEffect(()=>{b&&v.current&&(Q.current=I,q(I))},[I,b]),_.useEffect(()=>{H(!1)},[K]),_.useEffect(()=>{M.current=!1,$.current=0,W.current=!1,H(!1),E.current&&v.current&&N(V=>V+1)},[s]);const le=_.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&v=${K}`,[s,K]),te=_.useMemo(()=>`/api/record/preview?id=${encodeURIComponent(s)}&hover=1&file=index_hq.m3u8`,[s]);return g.jsx(KA,{content:(V,{close:G})=>V&&g.jsx("div",{className:"w-[420px] max-w-[calc(100vw-1.5rem)]",children:g.jsxs("div",{className:"relative aspect-video overflow-hidden rounded-lg bg-black",children:[g.jsx(pR,{src:te,muted:!1,className:"w-full h-full relative z-0"}),g.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:[g.jsx("span",{className:"inline-block size-1.5 rounded-full bg-white animate-pulse"}),"Live"]}),g.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(),G()},children:g.jsx(p0,{className:"h-4 w-4"})})]})}),children:g.jsx("div",{ref:y,className:["block relative rounded bg-gray-100 dark:bg-white/5 overflow-hidden",f||"w-full h-full"].join(" "),children:R?g.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"}):g.jsx("img",{src:le,loading:b?"eager":"lazy",fetchPriority:b?"high":"auto",decoding:"async",alt:"",className:["block w-full h-full object-cover object-center",p].filter(Boolean).join(" "),onLoad:()=>{M.current=!0,$.current=0,F.current&&window.clearTimeout(F.current),H(!1)},onError:()=>{if(H(!0),!u||!E.current||!v.current||M.current)return;const V=n?D(n):NaN,G=Number(d??6e4);if(!(!Number.isFinite(V)||Date.now()-V=ie||(F.current&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{$.current+=1,N(oe=>oe+1)},u))}})})})}function Vh({label:s,value:e=0,indeterminate:t=!1,showPercent:i=!1,rightLabel:n,steps:r,currentStep:a,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,y=p?r.length:0,v=E=>E===0?"text-left":E===y-1?"text-right":"text-center",b=E=>typeof a!="number"||!Number.isFinite(a)?!1:E<=a,S=i&&!t;return g.jsxs("div",{className:c,children:[s||S?g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s?g.jsx("p",{className:"flex-1 min-w-0 truncate text-xs font-medium text-gray-900 dark:text-white",children:s}):g.jsx("span",{className:"flex-1"}),S?g.jsxs("span",{className:"shrink-0 text-xs font-medium text-gray-700 dark:text-gray-300",children:[Math.round(d),"%"]}):null]}):null,g.jsxs("div",{"aria-hidden":"true",className:s||S?"mt-2":"",children:[g.jsx("div",{className:"overflow-hidden rounded-full bg-gray-200 dark:bg-white/10",children:t?g.jsx("div",{className:`${f} w-full rounded-full bg-indigo-600/70 dark:bg-indigo-500/70 animate-pulse`}):g.jsx("div",{className:`${f} rounded-full bg-indigo-600 dark:bg-indigo-500 transition-[width] duration-200`,style:{width:`${d}%`}})}),n?g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:n}):null,p?g.jsx("div",{className:"mt-3 hidden text-sm font-medium text-gray-600 sm:grid dark:text-gray-400",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:r.map((E,L)=>g.jsx("div",{className:[v(L),b(L)?"text-indigo-600 dark:text-indigo-400":""].join(" "),children:E},`${L}-${E}`))}):null]})]})}function I$(s){const[e,t]=_.useState(s),i=_.useRef(s.length);return _.useEffect(()=>{const n=ap("/api/record/stream","jobs",r=>{Array.isArray(r)&&(r.length,i.current,i.current=r.length,t(r))});return()=>n()},[]),e}const Y0=s=>{const e=s;return e.modelName??e.model??e.modelKey??e.username??e.name??"—"},yR=s=>{const e=s;return e.sourceUrl??e.url??e.roomUrl??""},vR=s=>{const e=s;return String(e.imageUrl??e.image_url??"").trim()},dc=s=>{const e=s;return String(e.key??e.id??Y0(s))},Ks=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},hc=s=>{if(s.kind==="job"){const t=s.job;return Ks(t.addedAt)||Ks(t.createdAt)||Ks(t.enqueuedAt)||Ks(t.queuedAt)||Ks(t.requestedAt)||Ks(t.startedAt)||0}const e=s.pending;return Ks(e.addedAt)||Ks(e.createdAt)||Ks(e.enqueuedAt)||Ks(e.queuedAt)||Ks(e.requestedAt)||0},xR=s=>{switch((s??"").toLowerCase()){case"stopping":return"Stop wird angefordert…";case"probe":return"Analysiere Datei (Dauer/Streams)…";case"remuxing":return"Konvertiere Container zu MP4…";case"moving":return"Verschiebe nach Done…";case"assets":return"Erstelle Vorschau/Thumbnails…";case"postwork":return"Nacharbeiten laufen…";default:return""}};async function N$(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 bR(s,e){const t=s.postWork;if(!t)return"Warte auf Nacharbeiten…";if(t.state==="running"){const i=typeof t.running=="number"?t.running:0,n=typeof t.maxParallel=="number"?t.maxParallel:0;return n>0?`Nacharbeiten laufen… (${i}/${n} parallel)`:"Nacharbeiten laufen…"}if(t.state==="queued"){const i=typeof t.position=="number"?t.position:0,n=typeof t.waiting=="number"?t.waiting:0,r=typeof t.running=="number"?t.running:0,a=Math.max(n+r,i),u=typeof e?.pos=="number"&&Number.isFinite(e.pos)&&e.pos>0?e.pos:i,c=typeof e?.total=="number"&&Number.isFinite(e.total)&&e.total>0?e.total:a;return u>0&&c>0?`Warte auf Nacharbeiten… ${u} / ${c}`:"Warte auf Nacharbeiten…"}return"Warte auf Nacharbeiten…"}function O$({job:s,postworkInfo:e}){const t=String(s?.phase??"").trim(),i=Number(s?.progress??0),n=t.toLowerCase(),r=n==="recording";let a=t?xR(t)||t:"";n==="postwork"&&(a=bR(s,e)),r&&(a="Recording läuft…");const u=a||String(s?.status??"").trim().toLowerCase(),c=!r&&Number.isFinite(i)&&i>0&&i<100,d=!r&&!c&&!!t&&(!Number.isFinite(i)||i<=0||i>=100);return g.jsx("div",{className:"min-w-0",children:c?g.jsx(Vh,{label:u,value:Math.max(0,Math.min(100,i)),showPercent:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):d?g.jsx(Vh,{label:u,indeterminate:!0,size:"sm",className:"w-full min-w-0 sm:min-w-[220px]"}):g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:u})})})}function Gv({r:s,nowMs:e,blurPreviews:t,modelsByKey:i,stopRequestedIds:n,postworkInfoOf:r,markStopRequested:a,onOpenPlayer:u,onStopJob:c,onToggleFavorite:d,onToggleLike:f,onToggleWatch:p}){if(s.kind==="pending"){const G=s.pending,J=Y0(G),ie=yR(G),oe=(G.currentShow||"unknown").toLowerCase();return g.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:[g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",title:J,children:J}),g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[g.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"}),g.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:oe})]})]}),g.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:"⏳"})]}),g.jsx("div",{className:"mt-3",children:(()=>{const j=vR(G);return g.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:j?g.jsx("img",{src:j,alt:J,className:["h-full w-full object-cover",t?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:X=>{X.currentTarget.style.display="none"}}):g.jsx("div",{className:"grid h-full w-full place-items-center",children:g.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-300",children:"Waiting…"})})})})()}),ie?g.jsx("a",{href:ie,target:"_blank",rel:"noreferrer",className:"mt-3 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:j=>j.stopPropagation(),title:ie,children:ie}):null]})]})}const y=s.job,v=nb(y.output),b=w1(y.output||""),S=String(y.phase??"").trim(),E=S.toLowerCase(),L=E==="recording",N=!!n[y.id],R=String(y.status??"").toLowerCase(),F=E!==""&&E!=="recording"||R!=="running"||N;let $=S?xR(S)||S:"";E==="recording"?$="Recording läuft…":E==="postwork"&&($=bR(y,r(y)));const M=R||"unknown",W=$||M,D=Number(y.progress??0),I=!L&&Number.isFinite(D)&&D>0&&D<100,Q=!L&&!I&&!!S&&(!Number.isFinite(D)||D<=0||D>=100),K=v&&v!=="—"?v.toLowerCase():"",q=K?i[K]:void 0,le=!!q?.favorite,te=q?.liked===!0,V=!!q?.watching;return g.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:()=>u(y),role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&u(y)},children:[g.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"}),g.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"}),g.jsxs("div",{className:"relative p-3",children:[g.jsxs("div",{className:"flex items-start gap-3",children:[g.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:g.jsx(gR,{jobId:y.id,blur:t,alignStartAt:y.startedAt,alignEndAt:y.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"truncate text-base font-semibold text-gray-900 dark:text-white",title:v,children:v}),g.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",F?"ring-1 ring-amber-500/30":"ring-1 ring-emerald-500/25"].join(" "),title:M,children:M})]}),g.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-600 dark:text-gray-300",title:y.output,children:b||"—"})]}),g.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-1",children:[g.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:TR(y,e)}),g.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:_R(SR(y))})]})]}),y.sourceUrl?g.jsx("a",{href:y.sourceUrl,target:"_blank",rel:"noreferrer",className:"mt-1 block truncate text-xs text-indigo-600 hover:underline dark:text-indigo-400",onClick:G=>G.stopPropagation(),title:y.sourceUrl,children:y.sourceUrl}):null]})]}),I||Q?g.jsx("div",{className:"mt-3",children:I?g.jsx(Vh,{label:W,value:Math.max(0,Math.min(100,D)),showPercent:!0,size:"sm",className:"w-full"}):g.jsx(Vh,{label:W,indeterminate:!0,size:"sm",className:"w-full"})}):null,g.jsxs("div",{className:"mt-3 flex items-center justify-between gap-2 border-t border-white/30 pt-3 dark:border-white/10",children:[g.jsx("div",{className:"flex items-center gap-1",onClick:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),children:g.jsx(za,{job:y,variant:"table",busy:F,isFavorite:le,isLiked:te,isWatching:V,onToggleFavorite:d,onToggleLike:f,onToggleWatch:p,order:["watch","favorite","like","details"],className:"flex items-center gap-1"})}),g.jsx(oi,{size:"sm",variant:"primary",disabled:F,className:"shrink-0",onClick:G=>{G.stopPropagation(),!F&&(a(y.id),c(y.id))},children:F?"Stoppe…":"Stop"})]})]})]})}const w1=s=>(s||"").replaceAll("\\","/").trim().split("/").pop()||"",nb=s=>{const e=w1(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},M$=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`},TR=(s,e)=>{const t=s,i=Ks(t.startedAtMs)||Ks(s.startedAt);if(!Number.isFinite(i)||i<=0)return"—";const n=s.endedAt?Ks(t.endedAtMs)||Ks(s.endedAt):e;return!Number.isFinite(n)||n<=0?"—":M$(n-i)},SR=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},_R=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]}`},Vv=s=>{const e=s,t=String(e.phase??"").trim(),i=e.postWork;return!!(String(e.postWorkKey??"").trim()||i&&(i.state==="queued"||i.state==="running")||s.endedAt&&t||t==="postwork")},sA=s=>{const e=String(s??"").trim().toLowerCase();return e==="stopped"||e==="finished"||e==="failed"||e==="done"||e==="completed"||e==="canceled"||e==="cancelled"};function P$({jobs:s,pending:e=[],onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,modelsByKey:c={},blurPreviews:d}){const f=I$(s),[p,y]=_.useState(!1),[v,b]=_.useState(!1),S=_.useRef(null),[E,L]=_.useState(!1),N=_.useCallback(async()=>{try{const se=!!(await N$("/api/autostart/state",{cache:"no-store"}))?.paused;S.current=se,b(se)}catch{}},[]);_.useEffect(()=>{N();const X=ap("/api/autostart/state/stream","autostart",se=>{const fe=!!se?.paused;S.current!==fe&&(S.current=fe,b(fe))});return()=>{X()}},[N]);const R=_.useCallback(async()=>{if(!(E||v)){L(!0);try{await fetch("/api/autostart/pause",{method:"POST"}),b(!0)}catch{}finally{L(!1)}}},[E,v]),H=_.useCallback(async()=>{if(!(E||!v)){L(!0);try{await fetch("/api/autostart/resume",{method:"POST"}),b(!1)}catch{}finally{L(!1)}}},[E,v]),[F,$]=_.useState({}),[M,W]=_.useState({}),D=_.useCallback(X=>{const se=Array.isArray(X)?X:[X];$(fe=>{const pe={...fe};for(const de of se)de&&(pe[de]=!0);return pe}),W(fe=>{const pe={...fe};for(const de of se)de&&(pe[de]=!0);return pe})},[]);_.useEffect(()=>{$(X=>{const se=Object.keys(X);if(se.length===0)return X;const fe={};for(const pe of se){const de=f.find(Pe=>Pe.id===pe);if(!de)continue;const Ve=String(de.phase??"").trim().toLowerCase();Ve!==""&&Ve!=="recording"||de.status!=="running"||(fe[pe]=!0)}return fe})},[f]);const[I,Q]=_.useState(()=>Date.now()),K=_.useMemo(()=>f.some(X=>!X.endedAt&&X.status==="running"),[f]),q=_.useMemo(()=>{const X=new Map,se=Ze=>{const Je=Ze,Pe=Je.postWork;return Ks(Pe?.enqueuedAt)||Ks(Je.enqueuedAt)||Ks(Je.queuedAt)||Ks(Je.createdAt)||Ks(Je.addedAt)||Ks(Ze.endedAt)||Ks(Ze.startedAt)||0},fe=[],pe=[];for(const Ze of f){const Je=Ze?.postWork;if(!Je)continue;const Pe=String(Je.state??"").toLowerCase();Pe==="running"?fe.push(Ze):Pe==="queued"&&pe.push(Ze)}fe.sort((Ze,Je)=>se(Ze)-se(Je)),pe.sort((Ze,Je)=>se(Ze)-se(Je));const de=fe.length,Ve=de+pe.length;for(let Ze=0;Ze{const se=String(X?.id??"");return se?q.get(se):void 0},[q]);_.useEffect(()=>{if(!K)return;const X=window.setInterval(()=>Q(Date.now()),1e3);return()=>window.clearInterval(X)},[K]);const te=_.useMemo(()=>f.filter(X=>{if(Vv(X)||X.endedAt)return!1;const se=String(X.phase??"").trim(),fe=!!F[X.id],pe=se.trim().toLowerCase();return!(pe!==""&&pe!=="recording"||X.status!=="running"||fe)}).map(X=>X.id),[f,F]),V=_.useMemo(()=>[{key:"preview",header:"Vorschau",widthClassName:"w-[96px]",cell:X=>{if(X.kind==="job"){const de=X.job;return g.jsx("div",{className:"grid w-[96px] h-[60px] overflow-hidden rounded-md",children:g.jsx(gR,{jobId:de.id,blur:d,alignStartAt:de.startedAt,alignEndAt:de.endedAt??null,alignEveryMs:1e4,fastRetryMs:1e3,fastRetryMax:25,fastRetryWindowMs:6e4,className:"w-full h-full"})})}const se=X.pending,fe=Y0(se),pe=vR(se);return pe?g.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:g.jsx("img",{src:pe,alt:fe,className:["h-full w-full object-cover",d?"blur-md":""].join(" "),loading:"lazy",referrerPolicy:"no-referrer",onError:de=>{de.currentTarget.style.display="none"}})}):g.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:X=>{if(X.kind==="job"){const de=X.job,Ve=w1(de.output||""),Ze=nb(de.output),Je=String(de.status??"").toLowerCase(),Pe=!!F[de.id],Fe=!!M[de.id],qe=Je==="stopped"||Fe&&!!de.endedAt,dt=qe?"stopped":Je||"unknown",Ge=!qe&&Pe,At=Ge?"stopping":dt;return g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("span",{className:"min-w-0 block max-w-[170px] truncate font-medium",title:Ze,children:Ze}),g.jsx("span",{className:["shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1",Je==="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":qe?"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":Je==="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":Je==="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":Ge?"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:At,children:At})]}),g.jsx("span",{className:"block max-w-[220px] truncate",title:de.output,children:Ve}),de.sourceUrl?g.jsx("a",{href:de.sourceUrl,target:"_blank",rel:"noreferrer",title:de.sourceUrl,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:lt=>lt.stopPropagation(),children:de.sourceUrl}):g.jsx("span",{className:"block max-w-[260px] truncate text-gray-500 dark:text-gray-400",children:"—"})]})}const se=X.pending,fe=Y0(se),pe=yR(se);return g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"block max-w-[170px] truncate font-medium",title:fe,children:fe}),pe?g.jsx("a",{href:pe,target:"_blank",rel:"noreferrer",title:pe,className:"block max-w-[260px] truncate text-indigo-600 dark:text-indigo-400 hover:underline",onClick:de=>de.stopPropagation(),children:pe}):g.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:X=>{if(X.kind==="job"){const pe=X.job;return g.jsx(O$,{job:pe,postworkInfo:le(pe)})}const fe=(X.pending.currentShow||"unknown").toLowerCase();return g.jsx("div",{className:"min-w-0",children:g.jsx("div",{className:"truncate",children:g.jsx("span",{className:"font-medium",children:fe})})})}},{key:"runtime",header:"Dauer",widthClassName:"w-[90px]",cell:X=>X.kind==="job"?TR(X.job,I):"—"},{key:"size",header:"Größe",align:"right",widthClassName:"w-[110px]",cell:X=>X.kind==="job"?g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white",children:_R(SR(X.job))}):g.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:X=>{if(X.kind!=="job")return g.jsx("div",{className:"pr-2 text-right text-sm text-gray-500 dark:text-gray-400",children:"—"});const se=X.job,fe=String(se.phase??"").trim(),pe=!!F[se.id],de=fe.trim().toLowerCase(),Ze=de!==""&&de!=="recording"||se.status!=="running"||pe,Je=nb(se.output||""),Pe=Je&&Je!=="—"?c[Je.toLowerCase()]:void 0,Fe=!!Pe?.favorite,qe=Pe?.liked===!0,dt=!!Pe?.watching;return g.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pr-2",children:[g.jsx(za,{job:se,variant:"table",busy:Ze,isFavorite:Fe,isLiked:qe,isWatching:dt,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a,onAddToDownloads:u,order:["watch","favorite","like","details"],className:"flex items-center gap-1"}),(()=>{const Ge=String(se.phase??"").trim(),At=!!F[se.id],lt=Ge.trim().toLowerCase(),nt=lt!==""&<!=="recording"||se.status!=="running"||At;return g.jsx(oi,{size:"sm",variant:"primary",disabled:nt,className:"shrink-0",onClick:wt=>{wt.stopPropagation(),!nt&&(D(se.id),i(se.id))},children:nt?"Stoppe…":"Stop"})})()]})}}],[d,D,c,I,i,n,r,a,F,M,le]),G=_.useMemo(()=>{const X=f.filter(se=>!(Vv(se)||sA(se?.status)||se?.endedAt)).map(se=>({kind:"job",job:se}));return X.sort((se,fe)=>hc(fe)-hc(se)),X},[f]),J=_.useMemo(()=>{const X=f.filter(se=>!(!Vv(se)||sA(se?.status))).map(se=>({kind:"job",job:se}));return X.sort((se,fe)=>hc(fe)-hc(se)),X},[f]),ie=_.useMemo(()=>{const X=e.map(se=>({kind:"pending",pending:se}));return X.sort((se,fe)=>hc(fe)-hc(se)),X},[e]),oe=G.length+J.length+ie.length,j=_.useCallback(async()=>{if(!p&&te.length!==0){y(!0);try{D(te),await Promise.allSettled(te.map(X=>Promise.resolve(i(X))))}finally{y(!1)}}},[p,te,D,i]);return g.jsxs("div",{className:"grid gap-3",children:[g.jsx("div",{className:"sticky top-[56px] z-20",children:g.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:g.jsxs("div",{className:"flex items-center justify-between gap-2 p-3",children:[g.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:"Downloads"}),g.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:oe})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[g.jsx(oi,{size:"sm",variant:v?"secondary":"primary",disabled:E,onClick:X=>{X.preventDefault(),X.stopPropagation(),v?H():R()},className:"hidden sm:inline-flex",title:v?"Autostart fortsetzen":"Autostart pausieren",leadingIcon:v?g.jsx(kM,{className:"size-4 shrink-0"}):g.jsx(DM,{className:"size-4 shrink-0"}),children:"Autostart"}),g.jsx(oi,{size:"sm",variant:"primary",disabled:p||te.length===0,onClick:X=>{X.preventDefault(),X.stopPropagation(),j()},className:"hidden sm:inline-flex",title:te.length===0?"Nichts zu stoppen":"Alle laufenden stoppen",children:p?"Stoppe alle…":`Alle stoppen (${te.length})`})]})]})})}),G.length>0||J.length>0||ie.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-3 grid gap-4 sm:hidden",children:[G.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Downloads (",G.length,")"]}),G.map(X=>g.jsx(Gv,{r:X,nowMs:I,blurPreviews:d,modelsByKey:c,postworkInfoOf:le,stopRequestedIds:F,markStopRequested:D,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`dl:${X.kind==="job"?X.job.id:dc(X.pending)}`))]}):null,J.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Nacharbeiten (",J.length,")"]}),J.map(X=>g.jsx(Gv,{r:X,nowMs:I,blurPreviews:d,modelsByKey:c,postworkInfoOf:le,stopRequestedIds:F,markStopRequested:D,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`pw:${X.kind==="job"?X.job.id:dc(X.pending)}`))]}):null,ie.length>0?g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"mt-2 text-xs font-semibold text-gray-700 dark:text-gray-200",children:["Wartend (",ie.length,")"]}),ie.map(X=>g.jsx(Gv,{r:X,nowMs:I,blurPreviews:d,modelsByKey:c,postworkInfoOf:le,stopRequestedIds:F,markStopRequested:D,onOpenPlayer:t,onStopJob:i,onToggleFavorite:n,onToggleLike:r,onToggleWatch:a},`wa:${X.kind==="job"?X.job.id:dc(X.pending)}`))]}):null]}),g.jsxs("div",{className:"mt-3 hidden sm:block space-y-4",children:[G.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Downloads (",G.length,")"]}),g.jsx(Sh,{rows:G,columns:V,getRowKey:X=>X.kind==="job"?`dl:job:${X.job.id}`:`dl:pending:${dc(X.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:X=>{X.kind==="job"&&t(X.job)}})]}):null,J.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Nacharbeiten (",J.length,")"]}),g.jsx(Sh,{rows:J,columns:V,getRowKey:X=>X.kind==="job"?`pw:job:${X.job.id}`:`pw:pending:${dc(X.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0,onRowClick:X=>{X.kind==="job"&&t(X.job)}})]}):null,ie.length>0?g.jsxs("div",{className:"overflow-x-auto",children:[g.jsxs("div",{className:"mb-2 text-sm font-semibold text-gray-900 dark:text-white",children:["Wartend (",ie.length,")"]}),g.jsx(Sh,{rows:ie,columns:V,getRowKey:X=>X.kind==="job"?`wa:job:${X.job.id}`:`wa:pending:${dc(X.pending)}`,striped:!0,fullWidth:!0,stickyHeader:!0,compact:!1,card:!0})]}):null]})]}):g.jsx(fa,{grayBody:!0,children:g.jsxs("div",{className:"flex items-center gap-3",children:[g.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:g.jsx("span",{className:"text-lg",children:"⏸️"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Keine laufenden Downloads"}),g.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 Ln(...s){return s.filter(Boolean).join(" ")}function rb({open:s,onClose:e,title:t,children:i,footer:n,icon:r,width:a="max-w-lg",layout:u="single",left:c,leftWidthClass:d="lg:w-80",scroll:f,bodyClassName:p,leftClassName:y,rightClassName:v,rightHeader:b,rightBodyClassName:S,mobileCollapsedImageSrc:E,mobileCollapsedImageAlt:L}){const N=f??(u==="split"?"right":"body"),R=_.useRef(null),[H,F]=_.useState(!1);return _.useEffect(()=>{if(!s)return;const $=document.documentElement,M=document.body,W=$.style.overflow,D=M.style.overflow,I=M.style.paddingRight,Q=window.innerWidth-$.clientWidth;return $.style.overflow="hidden",M.style.overflow="hidden",Q>0&&(M.style.paddingRight=`${Q}px`),()=>{$.style.overflow=W,M.style.overflow=D,M.style.paddingRight=I}},[s]),_.useEffect(()=>{s&&F(!1)},[s]),_.useEffect(()=>{if(!s)return;const $=R.current;if(!$)return;const M=72,W=()=>{const D=$.scrollTop||0;F(I=>{const Q=D>M;return I===Q?I:Q})};return W(),$.addEventListener("scroll",W,{passive:!0}),()=>$.removeEventListener("scroll",W)},[s]),g.jsx(bh,{show:s,as:_.Fragment,children:g.jsxs(xc,{open:s,as:"div",className:"relative z-50",onClose:e,children:[g.jsx(bh.Child,{as:_.Fragment,enter:"ease-out duration-300",enterFrom:"opacity-0",enterTo:"opacity-100",leave:"ease-in duration-200",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:g.jsx("div",{className:"fixed inset-0 bg-gray-500/75 dark:bg-gray-900/50"})}),g.jsx("div",{className:"fixed inset-0 z-50 overflow-hidden px-4 py-6 sm:px-6",children:g.jsx("div",{className:"min-h-full flex items-start justify-center sm:items-center",children:g.jsx(bh.Child,{as:_.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:g.jsxs(xc.Panel,{className:Ln("relative w-full rounded-lg bg-white text-left shadow-xl transition-all","max-h-[calc(100vh-3rem)] sm:max-h-[calc(100vh-4rem)]","flex flex-col min-h-0","dark:bg-gray-800 dark:outline dark:-outline-offset-1 dark:outline-white/10",a),children:[r?g.jsx("div",{className:"mx-auto mb-4 mt-6 flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-500/10",children:r}):null,g.jsxs("div",{className:Ln("shrink-0 px-4 pt-4 sm:px-6 sm:pt-6 items-start justify-between gap-3",u==="split"?"hidden lg:flex":"flex"),children:[g.jsx("div",{className:"min-w-0",children:t?g.jsx(xc.Title,{className:"hidden sm:block text-base font-semibold text-gray-900 dark:text-white truncate",children:t}):null}),g.jsx("button",{type:"button",onClick:e,className:Ln("inline-flex shrink-0 items-center justify-center rounded-lg p-1.5","text-gray-500 hover:text-gray-900 hover:bg-black/5","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600","dark:text-gray-400 dark:hover:text-white dark:hover:bg-white/10 dark:focus-visible:outline-indigo-500"),"aria-label":"Schließen",title:"Schließen",children:g.jsx(p0,{className:"size-5"})})]}),u==="single"?g.jsx("div",{className:Ln("flex-1 min-h-0 h-full",N==="body"?"overflow-y-auto overscroll-contain":"overflow-hidden",v),children:i}):g.jsxs("div",{className:Ln("px-2 pb-4 pt-3 sm:px-4 sm:pb-6 sm:pt-4","flex-1 min-h-0","overflow-hidden","flex flex-col",p),children:[g.jsxs("div",{ref:R,className:Ln("lg:hidden flex-1 min-h-0 relative",N==="right"||N==="body"?"overflow-y-auto overscroll-contain":"overflow-hidden"),children:[g.jsxs("div",{className:Ln("sticky top-0 z-50","bg-white/95 backdrop-blur dark:bg-gray-800/95","border-b border-gray-200/70 dark:border-white/10"),children:[g.jsxs("div",{className:Ln("flex items-center justify-between gap-3 px-3",H?"py-2":"py-3"),children:[g.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[E?g.jsx("img",{src:E,alt:L||t||"",className:Ln("shrink-0 rounded-lg object-cover ring-1 ring-black/5 dark:ring-white/10",H?"size-8":"size-10"),loading:"lazy",decoding:"async"}):null,g.jsx("div",{className:"min-w-0",children:t?g.jsx("div",{className:Ln("truncate font-semibold text-gray-900 dark:text-white",H?"text-sm":"text-base"),children:t}):null})]}),g.jsx("button",{type:"button",onClick:e,className:Ln("inline-flex shrink-0 items-center justify-center rounded-lg p-1.5","text-gray-500 hover:text-gray-900 hover:bg-black/5","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600","dark:text-gray-400 dark:hover:text-white dark:hover:bg-white/10 dark:focus-visible:outline-indigo-500"),"aria-label":"Schließen",title:"Schließen",children:g.jsx(p0,{className:"size-5"})})]}),b?g.jsx("div",{children:b}):null]}),c?g.jsx("div",{className:Ln("lg:hidden px-2 pb-2",y),children:c}):null,g.jsx("div",{className:Ln("px-2 pt-0 min-h-0",v),children:g.jsx("div",{className:Ln("min-h-0",S),children:i})})]}),g.jsxs("div",{className:"hidden lg:flex flex-1 min-h-0 gap-3",children:[g.jsx("div",{className:Ln("min-h-0",d,"shrink-0","overflow-hidden",y),children:c}),g.jsxs("div",{className:Ln("flex-1 min-h-0 flex flex-col",v),children:[b?g.jsx("div",{className:"shrink-0",children:b}):null,g.jsx("div",{className:Ln("flex-1 min-h-0",N==="right"?"overflow-y-auto overscroll-contain":"overflow-hidden",S),children:i})]})]})]}),n?g.jsx("div",{className:"shrink-0 px-6 py-4 border-t border-gray-200/70 dark:border-white/10 flex justify-end gap-3",children:n}):null]})})})})]})})}async function qv(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 nA=(s,e)=>g.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 B$(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 Kv(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 F$(s){return String(s??"").trim().toLowerCase().replace(/^www\./,"")}function U$(s){const t=String(s||"").replaceAll("\\","/").split("/");return t[t.length-1]||""}function j$(s){const e=String(s||"");return e.toUpperCase().startsWith("HOT ")?e.slice(4).trim():e}function $$(s){const e=U$(s||""),t=j$(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 Wv(s){if(s.isUrl&&/^https?:\/\//i.test(String(s.input??"")))return String(s.input);const e=F$(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 rA({title:s,active:e,hiddenUntilHover:t,onClick:i,icon:n}){return g.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:g.jsx(oi,{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:g.jsx("span",{className:"text-base leading-none",children:n})})})}function aA(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 H$(){const[s,e]=_.useState([]),t=_.useRef({}),[i,n]=_.useState(!1),[r,a]=_.useState(null),[u,c]=_.useState(""),[d,f]=_.useState(1),p=10,[y,v]=_.useState([]),[b,S]=_.useState({}),[E,L]=_.useState(!1),[N,R]=_.useState(),H=_.useCallback(async()=>{L(!0);try{const ye=await fetch("/api/record/done?all=1&includeKeep=1",{cache:"no-store"});if(!ye.ok)return;const mt=await ye.json().catch(()=>null),st=Array.isArray(mt?.items)?mt.items:Array.isArray(mt)?mt:[],Xe={};for(const xt of st){const ft=$$(xt.output);if(!ft||ft==="—")continue;const Pt=ft.trim().toLowerCase();Pt&&(Xe[Pt]=(Xe[Pt]??0)+1)}S(Xe)}finally{L(!1)}},[]),F=_.useMemo(()=>new Set(y.map(ye=>ye.toLowerCase())),[y]),$=_.useCallback(ye=>{const mt=ye.toLowerCase();v(st=>st.some(xt=>xt.toLowerCase()===mt)?st.filter(xt=>xt.toLowerCase()!==mt):[...st,ye])},[]),M=_.useCallback(()=>v([]),[]);_.useEffect(()=>{const ye=mt=>{const st=mt,Xe=Array.isArray(st.detail?.tags)?st.detail.tags:[];v(Xe)};return window.addEventListener("models:set-tag-filter",ye),()=>window.removeEventListener("models:set-tag-filter",ye)},[]),_.useEffect(()=>{try{const ye=localStorage.getItem("models_pendingTags");if(!ye)return;const mt=JSON.parse(ye);Array.isArray(mt)&&v(mt),localStorage.removeItem("models_pendingTags")}catch{}},[]);const[W,D]=_.useState(""),[I,Q]=_.useState(null),[K,q]=_.useState(null),[le,te]=_.useState(!1),[V,G]=_.useState(!1),[J,ie]=_.useState(null),[oe,j]=_.useState(null),[X,se]=_.useState("favorite"),[fe,pe]=_.useState(!1),[de,Ve]=_.useState(null);async function Ze(){if(J){pe(!0),j(null),a(null);try{const ye=new FormData;ye.append("file",J),ye.append("kind",X);const mt=await fetch("/api/models/import",{method:"POST",body:ye});if(!mt.ok)throw new Error(await mt.text());const st=await mt.json();j(`✅ Import: ${st.inserted} neu, ${st.updated} aktualisiert, ${st.skipped} übersprungen`),G(!1),ie(null),await Fe(),window.dispatchEvent(new Event("models-changed"))}catch(ye){Ve(ye?.message??String(ye))}finally{pe(!1)}}}function Je(ye){const mt=Wv(ye)??void 0;return{output:`${ye.modelKey}_01_01_2000__00-00-00.mp4`,sourceUrl:mt}}const Pe=()=>{Ve(null),j(null),ie(null),se("favorite"),G(!0)},Fe=_.useCallback(async()=>{n(!0),a(null);try{const ye=await qv("/api/models/list",{cache:"no-store"});e(Array.isArray(ye)?ye:[]),H()}catch(ye){a(ye?.message??String(ye))}finally{n(!1)}},[H]);_.useEffect(()=>{H()},[H]),_.useEffect(()=>{Fe()},[Fe]),_.useEffect(()=>{const ye=mt=>{const Xe=mt?.detail??{};if(Xe?.model){const xt=Xe.model;e(ft=>{const Pt=ft.findIndex(It=>It.id===xt.id);if(Pt===-1)return ft;const qt=ft.slice();return qt[Pt]=xt,qt});return}if(Xe?.removed&&Xe?.id){const xt=String(Xe.id);e(ft=>ft.filter(Pt=>Pt.id!==xt));return}Fe()};return window.addEventListener("models-changed",ye),()=>window.removeEventListener("models-changed",ye)},[Fe]),_.useEffect(()=>{const ye=W.trim();if(!ye){Q(null),q(null);return}const mt=B$(ye);if(!mt){Q(null),q("Bitte nur gültige http(s) URLs einfügen (keine Modelnamen).");return}const st=window.setTimeout(async()=>{try{const Xe=await qv("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:mt})});if(!Xe?.isUrl){Q(null),q("Bitte nur URLs einfügen (keine Modelnamen).");return}Q(Xe),q(null)}catch(Xe){Q(null),q(Xe?.message??String(Xe))}},300);return()=>window.clearTimeout(st)},[W]);const qe=_.useMemo(()=>s.map(ye=>({m:ye,hay:`${ye.modelKey} ${ye.host??""} ${ye.input??""} ${ye.tags??""}`.toLowerCase()})),[s]),dt=_.useDeferredValue(u),Ge=_.useMemo(()=>[{key:"statusAll",header:"Status",align:"center",cell:ye=>{const mt=ye.liked===!0,st=ye.favorite===!0,Xe=ye.watching===!0,xt=!Xe&&!st&&!mt;return g.jsxs("div",{className:"group flex items-center justify-center gap-1 w-[110px]",children:[g.jsx("span",{className:wi(xt&&!Xe?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-opacity":"opacity-100"),children:g.jsx(oi,{variant:Xe?"soft":"secondary",size:"xs",className:wi("px-2 py-1 leading-none",!Xe&&"bg-transparent shadow-none hover:bg-gray-50 dark:hover:bg-white/10"),title:Xe?"Nicht mehr beobachten":"Beobachten",onClick:ft=>{ft.stopPropagation(),Et(ye.id,{watched:!Xe})},children:g.jsx("span",{className:wi("text-base leading-none",Xe?"text-indigo-600 dark:text-indigo-400":"text-gray-400 dark:text-gray-500"),children:"👁"})})}),g.jsx(rA,{title:st?"Favorit entfernen":"Als Favorit markieren",active:st,hiddenUntilHover:xt,onClick:ft=>{ft.stopPropagation(),st?Et(ye.id,{favorite:!1}):Et(ye.id,{favorite:!0,liked:!1})},icon:g.jsx("span",{className:st?"text-amber-500":"text-gray-400 dark:text-gray-500",children:"★"})}),g.jsx(rA,{title:mt?"Gefällt mir entfernen":"Gefällt mir",active:mt,hiddenUntilHover:xt,onClick:ft=>{ft.stopPropagation(),mt?Et(ye.id,{liked:!1}):Et(ye.id,{liked:!0,favorite:!1})},icon:g.jsx("span",{className:mt?"text-rose-500":"text-gray-400 dark:text-gray-500",children:"♥"})})]})}},{key:"model",header:"Model",sortable:!0,sortValue:ye=>(ye.modelKey||"").toLowerCase(),cell:ye=>{const mt=Wv(ye);return g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx("div",{className:"font-medium truncate",children:ye.modelKey}),mt?g.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",title:mt,onClick:st=>{st.stopPropagation(),window.open(mt,"_blank","noreferrer")},children:"↗"}):null]}),g.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:ye.host??"—"}),mt?g.jsx("div",{className:"text-xs text-indigo-600 dark:text-indigo-400 truncate max-w-[520px]",children:mt}):null]})}},{key:"videos",header:"Videos",sortable:!0,sortValue:ye=>{const mt=String(ye.modelKey||"").trim().toLowerCase(),st=b[mt];return typeof st=="number"?st:0},align:"right",cell:ye=>{const mt=String(ye.modelKey||"").trim().toLowerCase(),st=b[mt];return g.jsx("span",{className:"tabular-nums text-sm text-gray-900 dark:text-white w-[64px] inline-block text-right",children:typeof st=="number"?st:E?"…":0})}},{key:"tags",header:"Tags",sortable:!0,sortValue:ye=>Kv(ye.tags).length,cell:ye=>{const mt=Kv(ye.tags),st=mt.slice(0,6),Xe=mt.length-st.length,xt=mt.join(", ");return g.jsxs("div",{className:"flex flex-wrap gap-2 max-w-[520px]",title:xt||void 0,children:[ye.hot?nA(!0,"🔥 HOT"):null,ye.keep?nA(!0,"📌 Behalten"):null,st.map(ft=>g.jsx(Ga,{tag:ft,title:ft,active:F.has(ft.toLowerCase()),onClick:$},ft)),Xe>0?g.jsxs(Ga,{title:xt,children:["+",Xe]}):null,!ye.hot&&!ye.keep&&mt.length===0?g.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"—"}):null]})}},{key:"actions",header:"",align:"right",cell:ye=>g.jsx("div",{className:"flex justify-end w-[92px]",children:g.jsx(za,{job:Je(ye),variant:"table",order:["add","details"],className:"flex items-center gap-2"})})}],[F,$,b,E]),At=_.useMemo(()=>{const ye=dt.trim().toLowerCase(),mt=ye?qe.filter(st=>st.hay.includes(ye)).map(st=>st.m):s;return F.size===0?mt:mt.filter(st=>{const Xe=Kv(st.tags);if(Xe.length===0)return!1;const xt=new Set(Xe.map(ft=>ft.toLowerCase()));for(const ft of F)if(!xt.has(ft))return!1;return!0})},[s,qe,dt,F]),lt=_.useMemo(()=>{if(!N)return At;const ye=Ge.find(Xe=>Xe.key===N.key);if(!ye)return At;const mt=N.direction==="asc"?1:-1,st=At.map((Xe,xt)=>({r:Xe,i:xt}));return st.sort((Xe,xt)=>{let ft=0;if(ye.sortFn)ft=ye.sortFn(Xe.r,xt.r);else{const Pt=ye.sortValue?ye.sortValue(Xe.r):Xe.r?.[ye.key],qt=ye.sortValue?ye.sortValue(xt.r):xt.r?.[ye.key],It=aA(Pt),ni=aA(qt);It.isNull&&!ni.isNull?ft=1:!It.isNull&&ni.isNull?ft=-1:It.kind==="number"&&ni.kind==="number"?ft=It.valueni.value?1:0:ft=String(It.value).localeCompare(String(ni.value),void 0,{numeric:!0})}return ft===0?Xe.i-xt.i:ft*mt}),st.map(Xe=>Xe.r)},[At,N,Ge]);_.useEffect(()=>{f(1)},[u,y]);const bt=lt.length,nt=_.useMemo(()=>Math.max(1,Math.ceil(bt/p)),[bt,p]);_.useEffect(()=>{d>nt&&f(nt)},[d,nt]);const wt=_.useMemo(()=>{const ye=(d-1)*p;return lt.slice(ye,ye+p)},[lt,d,p]),ht=async()=>{if(I){if(!I.isUrl){q("Bitte nur URLs einfügen (keine Modelnamen).");return}te(!0),a(null);try{const ye=await qv("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});e(mt=>{const st=mt.filter(Xe=>Xe.id!==ye.id);return[ye,...st]}),D(""),Q(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:ye}}))}catch(ye){a(ye?.message??String(ye))}finally{te(!1)}}};async function Et(ye,mt){if(a(null),t.current[ye])return;t.current[ye]=!0;const st=s.find(Xe=>Xe.id===ye)??null;if(st){const Xe={...st,...mt};typeof mt?.watched=="boolean"&&(Xe.watching=mt.watched),mt?.favorite===!0&&(Xe.liked=!1),mt?.liked===!0&&(Xe.favorite=!1),e(xt=>xt.map(ft=>ft.id===ye?Xe:ft)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Xe}}))}try{const Xe=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:ye,...mt})});if(Xe.status===204){e(ft=>ft.filter(Pt=>Pt.id!==ye)),st?window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:st.id,modelKey:st.modelKey}})):window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:ye}}));return}if(!Xe.ok){const ft=await Xe.text().catch(()=>"");throw new Error(ft||`HTTP ${Xe.status}`)}const xt=await Xe.json();e(ft=>{const Pt=ft.findIndex(It=>It.id===xt.id);if(Pt===-1)return ft;const qt=ft.slice();return qt[Pt]=xt,qt}),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:xt}}))}catch(Xe){st&&(e(xt=>xt.map(ft=>ft.id===ye?st:ft)),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:st}}))),a(Xe?.message??String(Xe))}finally{delete t.current[ye]}}return g.jsxs("div",{className:"space-y-4",children:[g.jsx(fa,{header:g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Model hinzufügen"}),grayBody:!0,children:g.jsxs("div",{className:"grid gap-2",children:[g.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[g.jsx("input",{value:W,onChange:ye=>D(ye.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"}),g.jsx(oi,{className:"px-3 py-2 text-sm",onClick:ht,disabled:!I||le,title:I?"In Models speichern":"Bitte gültige URL einfügen",children:"Hinzufügen"}),g.jsx(oi,{className:"px-3 py-2 text-sm",onClick:Fe,disabled:i,children:"Aktualisieren"})]}),K?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:K}):I?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Gefunden: ",g.jsx("span",{className:"font-medium",children:I.modelKey}),I.host?g.jsxs("span",{className:"opacity-70",children:[" • ",I.host]}):null]}):null,r?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:r}):null]})}),g.jsxs(fa,{header:g.jsxs("div",{className:"space-y-2",children:[g.jsxs("div",{className:"grid gap-2 sm:flex sm:items-center sm:justify-between",children:[g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Models ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",At.length,")"]})]}),g.jsx("div",{className:"sm:hidden",children:g.jsx(oi,{variant:"secondary",size:"md",onClick:Pe,children:"Import"})})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("div",{className:"hidden sm:block",children:g.jsx(oi,{variant:"secondary",size:"md",onClick:Pe,children:"Importieren"})}),g.jsx("input",{value:u,onChange:ye=>c(ye.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 `})]})]}),y.length>0?g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Tag-Filter:"}),g.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.map(ye=>g.jsx(Ga,{tag:ye,active:!0,onClick:$,title:ye},ye)),g.jsx(oi,{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:[g.jsx("div",{className:"overflow-x-auto",children:g.jsx("div",{className:"min-w-[980px]",children:g.jsx(Sh,{rows:wt,columns:Ge,getRowKey:ye=>ye.id,striped:!0,compact:!0,fullWidth:!0,stickyHeader:!0,sort:N,onSortChange:ye=>R(ye),onRowClick:ye=>{const mt=Wv(ye);mt&&window.open(mt,"_blank","noreferrer")}})})}),g.jsx(XA,{page:d,pageSize:p,totalItems:bt,onPageChange:f})]}),g.jsx(rb,{open:V,onClose:()=>!fe&&G(!1),title:"Models importieren",footer:g.jsxs(g.Fragment,{children:[g.jsx(oi,{variant:"secondary",onClick:()=>G(!1),disabled:fe,children:"Abbrechen"}),g.jsx(oi,{variant:"primary",onClick:Ze,isLoading:fe,disabled:!J||fe,children:"Import starten"})]}),children:g.jsxs("div",{className:"space-y-3",children:[g.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Wähle eine CSV-Datei zum Import aus."}),g.jsxs("div",{className:"space-y-2",children:[g.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:"Import-Typ"}),g.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"favorite",checked:X==="favorite",onChange:()=>se("favorite"),disabled:fe}),"Favoriten (★)"]}),g.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[g.jsx("input",{type:"radio",name:"import-kind",value:"liked",checked:X==="liked",onChange:()=>se("liked"),disabled:fe}),"Gefällt mir (♥)"]})]})]}),g.jsx("input",{type:"file",accept:".csv,text/csv",onChange:ye=>{const mt=ye.target.files?.[0]??null;Ve(null),ie(mt)},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"}),J?g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Ausgewählt: ",g.jsx("span",{className:"font-medium",children:J.name})]}):null,de?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:de}):null,oe?g.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:oe}):null]})})]})}function qi(...s){return s.filter(Boolean).join(" ")}const z$=new Intl.NumberFormat("de-DE");function au(s){return s==null||!Number.isFinite(s)?"—":z$.format(s)}function G$(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 qm(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 V$(s){return s?s.split(",").map(e=>e.trim()).filter(Boolean):[]}function gh(s){return(s||"").split(/[\\/]/).pop()||""}function ER(s){if(!s)return"—";const e=typeof s=="string"?new Date(s):s;return Number.isNaN(e.getTime())?String(s):e.toLocaleDateString("de-DE",{year:"2-digit",month:"2-digit",day:"2-digit"})}function A1(s){return s.startsWith("HOT ")?s.slice(4):s}function wR(s){return String(s||"").startsWith("HOT ")}function q$(s,e){const t=String(s||"");return t&&t.replace(/([\\/])[^\\/]*$/,`$1${e}`)}function K$(s){return wR(s)?A1(s):`HOT ${s}`}function W$(s){const e=gh(s||""),t=A1(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 l0(s){return s?String(s).replace(/[\s\S]*?<\/script>/gi,"").replace(/[\s\S]*?<\/style>/gi,"").replace(/<\/?[^>]+>/g," ").replace(/\s+/g," ").trim():""}function oA(s){const e=String(s??"").trim();if(!e)return"";const t=e.match(/HTTP\s+(\d{3})/i);if(t?.[1])return`HTTP ${t[1]}`;const i=e.toLowerCase();if(i.includes("80?n.slice(0,77)+"…":n}function lA(s){const e=String(s??"").trim();if(!e)return"";const t=l0(e);return t.length>2e3?t.slice(0,2e3)+"…":t}function Y$(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 Or(s){return qi("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset",s)}const ah=s=>s?"blur-md scale-[1.03] brightness-90":"";function X$(s){return A1(s||"").trim()||"—"}function Q$(s){const e=s.endedAt??s.completedAt??s.endedAt;return e?ER(e):"—"}function Z$(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 J$(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 eH({open:s,modelKey:e,onClose:t,onOpenPlayer:i,cookies:n,runningJobs:r,blurPreviews:a,onToggleWatch:u,onToggleFavorite:c,onToggleLike:d,onToggleHot:f,onDelete:p}){const[y,v]=_.useState([]),[,b]=_.useState(!1),[S,E]=_.useState(null),[L,N]=_.useState(null),[R,H]=_.useState(null),[F,$]=_.useState(null),[M,W]=_.useState(!1),[D,I]=_.useState([]),[Q,K]=_.useState(!1),[q,le]=_.useState([]),[te,V]=_.useState(!1),[G,J]=_.useState(0),[ie,oe]=_.useState(null),[j,X]=_.useState(0),[se,fe]=_.useState(1),pe=25,de=Z$(e),Ve=_.useCallback(async()=>{try{const B=await(await fetch("/api/models/list",{cache:"no-store"})).json().catch(()=>null);v(Array.isArray(B)?B:[])}catch{}},[]),Ze=_.useCallback(async()=>{if(de){K(!0);try{const xe=`/api/record/done?model=${encodeURIComponent(de)}&page=${se}&pageSize=${pe}&sort=completed_desc&includeKeep=1&withCount=1`,Z=await(await fetch(xe,{cache:"no-store"})).json().catch(()=>null),re=Array.isArray(Z?.items)?Z.items:[],Te=Number(Z?.count??re.length);I(re),X(Number.isFinite(Te)?Te:re.length)}catch{}finally{K(!1)}}},[de,se]);function Je(xe){return{id:`model:${xe}`,output:`${xe}_01_01_2000__00-00-00.mp4`,status:"finished"}}const Pe=_.useCallback((xe,B)=>{const Z=String(xe??"").trim();Z&&oe({src:Z,alt:B})},[]);_.useEffect(()=>{s||J(0)},[s]);const Fe=_.useMemo(()=>Array.isArray(r)?r:q,[r,q]);_.useEffect(()=>{s&&fe(1)},[s,e]),_.useEffect(()=>{if(!s)return;let xe=!0;return b(!0),fetch("/api/models/list",{cache:"no-store"}).then(B=>B.json()).then(B=>{xe&&v(Array.isArray(B)?B:[])}).catch(()=>{xe&&v([])}).finally(()=>{xe&&b(!1)}),()=>{xe=!1}},[s]),_.useEffect(()=>{if(!s||!de)return;let xe=!0,B=null,Z=null;const re=async()=>{try{Z?.abort(),Z=new AbortController;const Ke=await(await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store",signal:Z.signal,body:JSON.stringify({q:[de],show:[],refresh:!1})})).json().catch(()=>null);if(!xe)return;N({enabled:Ke?.enabled,fetchedAt:Ke?.fetchedAt,lastError:Ke?.lastError});const vt=Array.isArray(Ke?.rooms)?Ke.rooms:[];E(vt[0]??null)}catch(Te){if(Te?.name==="AbortError"||!xe)return;N({enabled:void 0,fetchedAt:void 0,lastError:"Fetch fehlgeschlagen"}),E(null)}};return re(),B=window.setInterval(re,8e3),()=>{xe=!1,B&&window.clearInterval(B),Z?.abort()}},[s,de]),_.useEffect(()=>{if(!s||!de)return;let xe=!0;W(!0),H(null),$(null);const B=J$(n),Z=`/api/chaturbate/biocontext?model=${encodeURIComponent(de)}${G>0?"&refresh=1":""}`;return fetch(Z,{cache:"no-store",headers:B?{"X-Chaturbate-Cookie":B}:void 0}).then(async re=>{if(!re.ok){const Te=await re.text().catch(()=>"");throw new Error(Te||`HTTP ${re.status}`)}return re.json()}).then(re=>{xe&&($({enabled:re?.enabled,fetchedAt:re?.fetchedAt,lastError:re?.lastError}),H(re?.bio??null))}).catch(re=>{xe&&($({enabled:void 0,fetchedAt:void 0,lastError:re?.message||"Fetch fehlgeschlagen"}),H(null))}).finally(()=>{xe&&W(!1)}),()=>{xe=!1}},[s,de,G,n]),_.useEffect(()=>{!s||!de||Ze()},[s,de,Ze]),_.useEffect(()=>{if(!s||Array.isArray(r))return;let xe=!0;return V(!0),fetch("/api/record/jobs",{cache:"no-store"}).then(B=>B.json()).then(B=>{xe&&le(Array.isArray(B)?B:[])}).catch(()=>{xe&&le([])}).finally(()=>{xe&&V(!1)}),()=>{xe=!1}},[s,r]);const qe=_.useMemo(()=>de?y.find(xe=>(xe.modelKey||"").toLowerCase()===de)??null:null,[y,de]),dt=D,Ge=_.useMemo(()=>Math.max(1,Math.ceil(j/pe)),[j]),At=_.useMemo(()=>de?Fe.filter(xe=>{const B=W$(xe.output);return B!=="—"&&B.trim().toLowerCase()===de}):[],[Fe,de]),lt=_.useMemo(()=>{const xe=V$(qe?.tags),B=Array.isArray(S?.tags)?S.tags:[],Z=new Map;for(const re of[...xe,...B]){const Te=String(re).trim().toLowerCase();Te&&(Z.has(Te)||Z.set(Te,String(re).trim()))}return Array.from(Z.values()).sort((re,Te)=>re.localeCompare(Te,"de"))},[qe?.tags,S?.tags]),bt=S?.display_name||qe?.modelKey||de||"Model",nt=S?.image_url_360x270||S?.image_url||"",wt=S?.image_url||nt,ht=S?.chat_room_url_revshare||S?.chat_room_url||"",Et=(S?.current_show||"").trim().toLowerCase(),ye=Et?Et==="public"?"Public":Et==="private"?"Private":Et:"",mt=(R?.location||"").trim(),st=R?.follower_count,Xe=R?.display_age,xt=(R?.room_status||"").trim(),ft=R?.last_broadcast?qm(R.last_broadcast):"—",Pt=l0(R?.about_me),qt=l0(R?.wish_list),It=Array.isArray(R?.social_medias)?R.social_medias:[],ni=Array.isArray(R?.photo_sets)?R.photo_sets:[],Gt=Array.isArray(R?.interested_in)?R.interested_in:[],yi=({icon:xe,label:B,value:Z})=>g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 px-2.5 py-2 sm:px-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] sm:text-xs text-gray-600 dark:text-gray-300",children:[xe,B]}),g.jsx("div",{className:"mt-0.5 text-sm font-semibold text-gray-900 dark:text-white",children:Z})]}),Zt=_.useCallback(async xe=>{const B=xe.output||"",Z=gh(B);if(!Z){await f?.(xe);return}const re=K$(Z);I(Te=>Te.map(Ke=>Ke.id&&xe.id&&Ke.id===xe.id||Ke.output&&xe.output&&Ke.output===xe.output?{...Ke,output:q$(Ke.output||"",re)}:Ke)),await f?.(xe),Ze()},[f,Ze]),Jt=_.useCallback(async xe=>{const B=xe.output||"";gh(B)&&I(re=>re.filter(Te=>!(Te.id&&xe.id&&Te.id===xe.id||Te.output&&xe.output&&Te.output===xe.output))),await p?.(xe),Ze()},[p,Ze]),di=_.useCallback(async()=>{de&&(v(xe=>xe.map(B=>(B.modelKey||"").toLowerCase()===de?{...B,favorite:!B.favorite}:B)),await c?.(Je(de)),Ve())},[de,c,Ve]),Zi=_.useCallback(async()=>{de&&(v(xe=>xe.map(B=>(B.modelKey||"").toLowerCase()===de?{...B,liked:B.liked!==!0}:B)),await d?.(Je(de)),Ve())},[de,d,Ve]),Di=_.useCallback(async()=>{de&&(v(xe=>xe.map(B=>(B.modelKey||"").toLowerCase()===de?{...B,watching:!B.watching}:B)),await u?.(Je(de)),Ve())},[de,u,Ve]),[Mi,Ki]=_.useState("info");_.useEffect(()=>{s&&Ki("info")},[s,de]);const As=[{id:"info",label:"Info"},{id:"downloads",label:"Downloads",count:j?au(j):void 0,disabled:Q},{id:"running",label:"Running",count:At.length?au(At.length):void 0,disabled:te}];return g.jsxs(rb,{open:s,onClose:t,title:bt,width:"max-w-6xl",layout:"split",scroll:"right",leftWidthClass:"lg:w-[320px]",mobileCollapsedImageSrc:nt||void 0,mobileCollapsedImageAlt:bt,rightBodyClassName:"pt-0 sm:pt-2",left:g.jsx("div",{className:"space-y-3 sm:space-y-4",children:g.jsxs("div",{className:"hidden sm:block space-y-2",children:[g.jsxs("div",{className:"overflow-hidden rounded-lg border border-gray-200/70 bg-white/70 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"relative",children:[nt?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Pe(wt,bt),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:nt,alt:bt,className:qi("h-24 sm:h-52 w-full object-cover transition",ah(a))})}):g.jsx("div",{className:"h-24 sm:h-52 w-full bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),g.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"}),g.jsxs("div",{className:"absolute left-3 top-3 flex flex-wrap items-center gap-2",children:[ye?g.jsx("span",{className:Or("bg-emerald-500/10 text-emerald-900 ring-emerald-200 backdrop-blur dark:text-emerald-200 dark:ring-emerald-400/20"),children:ye}):null,xt?g.jsx("span",{className:Or(xt.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:xt}):null,S?.is_hd?g.jsx("span",{className:Or("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?g.jsx("span",{className:Or("bg-amber-500/10 text-amber-900 ring-amber-200 backdrop-blur dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),g.jsxs("div",{className:"absolute bottom-3 left-3 right-3",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-white drop-shadow",children:S?.display_name||S?.username||qe?.modelKey||de||"—"}),g.jsx("div",{className:"truncate text-xs text-white/85 drop-shadow",children:S?.username?`@${S.username}`:qe?.modelKey?`@${qe.modelKey}`:""})]}),g.jsxs("div",{className:"absolute bottom-3 right-3 flex items-center gap-2",children:[g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),Di()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",qe?.watching?"bg-sky-500/25 ring-sky-200/30":"bg-black/20 ring-white/15"),title:qe?.watching?"Watch entfernen":"Auf Watch setzen","aria-pressed":!!qe?.watching,"aria-label":qe?.watching?"Watch entfernen":"Auf Watch setzen",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(f0,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(_u,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-200")})]})}),g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),di()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",qe?.favorite?"bg-amber-500/25 ring-amber-200/30":"bg-black/20 ring-white/15"),title:qe?.favorite?"Favorit entfernen":"Als Favorit markieren","aria-pressed":!!qe?.favorite,"aria-label":qe?.favorite?"Favorit entfernen":"Als Favorit markieren",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(m0,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Pc,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-200")})]})}),g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),Zi()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","cursor-pointer hover:scale-[1.03] active:scale-[0.98] transition",qe?.liked?"bg-rose-500/25 ring-rose-200/30":"bg-black/20 ring-white/15"),title:qe?.liked?"Like entfernen":"Liken","aria-pressed":qe?.liked===!0,"aria-label":qe?.liked?"Like entfernen":"Liken",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(Th,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-white/70")}),g.jsx(Eu,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-200")})]})})]})]}),g.jsxs("div",{className:"p-3 sm:p-4",children:[g.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:gap-3",children:[g.jsx(yi,{icon:g.jsx(J_,{className:"size-4"}),label:"Viewer",value:au(S?.num_users)}),g.jsx(yi,{icon:g.jsx(Ny,{className:"size-4"}),label:"Follower",value:au(S?.num_followers??st)})]}),g.jsxs("dl",{className:"mt-2 grid grid-cols-2 gap-2 text-xs",children:[g.jsxs("div",{className:"rounded-lg border border-gray-200/60 bg-white/50 px-2.5 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(nM,{className:"size-4"}),"Location"]}),g.jsx("dd",{className:"mt-1 text-[13px] font-semibold leading-snug text-gray-900 dark:text-white break-words",children:S?.location||mt||"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/60 bg-white/50 px-2.5 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(JO,{className:"size-4"}),"Sprache"]}),g.jsx("dd",{className:"mt-1 text-[13px] font-semibold leading-snug text-gray-900 dark:text-white break-words",children:S?.spoken_languages||"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/60 bg-white/50 px-2.5 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(Sm,{className:"size-4"}),"Online"]}),g.jsx("dd",{className:"mt-1 text-[13px] font-semibold leading-snug text-gray-900 dark:text-white break-words",children:Yv(S?.seconds_online)})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/60 bg-white/50 px-2.5 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(Th,{className:"size-4"}),"Alter"]}),g.jsx("dd",{className:"mt-1 text-[13px] font-semibold leading-snug text-gray-900 dark:text-white break-words",children:Xe!=null?String(Xe):S?.age!=null?String(S.age):"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/60 bg-white/50 px-2.5 py-2 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("dt",{className:"flex items-center gap-1 text-gray-600 dark:text-gray-300",children:[g.jsx(Sm,{className:"size-4"}),"Last broadcast"]}),g.jsx("dd",{className:"mt-1 text-[13px] font-semibold leading-snug text-gray-900 dark:text-white break-words",children:ft})]})]}),L?.enabled===!1?g.jsx("div",{className:"mt-2 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."}):L?.lastError?g.jsxs("div",{className:"mt-2 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:[g.jsxs("div",{className:"font-medium",children:["Online-Info: ",oA(L.lastError)]}),g.jsxs("details",{className:"mt-1",children:[g.jsx("summary",{className:"cursor-pointer select-none text-[11px] text-rose-900/80 underline underline-offset-2 dark:text-rose-200/80",children:"Details"}),g.jsx("pre",{className:"mt-1 max-h-28 overflow-auto whitespace-pre-wrap break-words rounded-md bg-black/5 p-2 text-[11px] leading-snug dark:bg-white/10",children:lA(L.lastError)})]})]}):null,F?.enabled===!1?g.jsx("div",{className:"mt-2 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."}):F?.lastError?g.jsxs("div",{className:"mt-2 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: ",F.lastError]}):null]})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Tags"}),lt.length?g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:lt.map(xe=>g.jsx(Ga,{tag:xe},xe))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Tags vorhanden."})]})]})}),rightHeader:g.jsxs("div",{className:qi("border-b border-gray-200/70 dark:border-white/10","bg-white/95 backdrop-blur dark:bg-gray-800/95"),children:[g.jsxs("div",{className:"sm:hidden px-2 pb-2 space-y-1.5",children:[g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-2.5 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsxs("button",{type:"button",className:"relative shrink-0 overflow-hidden rounded-lg ring-1 ring-black/5 dark:ring-white/10",onClick:()=>wt&&Pe(wt,bt),"aria-label":"Bild vergrößern",children:[nt?g.jsx("img",{src:nt,alt:bt,className:qi("size-10 object-cover",ah(a))}):g.jsx("div",{className:"size-10 bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),g.jsx("span",{"aria-hidden":!0,className:qi("absolute bottom-1.5 right-1.5 size-2.5 rounded-full ring-2 ring-white/80 dark:ring-gray-900/60",(xt||"").toLowerCase()==="online"?"bg-emerald-400":"bg-gray-400")})]}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsxs("div",{className:"flex items-start justify-between gap-2",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-semibold text-gray-900 dark:text-white",children:S?.display_name||S?.username||qe?.modelKey||de||"—"}),g.jsx("div",{className:"truncate text-xs text-gray-600 dark:text-gray-300",children:S?.username?`@${S.username}`:qe?.modelKey?`@${qe.modelKey}`:""})]}),g.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),Di()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","transition active:scale-[0.98]",qe?.watching?"bg-sky-500/15 ring-sky-200/30":"bg-black/5 ring-black/10 dark:bg-white/5 dark:ring-white/10"),title:qe?.watching?"Watch entfernen":"Auf Watch setzen","aria-pressed":!!qe?.watching,"aria-label":qe?.watching?"Watch entfernen":"Auf Watch setzen",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(f0,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.watching?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-gray-700 dark:text-white/70")}),g.jsx(_u,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.watching?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-sky-500")})]})}),g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),di()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","transition active:scale-[0.98]",qe?.favorite?"bg-amber-500/15 ring-amber-200/30":"bg-black/5 ring-black/10 dark:bg-white/5 dark:ring-white/10"),title:qe?.favorite?"Favorit entfernen":"Als Favorit markieren","aria-pressed":!!qe?.favorite,"aria-label":qe?.favorite?"Favorit entfernen":"Als Favorit markieren",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(m0,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.favorite?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-gray-700 dark:text-white/70")}),g.jsx(Pc,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.favorite?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-amber-500")})]})}),g.jsx("button",{type:"button",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),Zi()},className:qi("inline-flex items-center justify-center rounded-full p-1.5 ring-1 ring-inset backdrop-blur","transition active:scale-[0.98]",qe?.liked?"bg-rose-500/15 ring-rose-200/30":"bg-black/5 ring-black/10 dark:bg-white/5 dark:ring-white/10"),title:qe?.liked?"Like entfernen":"Liken","aria-pressed":qe?.liked===!0,"aria-label":qe?.liked?"Like entfernen":"Liken",children:g.jsxs("span",{className:"relative inline-block size-4",children:[g.jsx(Th,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.liked?"opacity-0 scale-75 rotate-12":"opacity-100 scale-100 rotate-0","text-gray-700 dark:text-white/70")}),g.jsx(Eu,{className:qi("absolute inset-0 size-4 transition-all duration-200 ease-out motion-reduce:transition-none",qe?.liked?"opacity-100 scale-110 rotate-0":"opacity-0 scale-75 -rotate-12","text-rose-500")})]})})]})]}),g.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[ye?g.jsx("span",{className:Or("bg-emerald-500/10 text-emerald-900 ring-emerald-200 dark:text-emerald-200 dark:ring-emerald-400/20"),children:ye}):null,xt?g.jsx("span",{className:Or(xt.toLowerCase()==="online"?"bg-emerald-500/10 text-emerald-900 ring-emerald-200 dark:text-emerald-200 dark:ring-emerald-400/20":"bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:xt}):null,S?.is_hd?g.jsx("span",{className:Or("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"HD"}):null,S?.is_new?g.jsx("span",{className:Or("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"NEW"}):null]}),ht?g.jsx("div",{className:"mt-1.5 flex justify-end",children:g.jsxs("a",{href:ht,target:"_blank",rel:"noreferrer",className:qi("inline-flex h-8 items-center justify-center gap-1 rounded-lg px-3 text-sm font-medium","border border-gray-200/70 bg-white/70 text-gray-900 shadow-sm backdrop-blur hover:bg-white","dark:border-white/10 dark:bg-white/5 dark:text-white"),title:"Room öffnen",children:[g.jsx(Tm,{className:"size-4"}),g.jsx("span",{children:"Room"})]})}):null]})]}),g.jsxs("div",{className:"mt-1 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-[12px] text-gray-700 dark:text-gray-200",children:[g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(J_,{className:"size-3.5 text-gray-400"}),g.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:au(S?.num_users)})]}),g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Ny,{className:"size-3.5 text-gray-400"}),g.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:au(S?.num_followers??st)})]}),g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Y_,{className:"size-3.5 text-gray-400"}),g.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:Yv(S?.seconds_online)})]}),g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Sm,{className:"size-3.5 text-gray-400"}),g.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:R?.last_broadcast?ER(R.last_broadcast):"—"})]})]}),L?.enabled===!1?g.jsx("div",{className:"mt-2 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."}):L?.lastError?g.jsxs("div",{className:"mt-2 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: ",L.lastError]}):null,F?.enabled===!1?g.jsx("div",{className:"mt-2 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."}):F?.lastError?g.jsxs("div",{className:"mt-2 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:[g.jsx("div",{className:"flex items-start justify-between gap-2",children:g.jsxs("div",{className:"font-medium",children:["BioContext: ",oA(F.lastError)]})}),g.jsxs("details",{className:"mt-1",children:[g.jsx("summary",{className:"cursor-pointer select-none text-[11px] text-rose-900/80 underline underline-offset-2 dark:text-rose-200/80",children:"Details"}),g.jsx("pre",{className:"mt-1 max-h-28 overflow-auto whitespace-pre-wrap break-words rounded-md bg-black/5 p-2 text-[11px] leading-snug dark:bg-white/10",children:lA(F.lastError)})]})]}):null]}),lt.length?g.jsx("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 px-2 py-1.5 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsxs("div",{className:"shrink-0 text-xs font-semibold text-gray-900 dark:text-white",children:["Tags ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",lt.length,")"]})]}),g.jsx("div",{className:"-mx-1 flex-1 overflow-x-auto px-1 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden",children:g.jsxs("div",{className:"flex min-w-max items-center gap-1.5",children:[lt.slice(0,20).map(xe=>g.jsx(Ga,{tag:xe},xe)),lt.length>20?g.jsxs("span",{className:Or("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:["+",lt.length-20]}):null]})})]})}):null]}),g.jsxs("div",{className:"flex items-start justify-between gap-2 px-2 py-2 sm:px-4",children:[g.jsx("div",{className:"min-w-0",children:g.jsx("div",{className:"text-[11px] leading-snug text-gray-600 dark:text-gray-300",children:de?g.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1",children:[L?.fetchedAt?g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["Online-Stand: ",qm(L.fetchedAt)]}):null,F?.fetchedAt?g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["· Bio-Stand: ",qm(F.fetchedAt)]}):null]}):"—"})}),g.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[Mi==="info"?g.jsx(oi,{variant:"secondary",className:qi("h-9 px-3 text-sm","whitespace-nowrap"),disabled:M||!e,onClick:()=>J(xe=>xe+1),title:"BioContext neu abrufen",children:g.jsxs("span",{className:"inline-flex items-center gap-2",children:[g.jsx(CO,{className:qi("size-4",M?"animate-spin":"")}),g.jsx("span",{className:"hidden sm:inline",children:"Bio aktualisieren"})]})}):null,ht?g.jsxs("a",{href:ht,target:"_blank",rel:"noreferrer",className:qi("inline-flex h-8 items-center justify-center gap-1 rounded-lg","border border-gray-200/70 bg-white/70 px-3 text-sm font-medium text-gray-900 shadow-sm backdrop-blur hover:bg-white","dark:border-white/10 dark:bg-white/5 dark:text-white","whitespace-nowrap"),title:"Room öffnen",children:[g.jsx(Tm,{className:"size-4"}),g.jsx("span",{className:"hidden sm:inline",children:"Room öffnen"})]}):null]})]}),g.jsx("div",{className:"px-2 pb-2",children:g.jsx("div",{className:"-mx-1 overflow-x-auto px-1 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden",children:g.jsx("div",{className:"min-w-max",children:g.jsx(ox,{tabs:As,value:Mi,onChange:xe=>Ki(xe),variant:"pillsBrand",ariaLabel:"Bereich auswählen"})})})})]}),footer:g.jsx("div",{className:"w-full",children:g.jsx(oi,{variant:"secondary",className:"w-full sm:w-auto",onClick:t,children:"Schließen"})}),children:[g.jsxs("div",{className:"min-h-0",children:[Mi==="info"?g.jsxs("div",{className:"space-y-2",children:[g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-3 sm:p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"flex items-center justify-between gap-3",children:g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Room Subject"})}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:S?.room_subject?g.jsx("p",{className:"line-clamp-4 whitespace-pre-wrap break-words",children:S.room_subject}):g.jsx("p",{className:"text-gray-600 dark:text-gray-300",children:"Keine Subject-Info vorhanden."})})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Bio"}),M?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),g.jsxs("div",{className:"mt-2 grid gap-3 sm:grid-cols-2",children:[g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(YO,{className:"size-4"}),"Über mich"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:Pt?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:Pt}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-200",children:[g.jsx(Ny,{className:"size-4"}),"Wishlist"]}),g.jsx("div",{className:"mt-2 text-sm text-gray-800 dark:text-gray-100",children:qt?g.jsx("p",{className:"line-clamp-6 whitespace-pre-wrap",children:qt}):g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"—"})})]})]}),g.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Real name:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R?.real_name?l0(R.real_name):"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Body type:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R?.body_type||"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Smoke/Drink:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R?.smoke_drink||"—"})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/60 px-3 py-2 text-xs dark:border-white/10 dark:bg-white/5",children:[g.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"Sex:"})," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:R?.sex||"—"})]})]}),Gt.length?g.jsxs("div",{className:"mt-2",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Interested in"}),g.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:Gt.map(xe=>g.jsx("span",{className:Or("bg-sky-500/10 text-sky-900 ring-sky-200 dark:text-sky-200 dark:ring-sky-400/20"),children:xe},xe))})]}):null]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Socials"}),It.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[It.length," Links"]}):null]}),It.length?g.jsx("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:It.map(xe=>{const B=Y$(xe.link);return g.jsxs("a",{href:B,target:"_blank",rel:"noreferrer",className:qi("group flex min-w-0 w-full items-center gap-3 overflow-hidden rounded-lg 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:xe.title_name,children:[g.jsx("div",{className:"flex size-9 items-center justify-center rounded-lg bg-black/5 dark:bg-white/5",children:xe.image_url?g.jsx("img",{src:xe.image_url,alt:"",className:"size-5"}):g.jsx(tM,{className:"size-5"})}),g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:xe.title_name}),g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:xe.label_text?xe.label_text:xe.tokens!=null?`${xe.tokens} token(s)`:"Link"})]}),g.jsx(Tm,{className:"ml-auto size-4 text-gray-400 transition group-hover:text-indigo-500 dark:text-gray-500 dark:group-hover:text-indigo-400"})]},xe.id)})}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Social-Medias vorhanden."})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Photo sets"}),ni.length?g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:[ni.length," Sets"]}):null]}),ni.length?g.jsx("div",{className:"mt-2 grid gap-3 sm:grid-cols-2",children:ni.slice(0,6).map(xe=>g.jsxs("div",{className:"overflow-hidden rounded-lg border border-gray-200/70 bg-white/60 dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"relative",children:[xe.cover_url?g.jsx("button",{type:"button",className:"block w-full cursor-zoom-in",onClick:()=>Pe(xe.cover_url,xe.name),"aria-label":"Bild vergrößern",children:g.jsx("img",{src:xe.cover_url,alt:xe.name,className:qi("h-28 w-full object-cover transition",ah(a))})}):g.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-black/5 dark:bg-white/5",children:g.jsx(Z_,{className:"size-6 text-gray-500"})}),g.jsxs("div",{className:"absolute left-2 top-2 flex flex-wrap gap-2",children:[xe.is_video?g.jsx("span",{className:Or("bg-indigo-500/10 text-indigo-900 ring-indigo-200 dark:text-indigo-200 dark:ring-indigo-400/20"),children:"Video"}):g.jsx("span",{className:Or("bg-gray-500/10 text-gray-900 ring-gray-200 dark:text-gray-200 dark:ring-white/15"),children:"Photos"}),xe.fan_club_only?g.jsx("span",{className:Or("bg-amber-500/10 text-amber-900 ring-amber-200 dark:text-amber-200 dark:ring-amber-400/20"),children:"FanClub"}):null]})]}),g.jsxs("div",{className:"p-3",children:[g.jsx("div",{className:"truncate text-sm font-medium text-gray-900 dark:text-white",children:xe.name}),g.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300",children:["Tokens: ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:au(xe.tokens)}),xe.user_can_access===!0?g.jsx("span",{className:"ml-2",children:"· Zugriff: ✅"}):null]})]})]},xe.id))}):g.jsx("div",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Keine Photo-Sets vorhanden."})]})]}):null,Mi==="downloads"?g.jsx("div",{className:"min-h-0",children:g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"shrink-0 flex flex-wrap items-center justify-between gap-3",children:[g.jsxs("div",{children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Abgeschlossene Downloads"}),g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Inkl. Dateien aus ",g.jsx("span",{className:"font-medium",children:"/done/keep/"})]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx(oi,{size:"sm",variant:"secondary",disabled:Q||se<=1,onClick:()=>fe(xe=>Math.max(1,xe-1)),children:"Zurück"}),g.jsxs("span",{className:"text-xs text-gray-600 dark:text-gray-300",children:["Seite ",se," / ",Ge]}),g.jsx(oi,{size:"sm",variant:"secondary",disabled:Q||se>=Ge,onClick:()=>fe(xe=>Math.min(Ge,xe+1)),children:"Weiter"})]})]}),g.jsx("div",{className:"mt-2",children:Q?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade Downloads…"}):dt.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine abgeschlossenen Downloads für dieses Model gefunden."}):g.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:dt.map(xe=>{const B=gh(xe.output||""),Z=wR(B),re=X$(B),Te=Yv(xe.durationSeconds),Ke=G$(xe.sizeBytes),vt=Q$(xe);return g.jsxs("div",{role:i?"button":void 0,tabIndex:i?0:void 0,className:qi("group relative overflow-hidden rounded-lg 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-lg dark:hover:shadow-none","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 dark:focus-visible:outline-indigo-500",i?"cursor-pointer":""),onClick:()=>i?.(xe),onKeyDown:Tt=>{i&&(Tt.key==="Enter"||Tt.key===" ")&&i(xe)},children:[g.jsxs("div",{className:"relative aspect-video bg-black/5 dark:bg-white/5",children:[g.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-indigo-500/10 via-transparent to-sky-500/10"}),g.jsx("div",{className:qi("absolute inset-0",ah(a))}),g.jsx("div",{className:"absolute inset-x-3 top-3 z-10 flex justify-end",onClick:Tt=>Tt.stopPropagation(),onMouseDown:Tt=>Tt.stopPropagation(),children:g.jsx(za,{job:xe,variant:"overlay",collapseToMenu:!0,isHot:Z,isFavorite:!!qe?.favorite,isLiked:qe?.liked===!0,isWatching:!!qe?.watching,onToggleHot:Zt,onDelete:Jt,order:["hot","delete"],className:"w-full justify-end gap-2"})}),g.jsx("div",{className:"absolute inset-0 grid place-items-center",children:g.jsxs("div",{className:"rounded-lg bg-black/10 px-4 py-3 text-gray-700 dark:bg-white/10 dark:text-gray-200",children:[g.jsx(VO,{className:"mx-auto size-8 opacity-80"}),g.jsx("div",{className:"mt-1 text-sm font-medium opacity-80",children:"Preview"})]})})]}),g.jsxs("div",{className:"border-t border-gray-200/60 bg-white px-5 py-4 dark:border-white/10 dark:bg-gray-900",children:[g.jsx("div",{className:"flex items-center justify-between gap-2",children:g.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[Z?g.jsx("span",{className:"shrink-0 rounded-md bg-amber-500/15 px-2 py-0.5 text-xs font-semibold text-amber-800 dark:text-amber-300",children:"HOT"}):null,g.jsx("div",{className:"min-w-0 truncate text-base font-semibold text-gray-900 dark:text-white",children:re})]})}),g.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-gray-600 dark:text-gray-300",children:[g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Sm,{className:"size-5 text-gray-400"}),vt]}),g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Y_,{className:"size-5 text-gray-400"}),Te]}),g.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.jsx(Z_,{className:"size-5 text-gray-400"}),Ke]})]})]})]},`${xe.id}-${B}`)})})})]})}):null,Mi==="running"?g.jsx("div",{className:"min-h-0",children:g.jsxs("div",{className:"rounded-lg border border-gray-200/70 bg-white/70 p-4 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"flex items-center justify-between gap-3",children:[g.jsx("div",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:"Laufende Jobs"}),te?g.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Lade…"}):null]}),g.jsx("div",{className:"mt-2",children:te?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Lade…"}):At.length===0?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine laufenden Jobs."}):g.jsx("div",{className:"grid gap-2",children:At.map(xe=>g.jsx("div",{className:"overflow-hidden rounded-lg border border-gray-200/70 bg-white/60 px-3 py-2 text-sm dark:border-white/10 dark:bg-white/5",children:g.jsxs("div",{className:"flex items-start gap-3",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("div",{className:"break-words line-clamp-2 font-medium text-gray-900 dark:text-white",children:gh(xe.output||"")}),g.jsxs("div",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-300",children:["Start:"," ",g.jsx("span",{className:"font-medium text-gray-900 dark:text-white",children:qm(xe.startedAt)})]})]}),i?g.jsx(oi,{size:"sm",variant:"secondary",className:"shrink-0",onClick:()=>i(xe),children:"Öffnen"}):null]})},xe.id))})})]})}):null]}),g.jsx(rb,{open:!!ie,onClose:()=>oe(null),title:ie?.alt||"Bild",width:"max-w-4xl",layout:"single",scroll:"body",footer:g.jsxs("div",{className:"flex items-center justify-end gap-2",children:[ie?.src?g.jsxs("a",{href:ie.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:[g.jsx(Tm,{className:"size-4"}),"In neuem Tab"]}):null,g.jsx(oi,{variant:"secondary",onClick:()=>oe(null),children:"Schließen"})]}),children:g.jsx("div",{className:"grid place-items-center",children:ie?.src?g.jsx("img",{src:ie.src,alt:ie.alt||"",className:qi("max-h-[80vh] w-auto max-w-full rounded-lg object-contain",ah(a))}):null})})]})}const Km=s=>Math.max(0,Math.min(1,s));function Wm(s){return s==="good"?"bg-emerald-500":s==="warn"?"bg-amber-500":"bg-red-500"}function tH(s){return s==null?"–":`${Math.round(s)}ms`}function uA(s){return s==null?"–":`${Math.round(s)}%`}function Xv(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 iH(s=1e3){const[e,t]=Qt.useState(null);return Qt.useEffect(()=>{let i=0,n=performance.now(),r=0,a=!0,u=!1;const c=y=>{if(!a||!u)return;r+=1;const v=y-n;if(v>=s){const b=Math.round(r*1e3/v);t(b),r=0,n=y}i=requestAnimationFrame(c)},d=()=>{a&&(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),()=>{a=!1,document.removeEventListener("visibilitychange",p),f()}},[s]),e}function cA({mode:s="inline",className:e,pollMs:t=3e3}){const i=iH(1e3),[n,r]=Qt.useState(null),[a,u]=Qt.useState(null),[c,d]=Qt.useState(null),[f,p]=Qt.useState(null),[y,v]=Qt.useState(null),b=5*1024*1024*1024,S=8*1024*1024*1024,E=Qt.useRef(!1);Qt.useEffect(()=>{const q=`/api/perf/stream?ms=${encodeURIComponent(String(t))}`,le=ap(q,"perf",te=>{const V=typeof te?.cpuPercent=="number"?te.cpuPercent:null,G=typeof te?.diskFreeBytes=="number"?te.diskFreeBytes:null,J=typeof te?.diskTotalBytes=="number"?te.diskTotalBytes:null,ie=typeof te?.diskUsedPercent=="number"?te.diskUsedPercent:null;u(V),d(G),p(J),v(ie);const oe=typeof te?.serverMs=="number"?te.serverMs:null;r(oe!=null?Math.max(0,Date.now()-oe):null)});return()=>le()},[t]);const L=n==null?"bad":n<=120?"good":n<=300?"warn":"bad",N=i==null?"bad":i>=55?"good":i>=30?"warn":"bad",R=a==null?"bad":a<=60?"good":a<=85?"warn":"bad",H=Km((n??999)/500),F=Km((i??0)/60),$=Km((a??0)/100),M=c!=null&&f!=null&&f>0?c/f:null,W=y??(M!=null?(1-M)*100:null),D=Km((W??0)/100);c==null?E.current=!1:E.current?c>=S&&(E.current=!1):c<=b&&(E.current=!0);const I=c==null||E.current||M==null?"bad":M>=.15?"good":M>=.07?"warn":"bad",Q=c==null?"Disk: –":`Free: ${Xv(c)} / Total: ${Xv(f)} · Used: ${uA(W)}`,K=s==="floating"?"fixed bottom-4 right-4 z-[80]":"flex items-center";return g.jsx("div",{className:`${K} ${e??""}`,children:g.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:[g.jsxs("div",{className:"flex items-center gap-2",title:Q,children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Disk"}),g.jsx("div",{className:"hidden sm:block h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Wm(I)}`,style:{width:`${Math.round(D*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-11 tabular-nums text-gray-900 dark:text-gray-100",children:Xv(c)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"Ping"}),g.jsx("div",{className:"hidden sm:block h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Wm(L)}`,style:{width:`${Math.round(H*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:tH(n)})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"FPS"}),g.jsx("div",{className:"hidden sm:block h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Wm(N)}`,style:{width:`${Math.round(F*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-8 tabular-nums text-gray-900 dark:text-gray-100",children:i??"–"})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[g.jsx("span",{className:"text-[11px] font-medium text-gray-600 dark:text-gray-300",children:"CPU"}),g.jsx("div",{className:"hidden sm:block h-2 w-14 sm:w-16 rounded-full bg-gray-200/70 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:`h-full ${Wm(R)}`,style:{width:`${Math.round($*100)}%`}})}),g.jsx("span",{className:"text-[11px] w-10 tabular-nums text-gray-900 dark:text-gray-100",children:uA(a)})]})]})})}function sH(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=>{a||(u(),t=window.setTimeout(()=>{f()},p))},f=async()=>{if(!a)try{const p=(s.getModels?.()??[]).map(Q=>String(Q||"").trim()).filter(Boolean),v=(s.getShow?.()??[]).map(Q=>String(Q||"").trim()).filter(Boolean).slice().sort(),b=p.slice().sort(),S=b.length===0&&!!s.fetchAllWhenNoModels;if(b.length===0&&!S){c();const Q={enabled:r?.enabled??!1,rooms:[]};r=Q,s.onData(Q);const K=document.hidden?Math.max(15e3,e):e;d(K);return}const E=S?[]:b,L=`${v.join(",")}|${S?"__ALL__":E.join(",")}`,N=L;n=L,c();const R=new AbortController;i=R;const F=S?[[]]:sH(E,350);let $=[],M=!1,W=0,D=!1;for(const Q of F){if(R.signal.aborted||N!==n||a)return;const K=await fetch("/api/chaturbate/online",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:Q,show:v,refresh:!1}),signal:R.signal,cache:"no-store"});if(!K.ok)continue;D=!0;const q=await K.json();M=M||!!q?.enabled,$.push(...Array.isArray(q?.rooms)?q.rooms:[]);const le=Number(q?.total??0);Number.isFinite(le)&&le>W&&(W=le)}if(!D){const Q=document.hidden?Math.max(15e3,e):e;d(Q);return}const I={enabled:M,rooms:nH($),total:W};if(R.signal.aborted||N!==n||a)return;r=I,s.onData(I)}catch(p){if(p?.name==="AbortError")return;s.onError?.(p)}finally{const p=document.hidden?Math.max(15e3,e):e;d(p)}};return f(),()=>{a=!0,u(),c()}}async function Qv(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 rH(s,e,t,i){const n=`/api/generated/cover?category=${encodeURIComponent(s)}`,r=e?`&v=${e}`:"",a="",u=i&&i.trim()?`&model=${encodeURIComponent(i.trim())}`:"";return`${n}${r}${a}${u}`}function hA(s){if(!s)return[];const e=s.split(/[\n,;|]+/g).map(t=>t.trim()).filter(Boolean);return Array.from(new Set(e))}function AR(s){return String(s||"").replaceAll("\\","/").split("/").pop()||""}function kR(s){return s.toUpperCase().startsWith("HOT ")?s.slice(4).trim():s}function aH(s){const e=kR(AR(s||""));return e?e.replace(/\.[^.]+$/,""):""}const oH=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function Zv(s){const t=kR(AR(s)).replace(/\.[^.]+$/,""),i=t.match(oH);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 lH(s){const e=aH(s);return e?`/generated/meta/${encodeURIComponent(e)}/thumbs.webp`:null}async function uH(s,e,t,i){const n=(t||"").trim(),r=`/api/generated/cover?category=${encodeURIComponent(s)}&src=${encodeURIComponent(e)}`+(n?`&model=${encodeURIComponent(n)}`:"")+"&refresh=1",a=await fetch(r,{method:"GET",cache:"no-store"});if(!a.ok){const u=await a.text().catch(()=>"");throw new Error(u||`ensureCover failed: HTTP ${a.status}`)}}function cH(){const[s,e]=_.useState([]),[t,i]=_.useState(!1),[n,r]=_.useState(null),[a,u]=_.useState(()=>Date.now()),[c,d]=_.useState({}),[f,p]=_.useState({}),[y,v]=_.useState(!1),[b,S]=_.useState(null),[E,L]=_.useState({}),N=_.useRef(null),R=_.useRef({}),H=_.useCallback((D,I)=>{const Q={};for(const q of Array.isArray(D)?D:[]){const le=String(q?.modelKey??"").trim().toLowerCase();if(!le)continue;const te=hA(q?.tags).map(V=>V.toLowerCase());te.length&&(Q[le]=te)}const K={};for(const q of Array.isArray(I)?I:[]){const le=String(q?.output??"");if(!le)continue;const te=(Zv(le)||"").trim().toLowerCase();if(!te)continue;const V=Q[te];if(!(!V||V.length===0))for(const G of V)G&&(K[G]||(K[G]=[]),K[G].push(le))}for(const[q,le]of Object.entries(K))K[q]=Array.from(new Set(le));R.current=K},[]),F=_.useCallback(D=>{const I=String(D||"").trim();if(I){try{localStorage.setItem("finishedDownloads_pendingTags",JSON.stringify([I]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"finished"}})),window.dispatchEvent(new CustomEvent("finished-downloads:tag-filter",{detail:{tags:[I],mode:"replace"}}))}},[]),$=_.useCallback(D=>{const I=String(D||"").trim();if(I){try{localStorage.setItem("models_pendingTags",JSON.stringify([I]))}catch{}window.dispatchEvent(new CustomEvent("app:navigate-tab",{detail:{tab:"models"}})),window.dispatchEvent(new CustomEvent("models:set-tag-filter",{detail:{tags:[I]}}))}},[]),M=_.useCallback(async()=>{N.current?.abort();const D=new AbortController;N.current=D,i(!0),r(null);try{const[I,Q]=await Promise.all([Qv("/api/models/list",{cache:"no-store",signal:D.signal}),Qv("/api/record/done?page=1&pageSize=2000&sort=completed_desc",{cache:"no-store",signal:D.signal})]),K=Array.isArray(Q?.items)?Q.items:Array.isArray(Q)?Q:[];H(Array.isArray(I)?I:[],K);const q=new Map;for(const ie of Array.isArray(I)?I:[])for(const oe of hA(ie?.tags)){const j=oe.toLowerCase();q.set(j,(q.get(j)??0)+1)}const le=R.current||{},te=Array.from(q.entries()).map(([ie,oe])=>({tag:ie,modelsCount:oe,downloadsCount:(le[ie]||[]).length})).sort((ie,oe)=>ie.tag.localeCompare(oe.tag,void 0,{sensitivity:"base"})),V=new Map;try{const ie=await Qv("/api/generated/coverinfo/list",{cache:"no-store",signal:D.signal});for(const oe of Array.isArray(ie)?ie:[]){const j=String(oe?.category??"").trim().toLowerCase();j&&V.set(j,oe)}}catch{}const G={};for(const ie of te){const oe=V.get(ie.tag);G[ie.tag]=!!oe?.hasCover}p(G);const J={};for(const ie of te){const j=(le[ie.tag]||[])[0]||"";let X=j?Zv(j):null;if(!X){const se=V.get(ie.tag);se?.hasCover&&se.model?.trim()&&(X=se.model.trim())}X&&(J[ie.tag]=X)}L(J),d(ie=>{const oe={};for(const j of te){const X=ie[j.tag];X&&G[j.tag]===!0&&(oe[j.tag]=X)}return oe}),e(te)}catch(I){if(I?.name==="AbortError")return;r(I?.message??String(I)),e([]),R.current={},L({}),p({}),d({})}finally{N.current===D&&(N.current=null,i(!1))}},[H]);_.useEffect(()=>(M(),()=>{N.current?.abort()}),[M]);const W=_.useCallback(async()=>{if(!y){v(!0),r(null),S({done:0,total:s.length});try{const D=R.current||{},I=await Promise.all(s.map(async K=>{try{const q=D[K.tag]||[];if(q.length===0)return{tag:K.tag,ok:!0,status:0,text:"skipped (no candidates)"};const le=q[Math.floor(Math.random()*q.length)],te=lH(le);if(!te)return{tag:K.tag,ok:!0,status:0,text:"skipped (no thumb url)"};const V=Zv(le);return await uH(K.tag,te,V,!0),p(G=>({...G,[K.tag]:!0})),L(G=>{const J={...G};return V?.trim()?J[K.tag]=V.trim():delete J[K.tag],J}),d(G=>{const J={...G};return delete J[K.tag],J}),{tag:K.tag,ok:!0,status:200,text:""}}catch(q){return{tag:K.tag,ok:!1,status:0,text:q?.message??String(q)}}finally{S(q=>q&&{...q,done:Math.min(q.total,q.done+1)})}})),Q=I.filter(K=>!K.ok);if(Q.length){console.warn("Cover renew failed:",Q.slice(0,20));const K=Q.slice(0,8).map(q=>`${q.tag} (ERR)`).join(", ");r(`Covers fehlgeschlagen: ${Q.length}/${I.length} — z.B.: ${K}`)}else r(null)}finally{u(Date.now()),v(!1),setTimeout(()=>S(null),400)}}},[s,y]);return g.jsxs(fa,{header:g.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.jsxs("div",{className:"text-sm font-medium text-gray-900 dark:text-white",children:["Kategorien ",g.jsxs("span",{className:"text-gray-500 dark:text-gray-400",children:["(",s.length,")"]})]}),g.jsxs("div",{className:"flex items-center gap-2",children:[b?g.jsxs("div",{className:"hidden sm:flex items-center gap-2 mr-2",children:[g.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300 tabular-nums",children:["Covers: ",b.done,"/",b.total]}),g.jsx("div",{className:"h-2 w-28 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden",children:g.jsx("div",{className:"h-full bg-indigo-500",style:{width:b.total>0?`${Math.round(b.done/b.total*100)}%`:"0%"}})})]}):null,g.jsx(oi,{variant:"secondary",size:"md",onClick:W,disabled:t||y,children:"Cover erneuern"}),g.jsx(oi,{variant:"secondary",size:"md",onClick:M,disabled:t||y,children:"Aktualisieren"})]})]}),grayBody:!0,children:[n?g.jsx("div",{className:"text-xs text-red-600 dark:text-red-300",children:n}):null,s.length===0&&!t?g.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Keine Kategorien/Tags gefunden."}):null,g.jsx("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:s.map(D=>{const I=E[D.tag]??null,Q=f[D.tag]===!0,K=Object.prototype.hasOwnProperty.call(f,D.tag),q=Q?rH(D.tag,a,!1,I):"",le=c[D.tag]==="ok",te=c[D.tag]==="error";return g.jsxs("button",{type:"button",onClick:()=>F(D.tag),className:wi("group text-left rounded-2xl overflow-hidden transition","bg-white/70 dark:bg-white/[0.06]","border border-gray-200/70 dark:border-white/10","shadow-sm hover:shadow-md","hover:-translate-y-[1px]","hover:bg-white dark:hover:bg-white/[0.09]","focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-gray-950"),title:"In FinishedDownloads öffnen (Tag-Filter setzen)",children:[g.jsx("div",{className:"relative w-full overflow-hidden aspect-[16/9] bg-gray-100/70 dark:bg-white/5",children:K?Q?te?g.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2",children:[g.jsx("div",{className:"absolute inset-0 opacity-70",style:{background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,0.25), transparent 55%),radial-gradient(circle at 70% 80%, rgba(14,165,233,0.18), transparent 55%)"}}),g.jsxs("div",{className:"relative z-10 rounded-xl bg-white/80 dark:bg-black/30 px-3 py-2.5 shadow-sm ring-1 ring-black/5 dark:ring-white/10 backdrop-blur-md",children:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Cover konnte nicht geladen werden"}),g.jsx("div",{className:"mt-1 flex justify-center",children:g.jsx("span",{className:`text-[11px] inline-flex items-center rounded-full bg-indigo-50 px-2 py-1 font-semibold text-indigo-700 ring-1 ring-indigo-100 hover:bg-indigo-100\r dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20 dark:hover:bg-indigo-500/20`,onClick:V=>{V.preventDefault(),V.stopPropagation(),d(G=>{const J={...G};return delete J[D.tag],J}),u(Date.now())},children:"Retry"})})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 z-[1] pointer-events-none",style:{background:"linear-gradient(to bottom, rgba(255,255,255,0.10), rgba(255,255,255,0) 35%),linear-gradient(to top, rgba(0,0,0,0.35), rgba(0,0,0,0) 45%)"}}),g.jsx("img",{src:q,alt:"","aria-hidden":"true",className:"absolute inset-0 z-0 h-full w-full object-cover blur-xl scale-110 opacity-60",loading:"lazy"}),g.jsx("img",{src:q,alt:D.tag,className:"absolute inset-0 z-0 h-full w-full object-contain",loading:"lazy",onLoad:()=>d(V=>({...V,[D.tag]:"ok"})),onError:()=>{d(V=>({...V,[D.tag]:"error"})),p(V=>({...V,[D.tag]:!1}))}}),le&&I?g.jsx("div",{className:"absolute left-3 bottom-3 z-10 max-w-[calc(100%-24px)]",children:g.jsx("div",{className:wi("truncate rounded-full px-2.5 py-1 text-[11px] font-semibold","bg-black/40 text-white backdrop-blur-md","ring-1 ring-white/15"),children:I})}):null]}):g.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2",children:[g.jsx("div",{className:"absolute inset-0 opacity-70",style:{background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,0.25), transparent 55%),radial-gradient(circle at 70% 80%, rgba(14,165,233,0.18), transparent 55%)"}}),g.jsxs("div",{className:"relative z-10 rounded-xl bg-white/80 dark:bg-black/30 px-3 py-2.5 shadow-sm ring-1 ring-black/5 dark:ring-white/10 backdrop-blur-md",children:[g.jsx("div",{className:"text-xs font-semibold text-gray-900 dark:text-white",children:"Kein Cover vorhanden"}),I?g.jsxs("div",{className:"mt-0.5 text-[11px] text-gray-700 dark:text-gray-300",children:["Model: ",g.jsx("span",{className:"font-semibold",children:I})]}):null,g.jsx("div",{className:"mt-1 text-[11px] text-gray-600 dark:text-gray-400 text-center",children:"(Kein Request / keine 404)"})]})]}):g.jsxs("div",{className:"absolute inset-0",children:[g.jsx("div",{className:"absolute inset-0 opacity-70",style:{background:"radial-gradient(circle at 30% 20%, rgba(99,102,241,0.20), transparent 55%),radial-gradient(circle at 70% 80%, rgba(14,165,233,0.14), transparent 55%)"}}),g.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/20 to-transparent"}),g.jsx("div",{className:"absolute left-3 bottom-3 text-[11px] font-semibold text-white/80 bg-black/30 px-2.5 py-1 rounded-full ring-1 ring-white/10",children:"Cover wird geprüft…"})]})}),g.jsx("div",{className:"px-4 py-3.5",children:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsxs("div",{className:"min-w-0",children:[g.jsx("div",{className:"font-semibold text-gray-900 dark:text-white truncate tracking-tight",children:D.tag}),g.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[g.jsxs("span",{role:"button",tabIndex:0,className:wi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap","overflow-hidden","bg-indigo-50 text-indigo-700 ring-1 ring-indigo-100","dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20","cursor-pointer"),title:"FinishedDownloads nach diesem Tag filtern",onClick:V=>{V.preventDefault(),V.stopPropagation(),F(D.tag)},onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),V.stopPropagation(),F(D.tag))},children:[g.jsx("span",{className:"shrink-0",children:D.downloadsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Downloads"})]}),g.jsxs("span",{role:"button",tabIndex:0,className:wi("inline-flex max-w-full items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold","tabular-nums whitespace-nowrap overflow-hidden","bg-gray-50 text-gray-700 ring-1 ring-gray-200","dark:bg-white/5 dark:text-gray-200 dark:ring-white/10","cursor-pointer"),title:"Models nach diesem Tag filtern",onClick:V=>{V.preventDefault(),V.stopPropagation(),$(D.tag)},onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),V.stopPropagation(),$(D.tag))},children:[g.jsx("span",{className:"shrink-0",children:D.modelsCount}),g.jsx("span",{className:"min-w-0 truncate font-medium",children:"Models"})]})]})]}),g.jsx("span",{"aria-hidden":"true",className:wi("shrink-0 mt-0.5 text-gray-400 dark:text-gray-500","transition-transform group-hover:translate-x-[1px]"),children:"→"})]})})]},D.tag)})})]})}async function oh(s,e){const t=await fetch(s,{credentials:"include",...e});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(i||`HTTP ${t.status}`)}return t.json()}function dH(){try{const e=new URL(window.location.href).searchParams.get("next")||"/";return!e.startsWith("/")||e.startsWith("/login")?"/":e}catch{return"/"}}const k1="recorder_login_state_v1";function hH(){try{const s=sessionStorage.getItem(k1);if(!s)return null;const e=JSON.parse(s);return!e?.ts||Date.now()-e.ts>900*1e3?null:e}catch{return null}}function fH(s){try{sessionStorage.setItem(k1,JSON.stringify(s))}catch{}}function Ym(){try{sessionStorage.removeItem(k1)}catch{}}function mH(s){const t=(s??"").replace(/\D/g,"").slice(0,6).split("");for(;t.length<6;)t.push("");return t}function pH(s){return(s??[]).join("")}function gH({onLoggedIn:s}){const e=_.useMemo(()=>dH(),[]),[t,i]=_.useState(""),[n,r]=_.useState(""),[a,u]=_.useState(["","","","","",""]),c=_.useRef([]),[d,f]=_.useState(!1),[p,y]=_.useState(null),[v,b]=_.useState("login"),[S,E]=_.useState(null),[L,N]=_.useState(null),[R,H]=_.useState(null),F=_.useRef(!1),$=_.useMemo(()=>pH(a),[a]);function M(G){const J=c.current[G];J&&J.focus()}function W(){u(["","","","","",""]),F.current=!1,window.setTimeout(()=>M(0),0)}function D(G,J){const ie=(J??"").replace(/\D/g,"").slice(-1);u(oe=>{const j=[...oe];return j[G]=ie,j})}function I(G,J){const ie=(J??"").replace(/\D/g,"");if(!ie){D(G,""),F.current=!1;return}if(ie.length>1){u(oe=>{const j=[...oe];let X=G;for(const se of ie){if(X>5)break;j[X]=se,X++}return j}),F.current=!1,window.setTimeout(()=>M(Math.min(5,G+ie.length)),0);return}D(G,ie),F.current=!1,G<5&&window.setTimeout(()=>M(G+1),0)}function Q(G,J){if(J.key==="Backspace"){if(a[G]){J.preventDefault(),D(G,""),F.current=!1;return}G>0&&(J.preventDefault(),M(G-1),D(G-1,""),F.current=!1);return}if(J.key==="ArrowLeft"){J.preventDefault(),G>0&&M(G-1);return}if(J.key==="ArrowRight"){J.preventDefault(),G<5&&M(G+1);return}}function K(G,J){const oe=(J.clipboardData.getData("text")||"").replace(/\D/g,"").slice(0,6);oe&&(J.preventDefault(),u(j=>{const X=[...j];let se=G;for(const fe of oe){if(se>5)break;X[se]=fe,se++}return X}),F.current=!1,window.setTimeout(()=>M(Math.min(5,G+oe.length)),0))}_.useEffect(()=>{const G=hH();G&&(b(G.stage??"login"),i(G.username??""),u(mH(G.code??"")),E(G.setupAuthUrl??null),N(G.setupSecret??null),H(G.setupInfo??null))},[]),_.useEffect(()=>{fH({stage:v,username:t,code:$,setupAuthUrl:S,setupSecret:L,setupInfo:R,ts:Date.now()})},[v,t,$,S,L,R]),_.useEffect(()=>{F.current=!1,(v==="verify"||v==="setup")&&window.setTimeout(()=>M(0),0)},[v]),_.useEffect(()=>{let G=!1;return(async()=>{try{const ie=await oh("/api/auth/me",{cache:"no-store"});if(G)return;if(ie?.authenticated){ie?.totpConfigured?(Ym(),window.location.assign(e||"/")):(b("setup"),te());return}if(ie?.pending2fa){b("verify");return}b("login")}catch{}})(),()=>{G=!0}},[e]);const q=async()=>{f(!0),y(null);try{if((await oh("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})}))?.totpRequired){b("verify"),W();return}const J=await oh("/api/auth/me",{cache:"no-store"});if(J?.authenticated&&!J?.totpConfigured){b("setup"),W(),await te();return}s&&await s(),Ym(),window.location.assign(e||"/")}catch(G){y(G?.message??String(G))}finally{f(!1)}},le=async()=>{const G=$.trim();if(/^\d{6}$/.test(G)){f(!0),y(null);try{await oh("/api/auth/2fa/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:G})}),s&&await s(),Ym(),window.location.assign(e||"/")}catch(J){F.current=!1,y(J?.message??String(J))}finally{f(!1)}}},te=async()=>{y(null),H(null);try{const G=await oh("/api/auth/2fa/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),J=(G?.otpauth??"").trim();if(!J)throw new Error("2FA Setup fehlgeschlagen (keine otpauth URL).");E(J),N((G?.secret??"").trim()||null),H("Scan den QR-Code in deiner Authenticator-App und bestätige danach mit dem 6-stelligen Code.")}catch(G){y(G?.message??String(G))}};_.useEffect(()=>{d||v!=="verify"&&v!=="setup"||/^\d{6}$/.test($)&&(F.current||(F.current=!0,le()))},[$,v,d]);const V=g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"2FA Code"}),g.jsx("div",{className:"flex items-center justify-between gap-2",children:a.map((G,J)=>g.jsx("input",{ref:ie=>{c.current[J]=ie},value:G,onChange:ie=>I(J,ie.target.value),onKeyDown:ie=>Q(J,ie),onPaste:ie=>K(J,ie),inputMode:"numeric",pattern:"[0-9]*",maxLength:1,autoComplete:J===0?"one-time-code":"off",enterKeyHint:J===5?"done":"next",autoCapitalize:"none",autoCorrect:"off",disabled:d,className:`h-12 w-12 rounded-lg text-center text-lg tabular-nums 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`,"aria-label":`2FA Ziffer ${J+1}`},J))})]});return g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsx("div",{className:"relative grid min-h-[100dvh] place-items-center px-4",children:g.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-gray-200/70 bg-white/80 p-6 shadow-sm backdrop-blur dark:border-white/10 dark:bg-white/5",children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Recorder Login"}),g.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:"Bitte melde dich an, um fortzufahren."})]}),g.jsxs("div",{className:"mt-5 space-y-3",children:[v==="login"?g.jsxs("form",{onSubmit:G=>{G.preventDefault(),!d&&q()},className:"space-y-3",children:[g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Username"}),g.jsx("input",{value:t,onChange:G=>i(G.target.value),autoComplete:"username",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",placeholder:"admin",disabled:d})]}),g.jsxs("div",{className:"space-y-1",children:[g.jsx("label",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"Passwort"}),g.jsx("input",{type:"password",value:n,onChange:G=>r(G.target.value),autoComplete:"current-password",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",placeholder:"••••••••••",disabled:d})]}),g.jsx(oi,{type:"submit",variant:"primary",className:"w-full rounded-lg",disabled:d||!t.trim()||!n,children:d?"Login…":"Login"})]}):v==="verify"?g.jsxs("form",{onSubmit:G=>{G.preventDefault(),!d&&le()},className:"space-y-3",children:[g.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200",children:"2FA ist aktiv – bitte gib den Code aus deiner Authenticator-App ein."}),V,g.jsxs("div",{className:"flex gap-2",children:[g.jsx(oi,{type:"button",variant:"secondary",className:"flex-1 rounded-lg",disabled:d,onClick:()=>{b("login"),W()},children:"Zurück"}),g.jsx(oi,{type:"submit",variant:"primary",className:"flex-1 rounded-lg",disabled:d||!/^\d{6}$/.test($),children:d?"Prüfe…":"Bestätigen"})]})]}):g.jsxs("form",{onSubmit:G=>{G.preventDefault(),!d&&le()},className:"space-y-3",children:[g.jsx("div",{className:"rounded-lg border border-indigo-200 bg-indigo-50 px-3 py-2 text-sm text-indigo-900 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-200",children:"2FA ist noch nicht eingerichtet – bitte richte es jetzt ein (empfohlen)."}),g.jsxs("div",{className:"space-y-2 text-sm text-gray-700 dark:text-gray-200",children:[g.jsx("div",{children:"1) Öffne deine Authenticator-App und füge einen neuen Account hinzu."}),g.jsx("div",{children:"2) Scanne den QR-Code oder verwende den Secret-Key."})]}),g.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white/70 p-3 dark:border-white/10 dark:bg-white/5",children:[g.jsx("div",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:"QR / Setup"}),S?g.jsx("div",{className:"mt-2 flex items-center justify-center",children:g.jsx("img",{alt:"2FA QR Code",className:"h-44 w-44 rounded bg-white p-2",src:`https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(S)}`})}):g.jsx("div",{className:"mt-2 text-xs text-gray-600 dark:text-gray-300",children:"QR wird geladen…"}),L?g.jsxs("div",{className:"mt-3",children:[g.jsx("div",{className:"text-xs text-gray-600 dark:text-gray-300",children:"Secret (manuell):"}),g.jsx("div",{className:"mt-1 select-all break-all rounded bg-gray-100 px-2 py-1 text-xs font-mono text-gray-900 dark:bg-white/10 dark:text-gray-100",children:L})]}):null,R?g.jsx("div",{className:"mt-3 text-xs text-gray-600 dark:text-gray-300",children:R}):null,g.jsx("div",{className:"mt-3",children:g.jsx(oi,{type:"button",variant:"secondary",className:"w-full rounded-lg",disabled:d,onClick:()=>{te()},title:"Setup-Infos neu laden",children:S?"QR/Setup erneut laden":"QR/Setup laden"})})]}),V,g.jsxs("div",{className:"flex gap-2",children:[g.jsx(oi,{type:"button",variant:"secondary",className:"flex-1 rounded-lg",disabled:d,onClick:()=>{s&&s(),Ym(),window.location.assign(e||"/")},title:"Ohne 2FA fortfahren (nicht empfohlen)",children:"Später"}),g.jsx(oi,{type:"submit",variant:"primary",className:"flex-1 rounded-lg",disabled:d||!/^\d{6}$/.test($),children:d?"Aktiviere…":"2FA aktivieren"})]})]}),p?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:p}),g.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:()=>y(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null]})]})})]})}const Jv="record_cookies";function Xm(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 xn(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 fA={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 To(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 ou(s){const e=(s??"").trim();if(!e)return null;for(const t of e.split(/\s+/g)){const i=To(t);if(i)return i}return null}function Ih(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}}function CR(s){try{const e=new URL(s),t=e.hostname.replace(/^www\./i,"").toLowerCase();if(t!=="chaturbate.com"&&!t.endsWith(".chaturbate.com"))return"";const i=e.pathname.split("/").filter(Boolean);return i[0]?decodeURIComponent(i[0]).trim():""}catch{return""}}function vl(s){const e=Ih(s);if(!e)return s;if(e==="chaturbate"){const i=CR(s);return i?`https://chaturbate.com/${encodeURIComponent(i)}/`:s}const t=DR(s);return t?`https://www.myfreecams.com/#${encodeURIComponent(t)}`:s}function yH(s){const e=Ih(s);return e?((e==="chaturbate"?CR(s):DR(s))||"").trim().toLowerCase():""}function DR(s){try{const e=new URL(s),t=e.hostname.replace(/^www\./i,"").toLowerCase();if(t!=="myfreecams.com"&&!t.endsWith(".myfreecams.com"))return"";const i=(e.hash||"").replace(/^#\/?/,"");if(i){const a=i.split("/").filter(Boolean),u=a[a.length-1]||"";if(u)return decodeURIComponent(u).trim()}const n=e.pathname.split("/").filter(Boolean),r=n[n.length-1]||"";return r?decodeURIComponent(r).trim():""}catch{return""}}const qs=s=>(s||"").replaceAll("\\","/").split("/").pop()||"";function vH(s,e){const i=(s||"").replaceAll("\\","/").split("/");return i[i.length-1]=e,i.join("/")}function xH(s){return s.startsWith("HOT ")?s.slice(4):s}const bH=/^(.*?)_\d{1,2}_\d{1,2}_\d{4}__\d{1,2}-\d{2}-\d{2}/;function lh(s){const t=xH(qs(s)).replace(/\.[^.]+$/,""),i=t.match(bH);if(i?.[1]?.trim())return i[1].trim();const n=t.lastIndexOf("_");return n>0?t.slice(0,n):t||null}function TH(){const[s,e]=_.useState(!1),[t,i]=_.useState(!1),n=_.useCallback(async()=>{try{const ve=await xn("/api/auth/me",{cache:"no-store"});i(!!ve?.authenticated)}catch{i(!1)}finally{e(!0)}},[]),r=_.useCallback(async()=>{try{await fetch("/api/auth/logout",{method:"POST",cache:"no-store"})}catch{}finally{i(!1),e(!0),st(null),xt(!1),Zt("running"),di(null),Di(!1),Et(null),te([]),G([]),j(0),ie(1),Ge({}),se(0),Ct({}),Vt.current={},Fi.current={},li.current=!1,vt([]),Li({}),pe(0),q("")}},[]);_.useEffect(()=>{n()},[n]);const a=ZA(),u=_.useRef(a),c=_.useRef(0),d=ve=>{const we=(ve||"").toLowerCase();return we.includes("altersverifikationsseite erhalten")||we.includes("verify your age")||we.includes("schutzseite von cloudflare erhalten")||we.includes("just a moment")||we.includes("kein room-html")},f=ve=>{const we=!!ve?.silent,ke="Cookies fehlen oder sind abgelaufen",Y="Der Recorder hat statt des Room-HTML eine Schutz-/Altersverifikationsseite erhalten. Bitte Cookies aktualisieren (bei Chaturbate z.B. cf_clearance + sessionId) und erneut starten.";if(!we){st(`⚠️ ${ke}. ${Y}`),Pt(!0);return}const ae=Date.now();ae-c.current>15e3&&(c.current=ae,u.current?.error(ke,Y))};_.useEffect(()=>{u.current=a},[a]);const[p,y]=_.useState(!1);_.useEffect(()=>{const ve=window,we=typeof ve.requestIdleCallback=="function"?ve.requestIdleCallback(()=>y(!0),{timeout:1500}):window.setTimeout(()=>y(!0),800);return()=>{typeof ve.cancelIdleCallback=="function"?ve.cancelIdleCallback(we):window.clearTimeout(we)}},[]);const v=8,b="finishedDownloads_sort",[S,E]=_.useState(()=>{try{return window.localStorage.getItem(b)||"completed_desc"}catch{return"completed_desc"}}),L=_.useRef(null),N=_.useRef(!1),R=_.useRef(null),H=_.useRef(!1),F=(ve,we)=>`${we}::${ve}`,$=_.useCallback(async ve=>{if(ve<1||N.current)return;const we=F(ve,S),ke=L.current;if(!(ke?.key===we&&Date.now()-ke.ts<15e3)){N.current=!0;try{const Y=await fetch(`/api/record/done?page=${ve}&pageSize=${v}&sort=${encodeURIComponent(S)}`,{cache:"no-store"});if(!Y.ok)return;const ae=await Y.json().catch(()=>null),_e=Array.isArray(ae?.items)?ae.items:Array.isArray(ae)?ae:[];L.current={key:we,items:_e,ts:Date.now()}}finally{N.current=!1}}},[S]),M=_.useCallback(async()=>{try{const ve=await fetch("/api/record/done/meta",{cache:"no-store"});if(!ve.ok)return;const we=await ve.json().catch(()=>null),ke=Number(we?.count??0),Y=Number.isFinite(ke)&&ke>=0?ke:0;j(Y),Ve(Date.now())}catch{}},[]),W=_.useCallback(()=>{window.dispatchEvent(new CustomEvent("finished-downloads:reload"))},[]),D=_.useCallback(async()=>{try{const ve=await fetch("/api/record/list",{cache:"no-store"});if(!ve.ok)return;const we=await ve.json().catch(()=>null),ke=Array.isArray(we)?we:Array.isArray(we?.items)?we.items:[];te(ke),ai.current=ke,Ve(Date.now())}catch{}},[]);_.useEffect(()=>{try{window.localStorage.setItem(b,S)}catch{}},[S]),_.useEffect(()=>{t&&M()},[t,M]);const[I,Q]=_.useState(null),[K,q]=_.useState(""),[le,te]=_.useState([]),[V,G]=_.useState([]),[J,ie]=_.useState(1),[oe,j]=_.useState(0),[X,se]=_.useState(0),[fe,pe]=_.useState(0),[de,Ve]=_.useState(()=>Date.now()),[Ze,Je]=_.useState(()=>Date.now());_.useEffect(()=>{const ve=window.setInterval(()=>Je(Date.now()),1e3);return()=>window.clearInterval(ve)},[]);const Pe=ve=>(ve||"").toLowerCase().trim(),Fe=ve=>{const we=Math.max(0,Math.floor(ve/1e3));if(we<2)return"gerade eben";if(we<60)return`vor ${we} Sekunden`;const ke=Math.floor(we/60);if(ke===1)return"vor 1 Minute";if(ke<60)return`vor ${ke} Minuten`;const Y=Math.floor(ke/60);return Y===1?"vor 1 Stunde":`vor ${Y} Stunden`},qe=_.useMemo(()=>{const ve=Ze-de;return`(zuletzt aktualisiert: ${Fe(ve)})`},[Ze,de]),[dt,Ge]=_.useState({}),At=_.useCallback(ve=>{const we={};for(const ke of Array.isArray(ve)?ve:[]){const Y=(ke?.modelKey||"").trim().toLowerCase();if(!Y)continue;const ae=Me=>(Me.favorite?4:0)+(Me.liked===!0?2:0)+(Me.watching?1:0),_e=we[Y];(!_e||ae(ke)>=ae(_e))&&(we[Y]=ke)}return we},[]),lt=_.useCallback(async()=>{try{const ve=await xn("/api/models/list",{cache:"no-store"});Ge(At(Array.isArray(ve)?ve:[])),Ve(Date.now())}catch{}},[At]),[bt,nt]=_.useState(null),wt=_.useRef(null),[ht,Et]=_.useState(null);_.useEffect(()=>{const ve=we=>{const Y=(we.detail?.modelKey??"").trim();if(!Y)return;if(!Y.includes(" ")&&!Y.includes("/")&&!Y.includes("\\")){const $e=Y.replace(/^@/,"").trim().toLowerCase();$e&&Et($e);return}const _e=To(Y);if(!_e){let $e=Y.replace(/^https?:\/\//i,"");$e.includes("/")&&($e=$e.split("/").filter(Boolean).pop()||$e),$e.includes(":")&&($e=$e.split(":").pop()||$e),$e=$e.trim().toLowerCase(),$e&&Et($e);return}const Me=vl(_e),Ce=yH(Me);Ce&&Et(Ce)};return window.addEventListener("open-model-details",ve),()=>window.removeEventListener("open-model-details",ve)},[]);const ye=_.useCallback(ve=>{const we=Date.now(),ke=wt.current;if(!ke){wt.current={ts:we,list:[ve]};return}ke.ts=we;const Y=ke.list.findIndex(ae=>ae.id===ve.id);Y>=0?ke.list[Y]=ve:ke.list.unshift(ve)},[]);_.useEffect(()=>{lt();const ve=we=>{const Y=we?.detail??{},ae=Y?.model;if(ae&&typeof ae=="object"){const _e=String(ae.modelKey??"").toLowerCase().trim();_e&&Ge(Me=>({...Me,[_e]:ae}));try{ye(ae)}catch{}nt(Me=>Me?.id===ae.id?ae:Me),Ve(Date.now());return}if(Y?.removed){const _e=String(Y?.id??"").trim(),Me=String(Y?.modelKey??"").toLowerCase().trim();Me&&Ge(Ce=>{const{[Me]:$e,...tt}=Ce;return tt}),_e&&nt(Ce=>Ce?.id===_e?null:Ce),Ve(Date.now());return}lt()};return window.addEventListener("models-changed",ve),()=>window.removeEventListener("models-changed",ve)},[lt,ye]);const[mt,st]=_.useState(null),[Xe,xt]=_.useState(!1),[ft,Pt]=_.useState(!1),[qt,It]=_.useState({}),[ni,Gt]=_.useState(!1),[yi,Zt]=_.useState("running"),[Jt,di]=_.useState(null),[Zi,Di]=_.useState(!1),[Mi,Ki]=_.useState(0),As=_.useCallback(()=>Ki(ve=>ve+1),[]),[xe,B]=_.useState(fA),Z=_.useRef(xe);_.useEffect(()=>{Z.current=xe},[xe]);const re=!!xe.autoAddToDownloadList,Te=!!xe.autoStartAddedDownloads,[Ke,vt]=_.useState([]),[Tt,Li]=_.useState({}),bi=_.useRef(!1),ji=_.useRef({}),ai=_.useRef([]),Fi=_.useRef({}),li=_.useRef(!1);_.useEffect(()=>{bi.current=Xe},[Xe]),_.useEffect(()=>{ji.current=qt},[qt]),_.useEffect(()=>{ai.current=le},[le]);const $s=_.useRef(null),$i=_.useRef(""),Hi=4,ii=_.useRef([]),Ht=_.useRef(0),Kt=_.useRef(new Set),Ui=_.useRef(!1),rs=_.useCallback(()=>{const ve=Ht.current>0;xt(ve),bi.current=ve},[]),mn=_.useCallback(ve=>{const we=To(ve.url);if(!we)return!1;const ke=vl(we);return Kt.current.has(ke)||(Kt.current.add(ke),ii.current.push({...ve,url:ke}),Ui.current||(Ui.current=!0,queueMicrotask(()=>{Ui.current=!1,je()}))),!0},[]);async function _n(ve,we){if(ve=vl(ve),ai.current.some(Y=>{if(String(Y.status||"").toLowerCase()!=="running"||Y.endedAt)return!1;const ae=To(String(Y.sourceUrl||""));return(ae?vl(ae):"")===ve}))return!0;try{const Y=ji.current,ae=Ih(ve);if(!ae)return we||st("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;if(ae==="chaturbate"&&!Tr(Y))return we||st('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;const _e=Object.entries(Y).map(([Ce,$e])=>`${Ce}=${$e}`).join("; "),Me=await xn("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:ve,cookie:_e})});return Me?.id&&(Fi.current[String(Me.id)]=!0),te(Ce=>[Me,...Ce]),ai.current=[Me,...ai.current],!0}catch(Y){const ae=Y?.message??String(Y);return d(ae)?(f({silent:we}),!1):(we||st(ae),!1)}}async function je(){for(;Ht.current0;){const ve=ii.current.shift();Ht.current++,rs(),(async()=>{try{if(await _n(ve.url,ve.silent)&&ve.pendingKeyLower){const ke=ve.pendingKeyLower;Li(Y=>{const ae={...Y||{}};return delete ae[ke],Ys.current=ae,ae})}}finally{Kt.current.delete(ve.url),Ht.current=Math.max(0,Ht.current-1),rs(),ii.current.length>0&&je()}})()}}const[gt,Ct]=_.useState({}),Vt=_.useRef({}),Bt=_.useRef({}),mi=_.useRef({}),Ut=_.useRef(!1),zi=_.useRef({});_.useEffect(()=>{Vt.current=gt},[gt]);const Si=_.useCallback(ve=>{const we=String(ve?.host??"").toLowerCase(),ke=String(ve?.input??"").toLowerCase();return we.includes("chaturbate")||ke.includes("chaturbate.com")},[]),Ss=_.useMemo(()=>{const ve=new Set;for(const we of Object.values(dt)){if(!Si(we))continue;const ke=Pe(String(we?.modelKey??""));ke&&ve.add(ke)}return Array.from(ve)},[dt,Si]),ks=_.useRef(dt);_.useEffect(()=>{ks.current=dt},[dt]);const Ys=_.useRef(Tt);_.useEffect(()=>{Ys.current=Tt},[Tt]);const En=_.useRef(Ss);_.useEffect(()=>{En.current=Ss},[Ss]);const as=_.useRef(yi);_.useEffect(()=>{as.current=yi},[yi]);const Cs=_.useCallback(async(ve,we)=>{const ke=To(ve);if(!ke)return!1;const Y=vl(ke),ae=!!we?.silent;ae||st(null);const _e=Ih(Y);if(!_e)return ae||st("Nur chaturbate.com oder myfreecams.com werden unterstützt."),!1;const Me=ji.current;if(_e==="chaturbate"&&!Tr(Me))return ae||st('Für Chaturbate müssen die Cookies "cf_clearance" und "sessionId" gesetzt sein.'),!1;if(ai.current.some($e=>{if(String($e.status||"").toLowerCase()!=="running"||$e.endedAt)return!1;const tt=To(String($e.sourceUrl||""));return(tt?vl(tt):"")===Y}))return!0;if(_e==="chaturbate"&&Z.current.useChaturbateApi)try{const $e=await xn("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:Y})}),tt=String($e?.modelKey??"").trim().toLowerCase();if(tt){if(bi.current)return Li(at=>({...at||{},[tt]:Y})),!0;const ut=Vt.current[tt],Qe=String(ut?.current_show??"");if(ut&&Qe&&Qe!=="public")return Li(at=>({...at||{},[tt]:Y})),!0}}catch{}else if(bi.current)return $s.current=Y,!0;if(bi.current)return!1;xt(!0),bi.current=!0;try{const $e=Object.entries(Me).map(([ut,Qe])=>`${ut}=${Qe}`).join("; "),tt=await xn("/api/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:Y,cookie:$e})});return tt?.id&&(Fi.current[String(tt.id)]=!0),te(ut=>[tt,...ut]),ai.current=[tt,...ai.current],!0}catch($e){const tt=$e?.message??String($e);return d(tt)?(f({silent:ae}),!1):(ae||st(tt),!1)}finally{xt(!1),bi.current=!1}},[]);_.useEffect(()=>{let ve=!1;const we=async()=>{try{const ae=await xn("/api/settings",{cache:"no-store"});!ve&&ae&&B({...fA,...ae})}catch{}},ke=()=>{we()},Y=()=>{we()};return window.addEventListener("recorder-settings-updated",ke),window.addEventListener("focus",Y),document.addEventListener("visibilitychange",Y),we(),()=>{ve=!0,window.removeEventListener("recorder-settings-updated",ke),window.removeEventListener("focus",Y),document.removeEventListener("visibilitychange",Y)}},[]),_.useEffect(()=>{let ve=!1;const we=async()=>{try{const Y=await xn("/api/models/meta",{cache:"no-store"}),ae=Number(Y?.count??0);!ve&&Number.isFinite(ae)&&(se(ae),Ve(Date.now()))}catch{}};we();const ke=window.setInterval(we,document.hidden?6e4:3e4);return()=>{ve=!0,window.clearInterval(ke)}},[]);const Mn=_.useMemo(()=>Object.entries(qt).map(([ve,we])=>({name:ve,value:we})),[qt]),hs=_.useCallback(ve=>{wt.current=null,nt(null),di(ve),Di(!1)},[]),Wi=le.filter(ve=>{const we=String(ve?.status??"").toLowerCase();return we==="running"||we==="postwork"}),Yi=_.useMemo(()=>{let ve=0;for(const we of Object.values(dt)){if(!we?.watching||!Si(we))continue;const ke=Pe(String(we?.modelKey??""));ke&>[ke]&&ve++}return ve},[dt,gt,Si]),{onlineFavCount:_s,onlineLikedCount:Zn}=_.useMemo(()=>{let ve=0,we=0;for(const ke of Object.values(dt)){const Y=Pe(String(ke?.modelKey??""));Y&>[Y]&&(ke?.favorite&&ve++,ke?.liked===!0&&we++)}return{onlineFavCount:ve,onlineLikedCount:we}},[dt,gt]),Pn=[{id:"running",label:"Laufende Downloads",count:Wi.length},{id:"finished",label:"Abgeschlossene Downloads",count:oe},{id:"models",label:"Models",count:X},{id:"categories",label:"Kategorien"},{id:"settings",label:"Einstellungen"}],Qa=_.useMemo(()=>K.trim().length>0&&!Xe,[K,Xe]);_.useEffect(()=>{let ve=!1;return(async()=>{try{const ke=await xn("/api/cookies",{cache:"no-store"}),Y=Xm(ke?.cookies);if(ve||It(Y),Object.keys(Y).length===0){const ae=localStorage.getItem(Jv);if(ae)try{const _e=JSON.parse(ae),Me=Xm(_e);Object.keys(Me).length>0&&(ve||It(Me),await xn("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:Me})}))}catch{}}}catch{const ke=localStorage.getItem(Jv);if(ke)try{const Y=JSON.parse(ke);ve||It(Xm(Y))}catch{}}finally{ve||Gt(!0)}})(),()=>{ve=!0}},[]),_.useEffect(()=>{ni&&localStorage.setItem(Jv,JSON.stringify(qt))},[qt,ni]),_.useEffect(()=>{M();const ve=()=>{document.hidden||M()};return document.addEventListener("visibilitychange",ve),()=>{document.removeEventListener("visibilitychange",ve)}},[M]);const wn=_.useCallback(async ve=>{H.current&&R.current?.abort();const we=new AbortController;R.current=we,H.current=!0;try{const ke=typeof ve=="number"?ve:J,Y=await fetch(`/api/record/done?page=${ke}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1`,{cache:"no-store",signal:we.signal});if(!Y.ok)throw new Error(`HTTP ${Y.status}`);const ae=await Y.json().catch(()=>null),_e=Array.isArray(ae?.items)?ae.items:Array.isArray(ae)?ae:[],Me=Number(ae?.count??ae?.totalCount??_e.length),Ce=Number.isFinite(Me)&&Me>=0?Me:_e.length;j(Ce);const $e=Math.max(1,Math.ceil(Ce/v)),tt=Math.min(Math.max(1,ke),$e);if(tt!==J&&ie(tt),tt!==ke){const ut=await fetch(`/api/record/done?page=${tt}&pageSize=${v}&sort=${encodeURIComponent(S)}&withCount=1`,{cache:"no-store",signal:we.signal});if(!ut.ok)throw new Error(`HTTP ${ut.status}`);const Qe=await ut.json().catch(()=>null),at=Array.isArray(Qe?.items)?Qe.items:[];G(at)}else G(_e);Ve(Date.now())}catch(ke){String(ke?.name)}finally{R.current===we&&(R.current=null,H.current=!1)}},[J,S]);_.useEffect(()=>{if(yi!=="finished")return;M(),W();const ve=()=>{document.hidden||(M(),W())};return document.addEventListener("visibilitychange",ve),()=>{document.removeEventListener("visibilitychange",ve)}},[yi,M,W]),_.useEffect(()=>{const ve=Math.max(1,Math.ceil(oe/v));J>ve&&ie(ve)},[oe,J]),_.useEffect(()=>{if(!t)return;let ve=null,we=null;const ke=()=>{we!=null&&(window.clearInterval(we),we=null)},Y=()=>{we==null&&(we=window.setInterval(()=>{document.hidden||(as.current==="finished"?(M(),W()):M())},document.hidden?6e4:15e3))},ae={t:0};let _e=null;const Me=()=>{const tt=Date.now();if(tt-ae.t<800){if(_e!=null)return;_e=window.setTimeout(()=>{_e=null,ae.t=Date.now(),as.current==="finished"?(M(),W()):M()},900);return}ae.t=tt,as.current==="finished"?(M(),W()):M()};M(),ve=new EventSource("/api/record/done/stream"),ve.onopen=()=>{ke()},ve.onerror=()=>{Y()};const Ce=()=>Me();ve.addEventListener("doneChanged",Ce);const $e=()=>{document.hidden||Me()};return document.addEventListener("visibilitychange",$e),()=>{document.removeEventListener("visibilitychange",$e),_e!=null&&window.clearTimeout(_e),ke(),ve?.removeEventListener("doneChanged",Ce),ve?.close(),ve=null}},[t,M,W]),_.useEffect(()=>{if(!t)return;D();const ve=window.setInterval(()=>{if(document.hidden)return;const ke=ai.current.some(Y=>{const ae=String(Y?.status??"").toLowerCase();return ae==="running"||ae==="postwork"});(as.current==="running"||ke)&&D()},document.hidden?6e4:3e3),we=()=>{document.hidden||D()};return document.addEventListener("visibilitychange",we),()=>{window.clearInterval(ve),document.removeEventListener("visibilitychange",we)}},[t,D]);function vs(ve){const we=To(ve);if(!we)return!1;try{return new URL(we).hostname.includes("chaturbate.com")}catch{return!1}}function Ji(ve,we){const ke=Object.fromEntries(Object.entries(ve).map(([Y,ae])=>[Y.trim().toLowerCase(),ae]));for(const Y of we){const ae=ke[Y.toLowerCase()];if(ae)return ae}}function Tr(ve){const we=Ji(ve,["cf_clearance"]),ke=Ji(ve,["sessionid","session_id","sessionId"]);return!!(we&&ke)}async function Ds(ve){try{await xn(`/api/record/stop?id=${encodeURIComponent(ve)}`,{method:"POST"})}catch(we){a.error("Stop fehlgeschlagen",we?.message??String(we))}}_.useEffect(()=>{const ve=we=>{const Y=Number(we.detail?.delta??0);if(!Number.isFinite(Y)||Y===0){M(),W();return}j(ae=>Math.max(0,ae+Y)),M(),W()};return window.addEventListener("finished-downloads:count-hint",ve),()=>window.removeEventListener("finished-downloads:count-hint",ve)},[M,W]),_.useEffect(()=>{const ve=we=>{const ke=we.detail||{};ke.tab==="finished"&&Zt("finished"),ke.tab==="categories"&&Zt("categories"),ke.tab==="models"&&Zt("models"),ke.tab==="running"&&Zt("running"),ke.tab==="settings"&&Zt("settings")};return window.addEventListener("app:navigate-tab",ve),()=>window.removeEventListener("app:navigate-tab",ve)},[]),_.useEffect(()=>{if(!Jt){nt(null),Q(null);return}const ve=(lh(Jt.output||"")||"").trim().toLowerCase();Q(ve||null);const we=ve?dt[ve]:void 0;nt(we??null)},[Jt,dt]);async function Ee(){return Cs(K)}const Ie=_.useCallback(async ve=>{const we=String(ve?.sourceUrl??""),ke=ou(we);if(!ke)return!1;const Y=To(ke);if(!Y)return!1;const ae=vl(Y),_e=await Cs(ae,{silent:!0});return _e||a.error("Konnte URL nicht hinzufügen","Start fehlgeschlagen oder URL ungültig."),_e},[Cs,a]),Ue=_.useCallback(async ve=>{const we=qs(ve.output||"");if(we){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"start"}}));try{const ke=await xn(`/api/record/delete?file=${encodeURIComponent(we)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"success"}})),window.setTimeout(()=>{G(ae=>{const _e=ae.filter(Qe=>qs(Qe.output||"")!==we);if(v-_e.length<=0)return _e;const Ce=F(J+1,S),$e=L.current;if(!$e||$e.key!==Ce||!Array.isArray($e.items)||$e.items.length===0)return _e;const tt=[..._e],ut=new Set(tt.map(Qe=>String(Qe.id||qs(Qe.output||"")).trim()));for(;tt.length0;){const Qe=$e.items.shift(),at=String(Qe.id||qs(Qe.output||"")).trim();!at||ut.has(at)||(ut.add(at),tt.push(Qe))}return L.current={...$e,items:$e.items,ts:$e.ts},tt}),j(ae=>Math.max(0,ae-1)),te(ae=>ae.filter(_e=>qs(_e.output||"")!==we)),di(ae=>ae&&qs(ae.output||"")===we?null:ae),$(J+1)},320);const Y=typeof ke?.undoToken=="string"?ke.undoToken:"";return Y?{undoToken:Y}:{}}catch{window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"error"}})),a.error("Löschen fehlgeschlagen: ",we);return}}},[a,wn]),it=_.useCallback(async ve=>{await Ue(ve)},[Ue]),St=_.useCallback(async ve=>{const we=qs(ve.output||"");if(we){window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"start"}}));try{await xn(`/api/record/keep?file=${encodeURIComponent(we)}`,{method:"POST"}),window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"success"}})),window.setTimeout(()=>{G(ke=>ke.filter(Y=>qs(Y.output||"")!==we)),te(ke=>ke.filter(Y=>qs(Y.output||"")!==we)),di(ke=>ke&&qs(ke.output||"")===we?null:ke)},320)}catch{window.dispatchEvent(new CustomEvent("finished-downloads:delete",{detail:{file:we,phase:"error"}})),a.error("Keep fehlgeschlagen",we);return}}},[yi,wn,a]),ei=_.useCallback(async ve=>{const we=qs(ve.output||"");if(we)try{window.dispatchEvent(new CustomEvent("player:release",{detail:{file:we}})),await new Promise(ae=>window.setTimeout(ae,60));const ke=await xn(`/api/record/toggle-hot?file=${encodeURIComponent(we)}`,{method:"POST"});window.dispatchEvent(new CustomEvent("finished-downloads:rename",{detail:{oldFile:ke.oldFile,newFile:ke.newFile}}));const Y=ae=>vH(ae||"",ke.newFile);return di(ae=>ae&&{...ae,output:Y(ae.output||"")}),G(ae=>ae.map(_e=>_e.id===ve.id||qs(_e.output||"")===we?{..._e,output:Y(_e.output||"")}:_e)),te(ae=>ae.map(_e=>_e.id===ve.id||qs(_e.output||"")===we?{..._e,output:Y(_e.output||"")}:_e)),ke}catch(ke){a.error("Umbenennen fehlgeschlagen",ke?.message??String(ke));return}},[a]);async function Yt(ve){const we=await fetch("/api/models/flags",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ve)});if(we.status===204)return null;if(!we.ok){const ke=await we.text().catch(()=>"");throw new Error(ke||`HTTP ${we.status}`)}return we.json()}const Ri=_.useCallback(ve=>{const we=wt.current;!we||!ve||(we.ts=Date.now(),we.list=we.list.filter(ke=>ke.id!==ve))},[]),Ti=_.useRef({}),Bn=_.useCallback(async ve=>{const we=qs(ve.output||""),ke=!!(Jt&&qs(Jt.output||"")===we),Y=Qe=>{try{const at=String(Qe.sourceUrl??Qe.SourceURL??""),pt=ou(at);return pt?new URL(pt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},ae=(lh(ve.output||"")||"").trim().toLowerCase();if(ae){const Qe=ae;if(Ti.current[Qe])return;Ti.current[Qe]=!0;const at=dt[ae]??{id:"",input:"",host:Y(ve)||void 0,modelKey:ae,watching:!1,favorite:!1,liked:null,isUrl:!1},pt=!at.favorite,Mt={...at,modelKey:at.modelKey||ae,favorite:pt,liked:pt?!1:at.liked};Ge(Nt=>({...Nt,[ae]:Mt})),ye(Mt),ke&&nt(Mt);try{const Nt=await Yt({...Mt.id?{id:Mt.id}:{},host:Mt.host||Y(ve)||"",modelKey:ae,favorite:pt,...pt?{liked:!1}:{}});if(!Nt){Ge(Xt=>{const{[ae]:zt,...ui}=Xt;return ui}),at.id&&Ri(at.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:ae}}));return}const Ft=Pe(Nt.modelKey||ae);Ft&&Ge(Xt=>({...Xt,[Ft]:Nt})),ye(Nt),ke&&nt(Nt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Nt}}))}catch(Nt){Ge(Ft=>({...Ft,[ae]:at})),ye(at),ke&&nt(at),a.error("Favorit umschalten fehlgeschlagen",Nt?.message??String(Nt))}finally{delete Ti.current[Qe]}return}let _e=ke?bt:null;if(_e||(_e=await Ls(ve,{ensure:!0})),!_e)return;const Me=Pe(_e.modelKey||_e.id||"");if(!Me||Ti.current[Me])return;Ti.current[Me]=!0;const Ce=_e,$e=!Ce.favorite,tt={...Ce,favorite:$e,liked:$e?!1:Ce.liked},ut=Pe(Ce.modelKey||"");ut&&Ge(Qe=>({...Qe,[ut]:tt})),ye(tt),ke&&nt(tt);try{const Qe=await Yt({id:Ce.id,favorite:$e,...$e?{liked:!1}:{}});if(!Qe){Ge(pt=>{const Mt=Pe(Ce.modelKey||"");if(!Mt)return pt;const{[Mt]:Nt,...Ft}=pt;return Ft}),Ri(Ce.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Ce.id,modelKey:Ce.modelKey}}));return}const at=Pe(Qe.modelKey||"");at&&Ge(pt=>({...pt,[at]:Qe})),ye(Qe),ke&&nt(Qe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Qe}}))}catch(Qe){const at=Pe(Ce.modelKey||"");at&&Ge(pt=>({...pt,[at]:Ce})),ye(Ce),ke&&nt(Ce),a.error("Favorit umschalten fehlgeschlagen",Qe?.message??String(Qe))}finally{delete Ti.current[Me]}},[a,Jt,bt,Ls,Yt,ye,Ri,dt]),An=_.useCallback(async ve=>{const we=qs(ve.output||""),ke=!!(Jt&&qs(Jt.output||"")===we),Y=Qe=>{try{const at=String(Qe.sourceUrl??Qe.SourceURL??""),pt=ou(at);return pt?new URL(pt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},ae=(lh(ve.output||"")||"").trim().toLowerCase();if(ae){const Qe=ae;if(Ti.current[Qe])return;Ti.current[Qe]=!0;const at=dt[ae]??{id:"",input:"",host:Y(ve)||void 0,modelKey:ae,watching:!1,favorite:!1,liked:null,isUrl:!1},pt=at.liked!==!0,Mt={...at,modelKey:at.modelKey||ae,liked:pt,favorite:pt?!1:at.favorite};Ge(Nt=>({...Nt,[ae]:Mt})),ye(Mt),ke&&nt(Mt);try{const Nt=await Yt({...Mt.id?{id:Mt.id}:{},host:Mt.host||Y(ve)||"",modelKey:ae,liked:pt,...pt?{favorite:!1}:{}});if(!Nt){Ge(Xt=>{const{[ae]:zt,...ui}=Xt;return ui}),at.id&&Ri(at.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:ae}}));return}const Ft=Pe(Nt.modelKey||ae);Ft&&Ge(Xt=>({...Xt,[Ft]:Nt})),ye(Nt),ke&&nt(Nt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Nt}}))}catch(Nt){Ge(Ft=>({...Ft,[ae]:at})),ye(at),ke&&nt(at),a.error("Like umschalten fehlgeschlagen",Nt?.message??String(Nt))}finally{delete Ti.current[Qe]}return}let _e=ke?bt:null;if(_e||(_e=await Ls(ve,{ensure:!0})),!_e)return;const Me=Pe(_e.modelKey||_e.id||"");if(!Me||Ti.current[Me])return;Ti.current[Me]=!0;const Ce=_e,$e=Ce.liked!==!0,tt={...Ce,liked:$e,favorite:$e?!1:Ce.favorite},ut=Pe(Ce.modelKey||"");ut&&Ge(Qe=>({...Qe,[ut]:tt})),ye(tt),ke&&nt(tt);try{const Qe=$e?await Yt({id:Ce.id,liked:!0,favorite:!1}):await Yt({id:Ce.id,liked:!1});if(!Qe){Ge(pt=>{const Mt=Pe(Ce.modelKey||"");if(!Mt)return pt;const{[Mt]:Nt,...Ft}=pt;return Ft}),Ri(Ce.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Ce.id,modelKey:Ce.modelKey}}));return}const at=Pe(Qe.modelKey||"");at&&Ge(pt=>({...pt,[at]:Qe})),ye(Qe),ke&&nt(Qe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Qe}}))}catch(Qe){const at=Pe(Ce.modelKey||"");at&&Ge(pt=>({...pt,[at]:Ce})),ye(Ce),ke&&nt(Ce),a.error("Like umschalten fehlgeschlagen",Qe?.message??String(Qe))}finally{delete Ti.current[Me]}},[a,Jt,bt,Ls,Yt,ye,Ri,dt]),Fn=_.useCallback(async ve=>{const we=qs(ve.output||""),ke=!!(Jt&&qs(Jt.output||"")===we),Y=Qe=>{try{const at=String(Qe.sourceUrl??Qe.SourceURL??""),pt=ou(at);return pt?new URL(pt).hostname.replace(/^www\./i,"").toLowerCase():""}catch{return""}},ae=(lh(ve.output||"")||"").trim().toLowerCase();if(ae){const Qe=ae;if(Ti.current[Qe])return;Ti.current[Qe]=!0;const at=dt[ae]??{id:"",input:"",host:Y(ve)||void 0,modelKey:ae,watching:!1,favorite:!1,liked:null,isUrl:!1},pt=!at.watching,Mt={...at,modelKey:at.modelKey||ae,watching:pt};Ge(Nt=>({...Nt,[ae]:Mt})),ye(Mt),ke&&nt(Mt);try{const Nt=await Yt({...Mt.id?{id:Mt.id}:{},host:Mt.host||Y(ve)||"",modelKey:ae,watched:pt});if(!Nt){Ge(Xt=>{const{[ae]:zt,...ui}=Xt;return ui}),at.id&&Ri(at.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:at.id,modelKey:ae}}));return}const Ft=Pe(Nt.modelKey||ae);Ft&&Ge(Xt=>({...Xt,[Ft]:Nt})),ye(Nt),ke&&nt(Nt),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Nt}}))}catch(Nt){Ge(Ft=>({...Ft,[ae]:at})),ye(at),ke&&nt(at),a.error("Watched umschalten fehlgeschlagen",Nt?.message??String(Nt))}finally{delete Ti.current[Qe]}return}let _e=ke?bt:null;if(_e||(_e=await Ls(ve,{ensure:!0})),!_e)return;const Me=Pe(_e.modelKey||_e.id||"");if(!Me||Ti.current[Me])return;Ti.current[Me]=!0;const Ce=_e,$e=!Ce.watching,tt={...Ce,watching:$e},ut=Pe(Ce.modelKey||"");ut&&Ge(Qe=>({...Qe,[ut]:tt})),ye(tt),ke&&nt(tt);try{const Qe=await Yt({id:Ce.id,watched:$e});if(!Qe){Ge(pt=>{const Mt=Pe(Ce.modelKey||"");if(!Mt)return pt;const{[Mt]:Nt,...Ft}=pt;return Ft}),Ri(Ce.id),ke&&nt(null),window.dispatchEvent(new CustomEvent("models-changed",{detail:{removed:!0,id:Ce.id,modelKey:Ce.modelKey}}));return}const at=Pe(Qe.modelKey||"");at&&Ge(pt=>({...pt,[at]:Qe})),ye(Qe),ke&&nt(Qe),window.dispatchEvent(new CustomEvent("models-changed",{detail:{model:Qe}}))}catch(Qe){const at=Pe(Ce.modelKey||"");at&&Ge(pt=>({...pt,[at]:Ce})),ye(Ce),ke&&nt(Ce),a.error("Watched umschalten fehlgeschlagen",Qe?.message??String(Qe))}finally{delete Ti.current[Me]}},[a,Jt,bt,Ls,Yt,ye,Ri,dt]);async function Ls(ve,we){const ke=!!we?.ensure,Y=tt=>{const ut=Date.now(),Qe=wt.current;if(!Qe){wt.current={ts:ut,list:[tt]};return}Qe.ts=ut;const at=Qe.list.findIndex(pt=>pt.id===tt.id);at>=0?Qe.list[at]=tt:Qe.list.unshift(tt)},ae=async tt=>{if(!tt)return null;const ut=tt.trim().toLowerCase();if(!ut)return null;const Qe=dt[ut];if(Qe)return Y(Qe),Qe;if(ke){let Ft;try{const zt=ve.sourceUrl??ve.SourceURL??"",ui=ou(zt);ui&&(Ft=new URL(ui).hostname.replace(/^www\./i,"").toLowerCase())}catch{}const Xt=await xn("/api/models/ensure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({modelKey:tt,...Ft?{host:Ft}:{}})});return ye(Xt),Xt}const at=Date.now(),pt=wt.current;if(!pt||at-pt.ts>3e4){const Ft=Object.values(dt);if(Ft.length)wt.current={ts:at,list:Ft};else{const Xt=await xn("/api/models/list",{cache:"no-store"});wt.current={ts:at,list:Array.isArray(Xt)?Xt:[]}}}const Nt=(wt.current?.list??[]).find(Ft=>(Ft.modelKey||"").trim().toLowerCase()===ut);return Nt||null},_e=lh(ve.output||"");if(_e)return ae(_e);const Me=ve.status==="running",Ce=ve.sourceUrl??ve.SourceURL??"",$e=ou(Ce);if(Me&&$e){const tt=await xn("/api/models/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:$e})}),ut=await xn("/api/models/upsert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(tt)});return ye(ut),ut}return null}return _.useEffect(()=>{if(!re&&!Te||!navigator.clipboard?.readText)return;let ve=!1,we=!1,ke=null;const Y=async()=>{if(!(ve||we)){we=!0;try{const Me=await navigator.clipboard.readText(),Ce=ou(Me);if(!Ce)return;const $e=To(Ce);if(!$e||!Ih($e))return;const ut=vl($e);if(ut===$i.current)return;$i.current=ut,re&&q(ut),Te&&mn({url:ut,silent:!1})}catch{}finally{we=!1}}},ae=Me=>{ve||(ke=window.setTimeout(async()=>{await Y(),ae(document.hidden?5e3:1500)},Me))},_e=()=>{Y()};return window.addEventListener("hover",_e),document.addEventListener("visibilitychange",_e),ae(0),()=>{ve=!0,ke&&window.clearTimeout(ke),window.removeEventListener("hover",_e),document.removeEventListener("visibilitychange",_e)}},[re,Te,Cs]),_.useEffect(()=>{const ve=dA({getModels:()=>{if(!Z.current.useChaturbateApi)return[];const we=ks.current,ke=Ys.current,Y=Object.values(we).filter(_e=>!!_e?.watching&&String(_e?.host??"").toLowerCase().includes("chaturbate")).map(_e=>String(_e?.modelKey??"").trim().toLowerCase()).filter(Boolean),ae=Object.keys(ke||{}).map(_e=>String(_e||"").trim().toLowerCase()).filter(Boolean);return Array.from(new Set([...Y,...ae]))},getShow:()=>["public","private","hidden","away"],intervalMs:8e3,onData:we=>{(async()=>{if(!we?.enabled){Ct({}),Vt.current={},Bt.current={},vt([]),zi.current={},Ut.current=!1,mi.current={},Ve(Date.now());return}const ke={};for(const Me of Array.isArray(we.rooms)?we.rooms:[]){const Ce=String(Me?.username??"").trim().toLowerCase();Ce&&(ke[Ce]=Me)}Ct(ke),Vt.current=ke;try{const Me=!!(Z.current.enableNotifications??!0),Ce=new Set(["private","away","hidden"]),$e=new Set(Object.values(ks.current||{}).filter(Ft=>!!Ft?.watching&&String(Ft?.host??"").toLowerCase().includes("chaturbate")).map(Ft=>String(Ft?.modelKey??"").trim().toLowerCase()).filter(Boolean)),tt=Bt.current||{},ut={...tt},Qe=mi.current||{},at=!Ut.current,pt=zi.current||{},Mt={...pt};for(const[Ft,Xt]of Object.entries(ke)){const zt=String(Xt?.current_show??"").toLowerCase().trim(),ui=String(tt[Ft]??"").toLowerCase().trim(),Es=!0&&!!!Qe[Ft],zr=!!pt[Ft],pn=String(Xt?.username??Ft).trim()||Ft,Jn=String(Xt?.image_url??"").trim();if(Mt[Ft]=!0,zt==="public"&&Ce.has(ui)){Me&&a.info(pn,"ist wieder online.",{imageUrl:Jn,imageAlt:`${pn} Vorschau`,durationMs:5500}),zt&&(ut[Ft]=zt);continue}if($e.has(Ft)&&Es){const xs=zr;Me&&!at&&a.info(pn,xs?"ist wieder online.":"ist online.",{imageUrl:Jn,imageAlt:`${pn} Vorschau`,durationMs:5500})}zt&&(ut[Ft]=zt)}const Nt={};for(const Ft of Object.keys(ke))Nt[Ft]=!0;mi.current=Nt,zi.current=Mt,Ut.current=!0,Bt.current=ut}catch{}const Y=En.current;for(const Me of Y||[]){const Ce=String(Me||"").trim().toLowerCase();Ce&&ke[Ce]}if(!Z.current.useChaturbateApi)vt([]);else if(as.current==="running"){const Me=ks.current,Ce=Ys.current,$e=Array.from(new Set(Object.values(Me).filter(at=>!!at?.watching&&String(at?.host??"").toLowerCase().includes("chaturbate")).map(at=>String(at?.modelKey??"").trim().toLowerCase()).filter(Boolean))),tt=Object.keys(Ce||{}).map(at=>String(at||"").trim().toLowerCase()).filter(Boolean),ut=new Set(tt),Qe=Array.from(new Set([...$e,...tt]));if(Qe.length===0)vt([]);else{const at=[];for(const pt of Qe){const Mt=ke[pt];if(!Mt)continue;const Nt=String(Mt?.username??"").trim(),Ft=String(Mt?.current_show??"unknown");if(Ft==="public"&&!ut.has(pt))continue;const Xt=`https://chaturbate.com/${(Nt||pt).trim()}/`;at.push({id:pt,modelKey:Nt||pt,url:Xt,currentShow:Ft,imageUrl:String(Mt?.image_url??"")})}at.sort((pt,Mt)=>pt.modelKey.localeCompare(Mt.modelKey,void 0,{sensitivity:"base"})),vt(at)}}if(!Z.current.useChaturbateApi||bi.current)return;const ae=Ys.current,_e=Object.keys(ae||{}).map(Me=>String(Me||"").toLowerCase()).filter(Boolean);for(const Me of _e){const Ce=ke[Me];if(!Ce||String(Ce.current_show??"")!=="public")continue;const $e=ae[Me];$e&&mn({url:$e,silent:!0,pendingKeyLower:Me})}Ve(Date.now())})()}});return()=>ve()},[]),_.useEffect(()=>{if(!xe.useChaturbateApi){pe(0);return}const ve=dA({getModels:()=>[],getShow:()=>["public","private","hidden","away"],intervalMs:3e4,fetchAllWhenNoModels:!0,onData:we=>{if(!we?.enabled){pe(0);return}const ke=Number(we?.total??0);pe(Number.isFinite(ke)?ke:0),Ve(Date.now())},onError:we=>{console.error("[ALL-online poller] error",we)}});return()=>ve()},[xe.useChaturbateApi]),s?t?g.jsxs("div",{className:"min-h-[100dvh] bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100",children:[g.jsxs("div",{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 overflow-hidden",children:[g.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"}),g.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"})]}),g.jsxs("div",{className:"relative",children:[g.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:g.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:[g.jsxs("div",{className:"flex items-center sm:items-start justify-between gap-3 sm:gap-4",children:[g.jsx("div",{className:"min-w-0",children:g.jsxs("div",{className:"min-w-0",children:[g.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[g.jsx("h1",{className:"text-lg font-semibold tracking-tight text-gray-900 dark:text-white",children:"Recorder"}),g.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.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:[g.jsx(RM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:fe})]}),g.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:[g.jsx(_u,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:Yi})]}),g.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:[g.jsx(Eu,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:_s})]}),g.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:[g.jsx(EM,{className:"size-4 opacity-80"}),g.jsx("span",{className:"tabular-nums",children:Zn})]})]}),g.jsx("div",{className:"hidden sm:block text-[11px] text-gray-500 dark:text-gray-400",children:qe})]}),g.jsxs("div",{className:"sm:hidden mt-1 w-full",children:[g.jsx("div",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:qe}),g.jsxs("div",{className:"mt-2 flex items-stretch gap-2",children:[p?g.jsx(cA,{mode:"inline",className:"flex-1"}):g.jsx("div",{className:"flex-1"}),g.jsx(oi,{variant:"secondary",onClick:()=>Pt(!0),className:"px-3 shrink-0",children:"Cookies"}),g.jsx(oi,{variant:"secondary",onClick:r,className:"px-3 shrink-0",children:"Abmelden"})]})]})]})}),g.jsxs("div",{className:"hidden sm:flex items-center gap-2 h-full",children:[p?g.jsx(cA,{mode:"inline"}):null,g.jsx(oi,{variant:"secondary",onClick:()=>Pt(!0),className:"h-9 px-3",children:"Cookies"}),g.jsx(oi,{variant:"secondary",onClick:r,className:"h-9 px-3",children:"Abmelden"})]})]}),g.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-stretch",children:[g.jsxs("div",{className:"relative",children:[g.jsx("label",{className:"sr-only",children:"Source URL"}),g.jsx("input",{value:K,onChange:ve=>q(ve.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"})]}),g.jsx(oi,{variant:"primary",onClick:Ee,disabled:!Qa,className:"w-full sm:w-auto rounded-lg",children:"Start"})]}),mt?g.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:g.jsxs("div",{className:"flex items-start justify-between gap-3",children:[g.jsx("div",{className:"min-w-0 break-words",children:mt}),g.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:()=>st(null),"aria-label":"Fehlermeldung schließen",title:"Schließen",children:"✕"})]})}):null,vs(K)&&!Tr(qt)?g.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:["⚠️ Für Chaturbate werden die Cookies ",g.jsx("code",{children:"cf_clearance"})," und ",g.jsx("code",{children:"sessionId"})," benötigt."]}):null,Xe?g.jsx("div",{className:"pt-1",children:g.jsx(Vh,{label:"Starte Download…",indeterminate:!0})}):null,g.jsx("div",{className:"hidden sm:block pt-2",children:g.jsx(ox,{tabs:Pn,value:yi,onChange:Zt,ariaLabel:"Tabs",variant:"barUnderline"})})]})}),g.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:g.jsx("div",{className:"mx-auto max-w-7xl px-4 py-2",children:g.jsx(ox,{tabs:Pn,value:yi,onChange:Zt,ariaLabel:"Tabs",variant:"barUnderline"})})}),g.jsxs("main",{className:"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-6 space-y-6",children:[yi==="running"?g.jsx(P$,{jobs:Wi,modelsByKey:dt,pending:Ke,onOpenPlayer:hs,onStopJob:Ds,onToggleFavorite:Bn,onToggleLike:An,onToggleWatch:Fn,onAddToDownloads:Ie,blurPreviews:!!xe.blurPreviews}):null,yi==="finished"?g.jsx(c3,{jobs:le,modelsByKey:dt,doneJobs:V,doneTotal:oe,page:J,pageSize:v,onPageChange:ie,onOpenPlayer:hs,onDeleteJob:Ue,onToggleHot:ei,onToggleFavorite:Bn,onToggleLike:An,onToggleWatch:Fn,blurPreviews:!!xe.blurPreviews,teaserPlayback:xe.teaserPlayback??"hover",teaserAudio:!!xe.teaserAudio,assetNonce:Mi,sortMode:S,onSortModeChange:ve=>{E(ve),ie(1)},loadMode:"all"}):null,yi==="models"?g.jsx(H$,{}):null,yi==="categories"?g.jsx(cH,{}):null,yi==="settings"?g.jsx(TO,{onAssetsGenerated:As}):null]}),g.jsx(dO,{open:ft,onClose:()=>Pt(!1),initialCookies:Mn,onApply:ve=>{const we=Xm(Object.fromEntries(ve.map(ke=>[ke.name,ke.value])));It(we),xn("/api/cookies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cookies:we})}).catch(()=>{})}}),g.jsx(eH,{open:!!ht,modelKey:ht,onClose:()=>Et(null),onOpenPlayer:hs,runningJobs:Wi,cookies:qt,blurPreviews:xe.blurPreviews,onToggleHot:ei,onDelete:it,onToggleFavorite:Bn,onToggleLike:An,onToggleWatch:Fn}),Jt?g.jsx(R$,{job:Jt,modelKey:I??void 0,modelsByKey:dt,expanded:Zi,onToggleExpand:()=>Di(ve=>!ve),onClose:()=>di(null),isHot:qs(Jt.output||"").startsWith("HOT "),isFavorite:!!bt?.favorite,isLiked:bt?.liked===!0,isWatching:!!bt?.watching,onKeep:St,onDelete:it,onToggleHot:ei,onToggleFavorite:Bn,onToggleLike:An,onStopJob:Ds,onToggleWatch:Fn},[String(Jt?.id??""),qs(Jt.output||""),String(Mi)].join("::")):null]})]}):g.jsx(gH,{onLoggedIn:n}):g.jsx("div",{className:"min-h-[100dvh] grid place-items-center",children:"Lade…"})}pA.createRoot(document.getElementById("root")).render(g.jsx(_.StrictMode,{children:g.jsx(r3,{position:"top-right",maxToasts:3,defaultDurationMs:3500,children:g.jsx(TH,{})})}));