@camstack/addon-pipeline 1.2.16 → 1.2.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-CaRFwVIZ.js → MaskShapeCanvas-DI4BY7W2-Hg_mGtXA.js} +1 -1
- package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-o7HcwAxC.js → MotionZonesSettings-NcxxQN8r-C0-pVeBX.js} +1 -1
- package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-B2TnFjvh.js → PrivacyMaskSettings-APgPLF7p-QVePTd0g.js} +1 -1
- package/embed-dist/assets/{index-D4RNu5XI.js → index-CsaHbiy9.js} +5 -5
- package/embed-dist/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-NcxxQN8r-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MotionZonesSettings-NcxxQN8r-C0-pVeBX.js","./MaskShapeCanvas-DI4BY7W2-Hg_mGtXA.js","./PrivacyMaskSettings-APgPLF7p-QVePTd0g.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,n)=>{let r={};for(var a in e)t(r,a,{get:e[a],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},l=(e,a,s,c)=>{if(a&&typeof a==`object`||typeof a==`function`)for(var l=r(a),u=0,d=l.length,f;u<d;u++)f=l[u],!o.call(e,f)&&f!==s&&t(e,f,{get:(e=>a[e]).bind(null,f),enumerable:!(c=n(a,f))||c.enumerable});return e},u=(n,r,o)=>(o=n==null?{}:e(a(n)),l(r||!n||!n.__esModule?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var d=s((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,o=e[r];if(0<a(o,t))e[r]=t,e[n]=o,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,o=e.length,s=o>>>1;r<s;){var c=2*(r+1)-1,l=e[c],u=c+1,d=e[u];if(0>a(l,n))u<o&&0>a(d,l)?(e[r]=d,e[u]=n,r=u):(e[r]=l,e[c]=n,r=c);else if(u<o&&0>a(d,n))e[r]=d,e[u]=n,r=u;else break a}}return t}function a(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var o=performance;e.unstable_now=function(){return o.now()}}else{var s=Date,c=s.now();e.unstable_now=function(){return s.now()-c}}var l=[],u=[],d=1,f=null,p=3,m=!1,h=!1,g=!1,_=!1,v=typeof setTimeout==`function`?setTimeout:null,y=typeof clearTimeout==`function`?clearTimeout:null,b=typeof setImmediate<`u`?setImmediate:null;function x(e){for(var a=n(u);a!==null;){if(a.callback===null)r(u);else if(a.startTime<=e)r(u),a.sortIndex=a.expirationTime,t(l,a);else break;a=n(u)}}function S(e){if(g=!1,x(e),!h)if(n(l)!==null)h=!0,C||(C=!0,te());else{var t=n(u);t!==null&&re(S,t.startTime-e)}}var C=!1,w=-1,T=5,E=-1;function D(){return _?!0:!(e.unstable_now()-E<T)}function ee(){if(_=!1,C){var t=e.unstable_now();E=t;var a=!0;try{a:{h=!1,g&&(g=!1,y(w),w=-1),m=!0;var o=p;try{b:{for(x(t),f=n(l);f!==null&&!(f.expirationTime>t&&D());){var s=f.callback;if(typeof s==`function`){f.callback=null,p=f.priorityLevel;var c=s(f.expirationTime<=t);if(t=e.unstable_now(),typeof c==`function`){f.callback=c,x(t),a=!0;break b}f===n(l)&&r(l),x(t)}else r(l);f=n(l)}if(f!==null)a=!0;else{var d=n(u);d!==null&&re(S,d.startTime-t),a=!1}}break a}finally{f=null,p=o,m=!1}a=void 0}}finally{a?te():C=!1}}}var te;if(typeof b==`function`)te=function(){b(ee)};else if(typeof MessageChannel<`u`){var O=new MessageChannel,ne=O.port2;O.port1.onmessage=ee,te=function(){ne.postMessage(null)}}else te=function(){v(ee,0)};function re(t,n){w=v(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):T=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(e){switch(p){case 1:case 2:case 3:var t=3;break;default:t=p}var n=p;p=t;try{return e()}finally{p=n}},e.unstable_requestPaint=function(){_=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=p;p=e;try{return t()}finally{p=n}},e.unstable_scheduleCallback=function(r,a,o){var s=e.unstable_now();switch(typeof o==`object`&&o?(o=o.delay,o=typeof o==`number`&&0<o?s+o:s):o=s,r){case 1:var c=-1;break;case 2:c=250;break;case 5:c=1073741823;break;case 4:c=1e4;break;default:c=5e3}return c=o+c,r={id:d++,callback:a,priorityLevel:r,startTime:o,expirationTime:c,sortIndex:-1},o>s?(r.sortIndex=o,t(u,r),n(l)===null&&r===n(u)&&(g?(y(w),w=-1):g=!0,re(S,o-s))):(r.sortIndex=c,t(l,r),h||m||(h=!0,C||(C=!0,te()))),r},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(e){var t=p;return function(){var n=p;p=t;try{return e.apply(this,arguments)}finally{p=n}}}})),f=s(((e,t)=>{t.exports=d()})),p=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),a=Symbol.for(`react.strict_mode`),o=Symbol.for(`react.profiler`),s=Symbol.for(`react.consumer`),c=Symbol.for(`react.context`),l=Symbol.for(`react.forward_ref`),u=Symbol.for(`react.suspense`),d=Symbol.for(`react.memo`),f=Symbol.for(`react.lazy`),p=Symbol.for(`react.activity`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=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,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function x(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var S=x.prototype=new b;S.constructor=x,_(S,y.prototype),S.isPureReactComponent=!0;var C=Array.isArray;function w(){}var T={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function D(e,n,r){var a=r.ref;return{$$typeof:t,type:e,key:n,ref:a===void 0?null:a,props:r}}function ee(e,t){return D(e.type,t,e.props)}function te(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function O(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ne=/\/+/g;function re(e,t){return typeof e==`object`&&e&&e.key!=null?O(``+e.key):t.toString(36)}function ie(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(w,w):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function ae(e,r,a,o,s){var c=typeof e;(c===`undefined`||c===`boolean`)&&(e=null);var l=!1;if(e===null)l=!0;else switch(c){case`bigint`:case`string`:case`number`:l=!0;break;case`object`:switch(e.$$typeof){case t:case n:l=!0;break;case f:return l=e._init,ae(l(e._payload),r,a,o,s)}}if(l)return s=s(e),l=o===``?`.`+re(e,0):o,C(s)?(a=``,l!=null&&(a=l.replace(ne,`$&/`)+`/`),ae(s,r,a,``,function(e){return e})):s!=null&&(te(s)&&(s=ee(s,a+(s.key==null||e&&e.key===s.key?``:(``+s.key).replace(ne,`$&/`)+`/`)+l)),r.push(s)),1;l=0;var u=o===``?`.`:o+`:`;if(C(e))for(var d=0;d<e.length;d++)o=e[d],c=u+re(o,d),l+=ae(o,r,a,c,s);else if(d=h(e),typeof d==`function`)for(e=d.call(e),d=0;!(o=e.next()).done;)o=o.value,c=u+re(o,d++),l+=ae(o,r,a,c,s);else if(c===`object`){if(typeof e.then==`function`)return ae(ie(e),r,a,o,s);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return l}function oe(e,t,n){if(e==null)return e;var r=[],a=0;return ae(e,r,``,``,function(e){return t.call(n,e,a++)}),r}function se(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var k=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},A={map:oe,forEach:function(e,t,n){oe(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return oe(e,function(){t++}),t},toArray:function(e){return oe(e,function(e){return e})||[]},only:function(e){if(!te(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=p,e.Children=A,e.Component=y,e.Fragment=r,e.Profiler=o,e.PureComponent=x,e.StrictMode=a,e.Suspense=u,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return T.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=_({},e.props),a=e.key;if(t!=null)for(o in t.key!==void 0&&(a=``+t.key),t)!E.call(t,o)||o===`key`||o===`__self`||o===`__source`||o===`ref`&&t.ref===void 0||(r[o]=t[o]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];r.children=s}return D(e.type,a,r)},e.createContext=function(e){return e={$$typeof:c,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:s,_context:e},e},e.createElement=function(e,t,n){var r,a={},o=null;if(t!=null)for(r in t.key!==void 0&&(o=``+t.key),t)E.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(a[r]=t[r]);var s=arguments.length-2;if(s===1)a.children=n;else if(1<s){for(var c=Array(s),l=0;l<s;l++)c[l]=arguments[l+2];a.children=c}if(e&&e.defaultProps)for(r in s=e.defaultProps,s)a[r]===void 0&&(a[r]=s[r]);return D(e,o,a)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:l,render:e}},e.isValidElement=te,e.lazy=function(e){return{$$typeof:f,_payload:{_status:-1,_result:e},_init:se}},e.memo=function(e,t){return{$$typeof:d,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=T.T,n={};T.T=n;try{var r=e(),a=T.S;a!==null&&a(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(w,k)}catch(e){k(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}},e.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},e.use=function(e){return T.H.use(e)},e.useActionState=function(e,t,n){return T.H.useActionState(e,t,n)},e.useCallback=function(e,t){return T.H.useCallback(e,t)},e.useContext=function(e){return T.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return T.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return T.H.useEffect(e,t)},e.useEffectEvent=function(e){return T.H.useEffectEvent(e)},e.useId=function(){return T.H.useId()},e.useImperativeHandle=function(e,t,n){return T.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return T.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return T.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return T.H.useMemo(e,t)},e.useOptimistic=function(e,t){return T.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return T.H.useReducer(e,t,n)},e.useRef=function(e){return T.H.useRef(e)},e.useState=function(e){return T.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return T.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return T.H.useTransition()},e.version=`19.2.7`})),m=s(((e,t)=>{t.exports=p()})),h=s((e=>{var t=m();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var a={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},o=Symbol.for(`react.portal`);function s(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var c=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return s(e,t,null,r)},e.flushSync=function(e){var t=c.T,n=a.p;try{if(c.T=null,a.p=2,e)return e()}finally{c.T=t,a.p=n,a.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,a.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&a.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=l(n,t.crossOrigin),o=typeof t.integrity==`string`?t.integrity:void 0,s=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?a.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:o,fetchPriority:s}):n===`script`&&a.d.X(e,{crossOrigin:r,integrity:o,fetchPriority:s,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`)if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=l(t.as,t.crossOrigin);a.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??a.d.M(e)},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=l(n,t.crossOrigin);a.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`)if(t){var n=l(t.as,t.crossOrigin);a.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else a.d.m(e)},e.requestFormReset=function(e){a.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return c.H.useFormState(e,t,n)},e.useFormStatus=function(){return c.H.useHostTransitionStatus()},e.version=`19.2.7`})),g=s(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=s((e=>{var t=f(),n=m(),r=g();function a(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function o(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function s(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function c(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function u(e){if(s(e)!==e)throw Error(a(188))}function d(e){var t=e.alternate;if(!t){if(t=s(e),t===null)throw Error(a(188));return t===e?e:null}for(var n=e,r=t;;){var o=n.return;if(o===null)break;var c=o.alternate;if(c===null){if(r=o.return,r!==null){n=r;continue}break}if(o.child===c.child){for(c=o.child;c;){if(c===n)return u(o),e;if(c===r)return u(o),t;c=c.sibling}throw Error(a(188))}if(n.return!==r.return)n=o,r=c;else{for(var l=!1,d=o.child;d;){if(d===n){l=!0,n=o,r=c;break}if(d===r){l=!0,r=o,n=c;break}d=d.sibling}if(!l){for(d=c.child;d;){if(d===n){l=!0,n=c,r=o;break}if(d===r){l=!0,r=c,n=o;break}d=d.sibling}if(!l)throw Error(a(189))}}if(n.alternate!==r)throw Error(a(190))}if(n.tag!==3)throw Error(a(188));return n.stateNode.current===n?e:t}function p(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=p(e),t!==null)return t;e=e.sibling}return null}var h=Object.assign,_=Symbol.for(`react.element`),v=Symbol.for(`react.transitional.element`),y=Symbol.for(`react.portal`),b=Symbol.for(`react.fragment`),x=Symbol.for(`react.strict_mode`),S=Symbol.for(`react.profiler`),C=Symbol.for(`react.consumer`),w=Symbol.for(`react.context`),T=Symbol.for(`react.forward_ref`),E=Symbol.for(`react.suspense`),D=Symbol.for(`react.suspense_list`),ee=Symbol.for(`react.memo`),te=Symbol.for(`react.lazy`),O=Symbol.for(`react.activity`),ne=Symbol.for(`react.memo_cache_sentinel`),re=Symbol.iterator;function ie(e){return typeof e!=`object`||!e?null:(e=re&&e[re]||e[`@@iterator`],typeof e==`function`?e:null)}var ae=Symbol.for(`react.client.reference`);function oe(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===ae?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case b:return`Fragment`;case S:return`Profiler`;case x:return`StrictMode`;case E:return`Suspense`;case D:return`SuspenseList`;case O:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case y:return`Portal`;case w:return e.displayName||`Context`;case C:return(e._context.displayName||`Context`)+`.Consumer`;case T:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case ee:return t=e.displayName||null,t===null?oe(e.type)||`Memo`:t;case te:t=e._payload,e=e._init;try{return oe(e(t))}catch{}}return null}var se=Array.isArray,k=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},le=[],ue=-1;function de(e){return{current:e}}function j(e){0>ue||(e.current=le[ue],le[ue]=null,ue--)}function M(e,t){ue++,le[ue]=e.current,e.current=t}var fe=de(null),pe=de(null),me=de(null),he=de(null);function ge(e,t){switch(M(me,t),M(pe,e),M(fe,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Jd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Jd(t),e=Yd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}j(fe),M(fe,e)}function _e(){j(fe),j(pe),j(me)}function N(e){e.memoizedState!==null&&M(he,e);var t=fe.current,n=Yd(t,e.type);t!==n&&(M(pe,e),M(fe,n))}function ve(e){pe.current===e&&(j(fe),j(pe)),he.current===e&&(j(he),ap._currentValue=ce)}var ye,be;function xe(e){if(ye===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ye=t&&t[1]||``,be=-1<e.stack.indexOf(`
|
|
3
3
|
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
|
4
4
|
`+ye+e+be}var Se=!1;function Ce(e,t){if(!e||Se)return``;Se=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var a=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);a&&a.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var o=r.DetermineComponentFrameRoot(),s=o[0],c=o[1];if(s&&c){var l=s.split(`
|
|
@@ -107,10 +107,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
107
107
|
@media (prefers-reduced-motion: reduce) {
|
|
108
108
|
.acv-streak, .acv-fan, .acv-sway-wrap, .acv-glow, .acv-swing { animation: none !important; }
|
|
109
109
|
}
|
|
110
|
-
`;function MH({trpc:e,deviceId:t,layout:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s;if(n===`compact`)return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`span`,{className:Z(`text-xs tabular-nums font-medium`,bH[c.mode]),children:c.target===null?c.currentTemp===null?null:(0,C.jsxs)(`span`,{className:`text-foreground-subtle`,children:[c.currentTemp,`°`]}):(0,C.jsxs)(C.Fragment,{children:[c.target,`°`,c.currentTemp!==null&&(0,C.jsxs)(`span`,{className:`text-foreground-subtle font-normal`,children:[` `,`(`,c.currentTemp,`°)`]})]})}),c.target!==null&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Decrease target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target-1;l({target:e}),a.setTarget({target:e})}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`−`}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Increase target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target+1;l({target:e}),a.setTarget({target:e})}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`+`})]}),(0,C.jsx)(`select`,{"aria-label":`Mode`,value:c.mode,disabled:u,onChange:e=>{e.stopPropagation();let t=c.availableModes.find(t=>t===e.target.value);!u&&t&&(l({mode:t}),a.setMode({mode:t}))},className:Z(`bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer`,u&&`opacity-40 cursor-not-allowed`),children:c.availableModes.map(e=>(0,C.jsx)(`option`,{value:e,children:CH[e]},e))})]});let d=TH[c.mode],f=c.mode!==`off`,p=kH(c.preset),m=c.preset===`turbo`,h=Math.max(.55,AH(c.fanMode)*(m?.6:1)),g=c.swingVertical!==null,_=c.swingHorizontal!==null,v=f&&(c.swingVertical===!0||c.swingHorizontal===!0);return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:Z(`relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors`,yH[c.mode]),children:[(0,C.jsx)(`style`,{children:jH}),(0,C.jsxs)(`div`,{className:`relative z-10 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-lg border border-border/50 bg-surface/30 px-3 py-3`,children:[(0,C.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-60`,children:(0,C.jsx)(RH,{mode:c.mode,accent:d,periodSec:h,swaying:v})}),(0,C.jsx)(`div`,{className:`pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50`}),f&&(0,C.jsx)(`span`,{"aria-hidden":!0,className:`acv-glow pointer-events-none absolute left-1/2 top-1/2 h-16 w-16 -translate-x-1/2 -translate-y-1/2 rounded-full blur-2xl`,style:{background:d,animation:`acv-glow 3.2s ease-in-out infinite`}}),(0,C.jsxs)(`div`,{className:`relative z-10 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide`,style:{color:d},children:[(0,C.jsx)(PH,{mode:c.mode,className:`h-3.5 w-3.5`}),CH[c.mode],c.currentTemp!==null&&(0,C.jsxs)(`span`,{className:`normal-case text-foreground-subtle`,children:[`· `,c.currentTemp,`° now`]}),c.currentHumidity!==null&&(0,C.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 normal-case text-foreground-subtle`,children:[(0,C.jsx)(AL,{className:`h-3 w-3`}),c.currentHumidity,`%`]})]}),c.target===null?(0,C.jsxs)(`div`,{className:`relative z-10 flex items-baseline gap-0.5`,children:[(0,C.jsx)(`span`,{className:`text-4xl font-bold leading-none tabular-nums text-foreground`,children:c.currentTemp??`—`}),(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle`,children:`°`})]}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{className:`relative z-10 flex items-center gap-3`,children:[(0,C.jsx)(IH,{label:`Decrease target`,symbol:`−`,disabled:u,onClick:()=>{if(u||c.target===null)return;let e=c.target-1;l({target:e}),a.setTarget({target:e})}}),(0,C.jsxs)(`div`,{className:`flex items-baseline gap-0.5`,children:[(0,C.jsx)(`span`,{className:`text-4xl font-bold leading-none tabular-nums`,style:{color:d},children:c.target}),(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle`,children:`°`})]}),(0,C.jsx)(IH,{label:`Increase target`,symbol:`+`,disabled:u,onClick:()=>{if(u||c.target===null)return;let e=c.target+1;l({target:e}),a.setTarget({target:e})}})]}),(0,C.jsx)(`div`,{className:`relative z-10 w-36`,children:(0,C.jsx)(LH,{value:c.target,min:EH,max:DH,accent:d})})]})]}),(0,C.jsxs)(`div`,{className:`relative z-10 grid grid-cols-3 gap-2`,children:[(0,C.jsx)(FH,{label:`Mode`,icon:(0,C.jsx)(`span`,{style:{color:d},className:`flex`,children:(0,C.jsx)(PH,{mode:c.mode,className:`h-4 w-4`})}),value:c.mode,options:c.availableModes.map(e=>({value:e,label:CH[e]})),disabled:u,onChange:e=>{let t=c.availableModes.find(t=>t===e);t&&(l({mode:t}),a.setMode({mode:t}))}}),c.availableFanModes.length>0&&(0,C.jsx)(FH,{label:`Fan`,icon:(0,C.jsx)(KR,{className:`h-4 w-4 text-sky-500`}),value:c.fanMode,options:c.availableFanModes.map(e=>({value:e,label:OH(e)})),disabled:u,onChange:e=>{l({fanMode:e}),a.setFanMode({fanMode:e})}}),c.availablePresets.length>0&&(0,C.jsx)(FH,{label:`Preset`,icon:(0,C.jsx)(p,{className:`h-4 w-4 text-emerald-500`}),value:c.preset,options:c.availablePresets.map(e=>({value:e,label:OH(e)})),disabled:u,onChange:e=>{l({preset:e}),a.setPreset({preset:e})}})]}),(g||_)&&(0,C.jsx)(NH,{label:`Swing`,children:(0,C.jsxs)(`div`,{className:`grid grid-cols-2 gap-1`,children:[g&&(0,C.jsx)(BH,{axis:`vertical`,on:c.swingVertical??!1,busy:u,onToggle:e=>{l({swingVertical:e}),a.setSwingVertical({on:e})}}),_&&(0,C.jsx)(BH,{axis:`horizontal`,on:c.swingHorizontal??!1,busy:u,onToggle:e=>{l({swingHorizontal:e}),a.setSwingHorizontal({on:e})}})]})})]})}function NH({label:e,children:t}){return(0,C.jsxs)(`div`,{className:`relative z-10 flex flex-col gap-1`,children:[(0,C.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e}),t]})}function PH({mode:e,className:t}){let n=wH[e];return(0,C.jsx)(n,{className:t,"aria-hidden":!0})}function FH({label:e,icon:t,value:n,options:r,disabled:a,onChange:o}){return(0,C.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,C.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e}),(0,C.jsxs)(`div`,{className:Z(`flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5`,a&&`opacity-40`),children:[(0,C.jsx)(`span`,{className:`flex shrink-0`,children:t}),(0,C.jsx)(`select`,{"aria-label":e,value:n,disabled:a,onChange:e=>{e.stopPropagation(),a||o(e.target.value)},className:`min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none`,children:r.map(e=>(0,C.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,C.jsx)(pL,{className:`h-3 w-3 shrink-0 text-foreground-subtle`})]})]})}function IH({label:e,symbol:t,disabled:n,onClick:r}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,disabled:n,onClick:r,className:Z(`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-surface text-lg leading-none text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground active:scale-95`,n&&`opacity-40 cursor-not-allowed`),children:t})}function LH({value:e,min:t,max:n,accent:r}){let a=`${Math.min(1,Math.max(0,(e-t)/(n-t)))*100}%`;return(0,C.jsxs)(`div`,{className:`mt-2 w-full`,children:[(0,C.jsxs)(`div`,{className:`relative h-1.5 w-full rounded-full bg-surface-subtle`,children:[(0,C.jsx)(`div`,{className:`absolute inset-y-0 left-0 rounded-full`,style:{width:a,background:r}}),(0,C.jsx)(`div`,{className:`absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface shadow`,style:{left:a,background:r}})]}),(0,C.jsxs)(`div`,{className:`mt-0.5 flex justify-between text-[9px] tabular-nums text-foreground-subtle`,children:[(0,C.jsxs)(`span`,{children:[t,`°`]}),(0,C.jsxs)(`span`,{children:[n,`°`]})]})]})}function RH({mode:e,accent:t,periodSec:n,swaying:r}){let a=[0,1,2,3,4,5],o=e===`heat`,s=e===`dry`;return(0,C.jsx)(`div`,{"aria-hidden":!0,className:`absolute inset-0 overflow-hidden`,children:e===`off`?(0,C.jsx)(`div`,{className:`flex h-full items-center justify-center gap-2 opacity-30`,children:a.map(e=>(0,C.jsx)(`span`,{className:`h-8 w-1 rounded-full bg-foreground-subtle opacity-40`},e))}):e===`fan_only`?(0,C.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,C.jsx)(zH,{color:t,periodSec:Math.max(.5,n*.7),size:56})}):(0,C.jsx)(`div`,{className:Z(`acv-sway-wrap absolute inset-0`,r&&`acv-sway`),style:r?{animation:`acv-sway 2.6s ease-in-out infinite`}:void 0,children:a.map(e=>(0,C.jsx)(`span`,{className:`acv-streak absolute rounded-full`,style:{left:`${8+e*15}%`,width:s?`0.4rem`:`0.3rem`,height:s?`0.4rem`:`1.9rem`,background:t,boxShadow:`0 0 6px ${t}`,animationName:o?`acv-rise`:`acv-fall`,animationTimingFunction:`linear`,animationIterationCount:`infinite`,animationDuration:`${n}s`,animationDelay:`${e%3*(n/3)+e*.05}s`}},e))})})}function zH({color:e,periodSec:t,size:n}){return(0,C.jsxs)(`svg`,{width:n,height:n,viewBox:`0 0 100 100`,className:`acv-fan`,style:{animation:`acv-spin ${t}s linear infinite`,transformOrigin:`50% 50%`},"aria-hidden":!0,children:[[0,120,240].map(t=>(0,C.jsx)(`path`,{d:`M50 50 C 58 30, 78 26, 84 12 C 66 20, 54 34, 50 50 Z`,fill:e,opacity:.85,transform:`rotate(${t} 50 50)`},t)),(0,C.jsx)(`circle`,{cx:`50`,cy:`50`,r:`7`,fill:e})]})}function BH({axis:e,on:t,busy:n,onToggle:r}){let a=e===`vertical`?`Vertical`:`Horizontal`,o=e===`vertical`?iR:rR,s=e===`vertical`?`acv-swing-v`:`acv-swing-h`;return(0,C.jsxs)(`button`,{type:`button`,"aria-label":`${a} swing`,"aria-pressed":t,disabled:n,onClick:()=>{n||r(!t)},className:Z(`flex items-center justify-center gap-2 rounded-lg border px-2 py-1.5 text-xs font-medium transition-colors`,t?`border-transparent bg-indigo-400 text-indigo-950 shadow-sm`:`border-border/60 bg-surface-subtle text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,n&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(o,{className:`acv-swing h-4 w-4`,"aria-hidden":!0,style:t?{animation:`${s} 1.4s ease-in-out infinite`}:void 0}),a]})}var VH={playing:`border-green-400 bg-green-50 dark:bg-green-950`,paused:`border-amber-400 bg-amber-50 dark:bg-amber-950`,buffering:`border-blue-400 bg-blue-50 dark:bg-blue-950`,on:`border-slate-400 bg-slate-50 dark:bg-slate-950`,idle:`border-slate-400 bg-slate-50 dark:bg-slate-950`,off:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`,standby:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`},HH={playing:`bg-green-500`,paused:`bg-amber-400`,buffering:`bg-blue-400`,on:`bg-slate-400`,idle:`bg-slate-400`,off:`bg-zinc-300`,standby:`bg-zinc-300`},UH=[`off`,`all`,`one`];function WH(e){return UH.includes(e)}var GH={off:`Off`,all:`All`,one:`One`};function KH(e){return e===`playing`||e===`buffering`?`pause`:`play`}function qH({trpc:e,deviceId:t,features:n,layout:r,optimistic:a}){let{cap:o,slice:s,available:c}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:l,applyOptimistic:u}=Yz(s,{enabled:a??!0});if(l===void 0)return null;let d=!c,f=KH(l.state);return(0,C.jsxs)(`div`,{"data-state":l.state,className:Z(`inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors`,VH[l.state],r===`full`&&`flex-col items-stretch gap-3`),children:[(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(`span`,{role:`status`,"aria-label":l.state,className:Z(`inline-block h-2 w-2 rounded-full flex-shrink-0`,HH[l.state])}),(0,C.jsx)(`button`,{type:`button`,"aria-label":f===`play`?`Play`:`Pause`,disabled:d,onClick:e=>{e.stopPropagation(),!d&&(f===`play`?(u({state:`playing`}),o?.play({})):(u({state:`paused`}),o?.pause({})))},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:f===`play`?`▶`:`⏸`})]}),r===`full`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Previous`,disabled:d,onClick:e=>{e.stopPropagation(),d||o?.previous({})},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:`⏮`}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Next`,disabled:d,onClick:e=>{e.stopPropagation(),d||o?.next({})},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:`⏭`})]}),l.volumeLevel!==null&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Vol`}),(0,C.jsx)(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,value:l.volumeLevel,disabled:d,onChange:e=>{let t=Number(e.target.value);u({volumeLevel:t}),d||o?.setVolume({volumeLevel:t})}}),(0,C.jsxs)(`span`,{className:`tabular-nums w-8 text-right`,children:[l.volumeLevel,`%`]})]}),l.isMuted!==null&&(0,C.jsx)(`button`,{type:`button`,"aria-label":l.isMuted?`Unmute`:`Mute`,disabled:d,onClick:e=>{if(e.stopPropagation(),!d&&l.isMuted!==null){let e=!l.isMuted;u({isMuted:e}),o?.setMute({muted:e})}},className:Z(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,l.isMuted?`bg-amber-400 text-amber-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,d&&`opacity-40 cursor-not-allowed`),children:l.isMuted?`🔇`:`🔊`}),l.availableSources.length>0&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Source`}),(0,C.jsxs)(`select`,{"aria-label":`Source`,value:l.source,disabled:d,onChange:e=>{let t=e.target.value;!d&&t&&(u({source:t}),o?.selectSource({source:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:[(0,C.jsx)(`option`,{value:``,disabled:!0,children:`—`}),l.availableSources.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))]})]}),l.shuffle!==null&&(0,C.jsx)(`button`,{type:`button`,"aria-label":`Shuffle`,disabled:d,onClick:e=>{if(e.stopPropagation(),!d&&l.shuffle!==null){let e=!l.shuffle;u({shuffle:e}),o?.setShuffle({shuffle:e})}},className:Z(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,l.shuffle?`bg-green-400 text-green-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,d&&`opacity-40 cursor-not-allowed`),children:`⇌ Shuffle`}),l.repeat!==null&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Repeat`}),(0,C.jsx)(`select`,{"aria-label":`Repeat`,value:l.repeat,disabled:d,onChange:e=>{let t=e.target.value;!d&&WH(t)&&(u({repeat:t}),o?.setRepeat({repeat:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:UH.map(e=>(0,C.jsx)(`option`,{value:e,children:GH[e]},e))})]})]})]})}function JH(e){return e.slice(0,10)}function YH(e){return e.slice(0,5)}function XH(e){return(e.includes(`T`)?e:e.replace(` `,`T`)).slice(0,16)}function ZH({value:e,busy:t,onCommit:n,unit:r,min:a,max:o,step:s,precision:c}){let[l,u]=(0,S.useState)(GM(e,c)),d=Number(l),f=l!==``&&!Number.isNaN(d),p=s??1,m=e=>{let t=e;return a!==void 0&&(t=Math.max(a,t)),o!==void 0&&(t=Math.min(o,t)),t},h=()=>{!t&&f&&n(m(d))};return(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Decrement`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=m(e-p);u(GM(t,c)),n(t)}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`−`}),(0,C.jsx)(`input`,{"aria-label":`Numeric value`,type:`number`,disabled:t,value:l,onChange:e=>{u(e.target.value);let r=Number(e.target.value);e.target.value!==``&&!Number.isNaN(r)&&(t||n(m(r)))},onBlur:h,onKeyDown:e=>{e.key===`Enter`&&h()},className:Z(`w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center`,t&&`opacity-40 cursor-not-allowed`)}),r!==void 0&&(0,C.jsx)(`span`,{className:`text-foreground-subtle text-xs`,children:r}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Increment`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=m(e+p);u(GM(t,c)),n(t)}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`+`})]})}function QH({value:e,busy:t,onCommit:n}){let[r,a]=(0,S.useState)(e);return(0,C.jsx)(`input`,{type:`text`,disabled:t,value:r,onChange:e=>a(e.target.value),onBlur:()=>{t||n(r)},onKeyDown:e=>{e.key===`Enter`&&!t&&n(r)},className:Z(`rounded border border-border bg-surface px-2 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}function $H({slice:e,busy:t,setValueFn:n,layout:r}){switch(e.kind){case`numeric`:return(0,C.jsx)(ZH,{value:typeof e.value==`number`?e.value:Number(e.value),busy:t,onCommit:e=>{n({control:{kind:`numeric`,value:e}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case`select`:return(0,C.jsx)(`select`,{"aria-label":`Control value`,disabled:t,value:String(e.value),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`select`,value:e.target.value}})},className:Z(`w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`),children:e.options.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))});case`text`:return(0,C.jsx)(QH,{value:String(e.value),busy:t,onCommit:e=>{n({control:{kind:`text`,value:e}})}});case`datetime`:{let a=String(e.value),o=e.format??`datetime`;return r===`compact`?a===``?(0,C.jsx)(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground-subtle`,children:`—`}):(0,C.jsx)(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground`,children:WM(a,o)}):(0,C.jsx)(`input`,{type:o===`date`?`date`:o===`time`?`time`:`datetime-local`,"aria-label":`Control value`,disabled:t,value:o===`date`?JH(a):o===`time`?YH(a):XH(a),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`datetime`,value:e.target.value}})},className:Z(`rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}default:return null}}function eU({trpc:e,deviceId:t,features:n,layout:r,optimistic:a}){let{cap:o,slice:s,available:c}=Iz({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control}),{display:l,applyOptimistic:u}=Yz(s,{enabled:a??!0});if(l===void 0)return null;let d=!c;return(0,C.jsx)(`div`,{"data-kind":l.kind,className:`inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors`,children:(0,C.jsx)($H,{slice:l,busy:d,setValueFn:e=>{!d&&o&&(u({value:e.control.value}),o.setValue(e))},layout:r})})}var tU=5,nU=35;function rU(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function iU(e,t,n){return Math.round(t+e*(n-t))}var aU=176,oU=76,sU=2*Math.PI*oU,cU=270/360*sU,lU=aU/2-oU-10;function uU(e){let t=aU/2,n=aU/2,r=sU-cU,a=e.mode===`band`?(()=>{let t=e.band.from*cU,n=Math.max(0,(e.band.to-e.band.from)*cU);return{dasharray:`${n} ${sU-n}`,dashoffset:-t}})():(()=>{let t=e.fraction*cU;return{dasharray:`${t} ${sU-t}`,dashoffset:void 0}})();return(0,C.jsxs)(`svg`,{width:aU,height:aU,viewBox:`0 0 ${aU} ${aU}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[(0,C.jsx)(`circle`,{cx:t,cy:n,r:oU,fill:`none`,stroke:`var(--color-border)`,strokeWidth:12,strokeDasharray:`${cU} ${r}`,strokeLinecap:`round`}),(0,C.jsx)(`circle`,{cx:t,cy:n,r:oU,fill:`none`,stroke:e.color,strokeWidth:12,strokeDasharray:a.dasharray,...a.dashoffset===void 0?{}:{strokeDashoffset:a.dashoffset},strokeLinecap:`round`})]})}var dU={heat:`#f59e0b`,cool:`#60a5fa`,auto:`#c084fc`,heat_cool:`#e879f9`,fan_only:`#94a3b8`,dry:`#22d3ee`,off:`#d4d4d8`};function fU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s,d=dU[c.mode],f=c.mode===`heat_cool`||c.targetLow!==null&&c.targetHigh!==null,p=tU,m=nU,h=!f&&c.target!==null?rU(c.target,p,m):0,g=f&&c.targetLow!==null?rU(c.targetLow,p,m):0,_=f&&c.targetHigh!==null?rU(c.targetHigh,p,m):0;return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:Z(`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors`,yH[c.mode]),children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,C.jsxs)(`div`,{className:`relative`,style:{width:aU,height:aU},children:[f?(0,C.jsx)(uU,{mode:`band`,band:{from:g,to:_},color:d}):(0,C.jsx)(uU,{mode:`fill`,fraction:h,color:d}),f?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:g,color:d,knobTopPx:lU,onDragFraction:e=>{if(u||c.targetHigh===null)return;let t=Math.min(iU(e,p,m),c.targetHigh);l({targetLow:t}),a.setTargetRange({targetLow:t,targetHigh:c.targetHigh})}})}),(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:_,color:d,knobTopPx:lU,onDragFraction:e=>{if(u||c.targetLow===null)return;let t=Math.max(iU(e,p,m),c.targetLow);l({targetHigh:t}),a.setTargetRange({targetLow:c.targetLow,targetHigh:t})}})})]}):(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:h,color:d,knobTopPx:lU,onDragFraction:e=>{if(u)return;let t=iU(e,p,m);l({target:t}),a.setTarget({target:t})}})}),(0,C.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:[(0,C.jsxs)(`div`,{"data-testid":`current-temp`,className:`text-4xl font-bold tabular-nums text-foreground leading-none`,children:[c.currentTemp===null?`—`:c.currentTemp,(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle font-normal ml-0.5`,children:`°`})]}),!f&&c.target!==null&&(0,C.jsxs)(`div`,{className:`text-xs font-semibold`,style:{color:d},children:[`set `,c.target,`°`]}),f&&c.targetLow!==null&&c.targetHigh!==null&&(0,C.jsxs)(`div`,{className:`text-xs font-semibold`,style:{color:d},children:[c.targetLow,`° – `,c.targetHigh,`°`]})]})]}),!f&&c.target!==null&&(0,C.jsx)(`div`,{className:`w-[200px]`,children:(0,C.jsx)(Lz,{value:`${c.target}°`,onDelta:e=>{if(u||c.target===null)return;let t=c.target+e;l({target:t}),a.setTarget({target:t})}})})]}),(0,C.jsx)(`select`,{"aria-label":`Mode`,value:c.mode,disabled:u,onChange:e=>{e.stopPropagation();let t=e.target.value;!u&&t&&(l({mode:c.availableModes.find(e=>e===t)??c.mode}),a.setMode({mode:c.availableModes.find(e=>e===t)??c.mode}))},className:Z(`w-full rounded border border-border bg-surface px-3 py-1.5 text-sm`,u&&`opacity-40 cursor-not-allowed`),children:c.availableModes.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))})]})}function pU(e){return e===`locked`||e===`locking`}function mU(e){return e===`jammed`}var hU={locked:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},locking:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},unlocked:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},unlocking:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},jammed:{colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`locked`}};function gU({state:e}){let t=hU[e];return(0,C.jsx)(`div`,{"data-testid":`lock-glyph`,"data-state":e,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2`,t.colorClass),children:t.icon===`locked`?(0,C.jsx)(YL,{className:`h-8 w-8`,"aria-hidden":`true`}):(0,C.jsx)(JL,{className:`h-8 w-8`,"aria-hidden":`true`})})}function _U({state:e}){return(0,C.jsx)(`span`,{className:Z(`text-sm font-medium capitalize`,mU(e)?`text-danger`:`text-foreground-muted`),children:e})}function vU({busy:e,onOpen:t}){return(0,C.jsxs)(`button`,{type:`button`,"aria-label":`Open (unlatch)`,title:`Open (unlatch)`,disabled:e,onClick:e=>{e.stopPropagation(),t()},className:Z(`inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium`,`text-foreground-muted hover:bg-surface-hover transition-colors`,e&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(DL,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Open`]})}function yU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=pU(c.state),d=mU(c.state)||!s,f=n?.includes(js.LockOpen)===!0,p=()=>{d||(u?(l({state:`unlocking`}),a.unlock({})):(l({state:`locking`}),a.lock({})))},m=()=>{d||a.open({})},h=u?`Unlock`:`Lock`;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,C.jsx)(gU,{state:c.state}),(0,C.jsx)(_U,{state:c.state})]}),(0,C.jsx)(`div`,{className:Z(d&&`pointer-events-none opacity-40`),children:(0,C.jsx)(Rz,{on:u,targetLabel:h,onConfirm:p})}),f&&(0,C.jsx)(`div`,{className:`flex justify-center`,children:(0,C.jsx)(vU,{busy:d,onOpen:m})})]})}var bU=150,xU=64,SU=bU/2,CU=2*Math.PI*xU,wU=270/360*CU;function TU({fraction:e,color:t,children:n,onDragFraction:r}){let a=Math.min(1,Math.max(0,e)),o=bU/2,s=bU/2,c=CU-wU,l=a*wU;return(0,C.jsxs)(`div`,{className:`relative`,style:{width:bU,height:bU},children:[(0,C.jsxs)(`svg`,{width:bU,height:bU,viewBox:`0 0 ${bU} ${bU}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[(0,C.jsx)(`circle`,{cx:o,cy:s,r:xU,fill:`none`,stroke:`var(--color-border)`,strokeWidth:11,strokeDasharray:`${wU} ${c}`,strokeLinecap:`round`}),(0,C.jsx)(`circle`,{cx:o,cy:s,r:xU,fill:`none`,stroke:t,strokeWidth:11,strokeDasharray:`${l} ${CU-l}`,strokeLinecap:`round`})]}),(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:a,color:t,knobTopPx:SU-xU-10,...r===void 0?{}:{onDragFraction:r}})}),(0,C.jsx)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:n})]})}function EU({on:e,busy:t,onToggle:n}){let r={transform:e?`translateX(30px)`:`translateX(3px)`};return(0,C.jsx)(`button`,{type:`button`,"aria-pressed":e,title:e?`Turn off`:`Turn on`,disabled:t,onClick:e=>{e.stopPropagation(),n()},className:Z(`relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0`,e?`bg-success/30 border-success/50`:`bg-surface-hover border-border`,t&&`opacity-60 cursor-not-allowed`),children:(0,C.jsx)(`span`,{className:Z(`absolute h-6 w-6 rounded-full transition-all`,e?`bg-success`:`bg-foreground-subtle`),style:r})})}var DU=500,OU=150,kU=`linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)`;function AU(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function jU(e){return AU(e,OU,DU)}var MU=`#f4b740`,NU=`#d4d4d8`;function PU({trpc:e,deviceId:t,features:n,optimistic:r}){let a=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),o=Iz({trpc:e,deviceId:t,cap:e=>e.brightness,slice:e=>e.state.brightness}),s=Iz({trpc:e,deviceId:t,cap:e=>e.color,slice:e=>e.state.color}),c=Yz(a.slice,{enabled:r??!0}),l=Yz(o.slice,{enabled:r??!0}),u=Yz(s.slice,{enabled:r??!0});if(a.cap===void 0||c.display===void 0)return null;let d=c.display.on===!0,f=!a.available,p=l.display?.percentage??0,m=!o.available,h=d?p/100:0,g=d?MU:NU,_=(n?.includes(js.LightColorMired)??!1)&&s.cap!==void 0,v=u.display?.mireds,y=!s.available;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,C.jsxs)(TU,{fraction:h,color:g,children:[(0,C.jsxs)(`div`,{"data-testid":`brightness-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[p,(0,C.jsx)(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),(0,C.jsx)(WL,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}),o.cap!==void 0&&(0,C.jsxs)(`label`,{className:`flex w-full items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{className:`w-16`,children:`Brightness`}),(0,C.jsx)(`input`,{"aria-label":`Brightness`,type:`range`,min:0,max:100,step:1,className:`flex-1`,value:p,disabled:m||!d,onChange:e=>{let t=Number(e.target.value);l.applyOptimistic({percentage:t}),m||o.cap?.setBrightness({percentage:t})}}),(0,C.jsxs)(`span`,{className:`tabular-nums w-9 text-right`,children:[p,`%`]})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:d?`On`:`Off`}),(0,C.jsx)(EU,{on:d,busy:f,onToggle:()=>{if(f)return;let e=!d;c.applyOptimistic({on:e}),a.cap?.setState({on:e})}})]}),_&&(0,C.jsxs)(`div`,{className:`flex items-center gap-2`,"data-testid":`color-temp-strip`,children:[(0,C.jsx)(NR,{className:`h-4 w-4 text-foreground-subtle`,"aria-hidden":`true`}),(0,C.jsxs)(`label`,{className:`flex-1`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Colour temperature`}),(0,C.jsx)(`input`,{"aria-label":`Colour temperature`,type:`range`,min:OU,max:DU,step:1,className:`w-full`,value:v??DU,disabled:y||!d,onChange:e=>{let t=Number(e.target.value);u.applyOptimistic({mode:`mired`,mireds:t}),y||s.cap?.setColor({color:{mode:`mired`,mireds:t}})}}),(0,C.jsx)(`div`,{className:`pointer-events-none mt-1`,children:(0,C.jsx)(Wz,{fraction:v===void 0?.5:jU(v),color:kU})})]})]})]})}var FU=`#3aa6a0`,IU=`#d4d4d8`;function LU({trpc:e,deviceId:t,features:n,optimistic:r}){let a=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),o=Iz({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl}),s=Yz(a.slice,{enabled:r??!0}),c=Yz(o.slice,{enabled:r??!0});if(a.cap===void 0||s.display===void 0)return null;let l=s.display.on===!0,u=!a.available,d=c.display?.percentage??0,f=!o.available,p=l?d/100:0,m=l?FU:IU,h=n?.includes(js.FanSpeed)??!1,g=(n?.includes(js.FanOscillating)??!1)&&o.cap!==void 0,_=c.display?.availablePresets??[],v=(n?.includes(js.FanPreset)??!1)&&o.cap!==void 0&&_.length>0,y=c.display?.preset??``,b=c.display?.oscillating===!0,x=()=>{if(u)return;let e=!l;s.applyOptimistic({on:e}),a.cap?.setState({on:e})},S=()=>{if(f)return;let e=!b;c.applyOptimistic({oscillating:e}),o.cap?.setOscillating({oscillating:e})},w=e=>{if(f)return;let t=c.display;if(t===void 0)return;let n=t.percentageStep!==void 0&&t.percentageStep>0?t.percentageStep:1,r=Math.min(100,Math.max(0,Math.round(e*100/n)*n));c.applyOptimistic({percentage:r}),o.cap?.setPercentage({percentage:r})},T=e=>{f||e===``||(c.applyOptimistic({preset:e}),o.cap?.setPreset({preset:e}))};return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsx)(`div`,{className:`flex flex-col items-center gap-3`,children:h?(0,C.jsxs)(TU,{fraction:p,color:m,onDragFraction:w,children:[(0,C.jsxs)(`div`,{"data-testid":`speed-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[d,(0,C.jsx)(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),(0,C.jsx)(ML,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}):(0,C.jsx)(`div`,{"data-testid":`fan-onoff-icon`,className:`flex h-[150px] w-[150px] items-center justify-center`,children:(0,C.jsx)(ML,{className:`h-16 w-16`,style:{color:m},"aria-hidden":`true`})})}),v&&(0,C.jsx)(`div`,{className:`flex justify-center`,children:(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Preset`}),(0,C.jsxs)(`select`,{"aria-label":`Fan preset`,value:y,disabled:f,onChange:e=>{e.stopPropagation(),T(e.target.value)},className:Z(`bg-surface border border-border rounded px-1 py-0.5`,f&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(`option`,{value:``,disabled:!0,children:`—`}),_.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))]})]})}),(0,C.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[g?(0,C.jsxs)(`button`,{type:`button`,"aria-label":`Oscillate`,"aria-pressed":b,disabled:f,onClick:e=>{e.stopPropagation(),S()},className:Z(`inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors`,b?`border-success/50 bg-success/10 text-success`:`border-border text-foreground-muted hover:bg-surface-hover`,f&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(mR,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Oscillate`]}):(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l?`On`:`Off`}),(0,C.jsx)(EU,{on:l,busy:u,onToggle:x})]})]})}function RU({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:a,available:o}=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),{display:s,applyOptimistic:c}=Yz(a,{enabled:n??!0});if(r===void 0||s===void 0)return null;let l=s.on===!0,u=!o;return(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsx)(`div`,{"data-testid":`switch-glyph`,"data-state":l?`on`:`off`,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors`,l?`border-success/30 bg-success/10 text-success`:`border-border bg-surface-subtle text-foreground-subtle`),children:(0,C.jsx)(fR,{className:`h-8 w-8`,"aria-hidden":`true`})}),(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l?`On`:`Off`}),(0,C.jsx)(EU,{on:l,busy:u,onToggle:()=>{if(u)return;let e=!l;c({on:e}),r.setState({on:e})}})]})}function zU(e){return e===`playing`||e===`buffering`?`pause`:`play`}function BU(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function VU(e){if(e===null)return`--:--`;let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}function HU({title:e,subtitle:t}){return(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,C.jsx)(aR,{className:`h-6 w-6 text-foreground-subtle`,"aria-hidden":`true`}),(0,C.jsx)(`span`,{className:`text-base font-semibold text-foreground line-clamp-1`,children:e??`Nothing playing`}),t&&(0,C.jsx)(`span`,{className:`text-xs text-foreground-subtle line-clamp-1`,children:t})]})}function UU({label:e,busy:t,onPress:n,children:r,primary:a}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),t||n()},className:Z(`inline-flex items-center justify-center rounded-full transition-colors`,a?`h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md`:`h-10 w-10 text-foreground-muted hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:r})}function WU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s,d=zU(c.state),f=(n?.includes(js.MediaPlayerSeek)??!1)&&c.durationMs!==null&&c.durationMs>0,p=n?.includes(js.MediaPlayerNext)??!1,m=n?.includes(js.MediaPlayerPrevious)??!1,h=(n?.includes(js.MediaPlayerVolume)??!1)&&c.volumeLevel!==null,g=()=>{u||(d===`play`?(l({state:`playing`}),a.play({})):(l({state:`paused`}),a.pause({})))},_=c.currentMedia?.artist??c.currentMedia?.album??null,v=BU(c.positionMs,c.durationMs),y=c.volumeLevel??0;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsx)(HU,{title:c.currentMedia?.title??null,subtitle:_}),f&&(0,C.jsxs)(`div`,{"data-testid":`media-seek`,className:`flex flex-col gap-1`,children:[(0,C.jsxs)(`label`,{className:`relative block`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Seek`}),(0,C.jsx)(`input`,{"aria-label":`Seek`,type:`range`,min:0,max:c.durationMs??0,step:1e3,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:c.positionMs??0,disabled:u,onChange:e=>{if(u)return;let t=Number(e.target.value);l({positionMs:t}),a.seek({positionMs:t})}}),(0,C.jsx)(`div`,{className:`pointer-events-none`,children:(0,C.jsx)(Wz,{fraction:v})})]}),(0,C.jsxs)(`div`,{className:`flex justify-between text-[11px] tabular-nums text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:VU(c.positionMs)}),(0,C.jsx)(`span`,{children:VU(c.durationMs)})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center justify-center gap-4`,children:[m&&(0,C.jsx)(UU,{label:`Previous`,busy:u,onPress:()=>void a.previous({}),children:(0,C.jsx)(SR,{className:`h-5 w-5`,"aria-hidden":`true`})}),(0,C.jsx)(UU,{label:d===`play`?`Play`:`Pause`,busy:u,onPress:g,primary:!0,children:d===`play`?(0,C.jsx)(dR,{className:`h-6 w-6`,"aria-hidden":`true`}):(0,C.jsx)(cR,{className:`h-6 w-6`,"aria-hidden":`true`})}),p&&(0,C.jsx)(UU,{label:`Next`,busy:u,onPress:()=>void a.next({}),children:(0,C.jsx)(CR,{className:`h-5 w-5`,"aria-hidden":`true`})})]}),h&&(0,C.jsxs)(`div`,{"data-testid":`media-volume`,className:`flex items-center gap-2`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":c.isMuted===!0?`Unmute`:`Mute`,title:c.isMuted===!0?`Unmute`:`Mute`,disabled:u,onClick:e=>{if(e.stopPropagation(),u||c.isMuted===null)return;let t=!c.isMuted;l({isMuted:t}),a.setMute({muted:t})},className:Z(`inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,u&&`opacity-40 cursor-not-allowed`),children:c.isMuted===!0?(0,C.jsx)(HR,{className:`h-4 w-4`,"aria-hidden":`true`}):(0,C.jsx)(VR,{className:`h-4 w-4`,"aria-hidden":`true`})}),(0,C.jsxs)(`label`,{className:`relative block flex-1`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Volume`}),(0,C.jsx)(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:y,disabled:u,onChange:e=>{if(u)return;let t=Number(e.target.value);l({volumeLevel:t}),a.setVolume({volumeLevel:t})}}),(0,C.jsx)(`div`,{className:`pointer-events-none`,children:(0,C.jsx)(Wz,{fraction:y/100})})]}),(0,C.jsxs)(`span`,{className:`w-9 text-right text-[11px] tabular-nums text-foreground-subtle`,children:[y,`%`]})]})]})}var GU={disarmed:{label:`Disarmed`,colorClass:`border-border bg-surface-subtle text-foreground-subtle`,icon:`disarmed`},armed_home:{label:`Armed Home`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_away:{label:`Armed Away`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_night:{label:`Armed Night`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_vacation:{label:`Armed Vacation`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_custom_bypass:{label:`Armed (Bypass)`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},arming:{label:`Arming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},disarming:{label:`Disarming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},pending:{label:`Pending`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},triggered:{label:`Triggered`,colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`triggered`}},KU={home:`Home`,away:`Away`,night:`Night`,vacation:`Vacation`,custom_bypass:`Bypass`};function qU(e){return e.startsWith(`armed_`)}function JU(e){return e===`arming`||e===`disarming`}function YU({icon:e}){return e===`disarmed`?(0,C.jsx)(yR,{className:`h-8 w-8`,"aria-hidden":`true`}):e===`triggered`?(0,C.jsx)(_R,{className:`h-8 w-8`,"aria-hidden":`true`}):e===`pending`?(0,C.jsx)(bR,{className:`h-8 w-8`,"aria-hidden":`true`}):(0,C.jsx)(vR,{className:`h-8 w-8`,"aria-hidden":`true`})}function XU({label:e,active:t,busy:n,onSelect:r}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,"aria-pressed":t,disabled:n,onClick:e=>{e.stopPropagation(),n||r()},className:Z(`flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors`,t?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-muted hover:bg-surface-hover`,n&&`opacity-40 cursor-not-allowed`),children:e})}function ZU({state:e,availableModes:t,busy:n,onDisarm:r,onArm:a}){let o=qU(e),s=JU(e);return(0,C.jsxs)(`div`,{className:`flex items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1`,children:[(0,C.jsx)(XU,{label:`Disarm`,active:!o&&!s,busy:n,onSelect:r}),t.map(t=>(0,C.jsx)(XU,{label:KU[t],active:!s&&e===`armed_${t}`,busy:n,onSelect:()=>a(t)},t))]})}function QU(e,t,n){let{cap:r,slice:a,available:o}=Iz({trpc:e,deviceId:t,cap:e=>e.alarmPanel,slice:e=>e.state.alarmPanel}),{display:s,applyOptimistic:c}=Yz(a,{enabled:n??!0}),l=!o;return{display:s,capPresent:r!==void 0,busy:l,handleDisarm:()=>{r===void 0||l||(c({state:`disarming`}),r.disarm({}))},handleArm:e=>{r===void 0||l||(c({state:`arming`}),r.arm({mode:e}))}}}function $U({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:a,busy:o,handleDisarm:s,handleArm:c}=QU(e,t,n);return!a||r===void 0?null:(0,C.jsx)(ZU,{state:r.state,availableModes:r.availableModes,busy:o,onDisarm:s,onArm:c})}function eW({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:a,busy:o,handleDisarm:s,handleArm:c}=QU(e,t,n);if(!a||r===void 0)return null;let l=GU[r.state];return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,C.jsx)(`div`,{"data-testid":`alarm-state`,"data-state":r.state,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2`,l.colorClass),children:(0,C.jsx)(YU,{icon:l.icon})}),(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l.label})]}),(0,C.jsx)(ZU,{state:r.state,availableModes:r.availableModes,busy:o,onDisarm:s,onArm:c})]})}function tW({children:e}){return(0,C.jsx)(`div`,{className:`flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4`,children:e})}function nW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch});return n!==void 0}function rW({trpc:e,deviceId:t,features:n,optimistic:r}){return nW(e,t)?(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function iW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl});return n!==void 0}function aW({trpc:e,deviceId:t,features:n,optimistic:r}){return iW(e,t)?(0,C.jsx)(gH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function oW({trpc:e,deviceId:t,features:n,optimistic:r}){return nW(e,t)?(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),(0,C.jsx)(_H,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function sW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl});return n!==void 0}function cW({trpc:e,deviceId:t,features:n,optimistic:r}){return sW(e,t)?(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),(0,C.jsx)(vH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function lW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl});return n!==void 0}function uW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(SH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function dW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(MH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function fW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(MH,{trpc:e,deviceId:t,features:n,layout:`full`,optimistic:r}):null}function pW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer});return n!==void 0}function mW({trpc:e,deviceId:t,features:n,optimistic:r}){return pW(e,t)?(0,C.jsx)(qH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function hW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control});return n!==void 0}function gW({trpc:e,deviceId:t,features:n,optimistic:r}){return hW(e,t)?(0,C.jsx)(eU,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function _W({trpc:e,deviceId:t,features:n,optimistic:r}){return hW(e,t)?(0,C.jsx)(tW,{children:(0,C.jsx)(eU,{trpc:e,deviceId:t,features:n,layout:`full`,optimistic:r})}):null}var vW={cover:{InlineControl:$z,HeroCard:iB},valve:{InlineControl:gV,HeroCard:xV},humidifier:{InlineControl:wV,HeroCard:EV},"water-heater":{InlineControl:AV,HeroCard:MV},switch:{InlineControl:rW,HeroCard:RU},light:{InlineControl:oW,HeroCard:PU},fan:{InlineControl:cW,HeroCard:LU},sensor:{InlineControl:wB,HeroCard:NB},thermostat:{InlineControl:uW,HeroCard:fU},climate:{InlineControl:dW,HeroCard:fW},button:{InlineControl:Gz,HeroCard:Kz},update:{InlineControl:IB,HeroCard:LB},lock:{InlineControl:aW,HeroCard:yU},"media-player":{InlineControl:mW,HeroCard:WU},alarm:{InlineControl:$U,HeroCard:eW},control:{InlineControl:gW,HeroCard:_W},weather:{InlineControl:RV,HeroCard:UV},vacuum:{InlineControl:XB,HeroCard:QB},"lawn-mower":{InlineControl:lV,HeroCard:dV},image:{InlineControl:XV,HeroCard:ZV},"pet-feeder":{InlineControl:fH,HeroCard:pH},dummy:{InlineControl:aB,HeroCard:oB}};Object.fromEntries(Object.values(W).map(e=>[e,vW[Mh[e]]])),W.Cover,W.Valve,W.Thermostat,W.Climate,W.Control,W.Button,W.MediaPlayer,W.AlarmPanel,W.Lock,W.Vacuum,W.LawnMower,W.Humidifier,W.Switch,W.Siren,W.Light,W.Fan,W.WaterHeater,W.Sensor,W.Presence,W.EventEmitter,W.Notifier,W.Script,W.Automation,W.Camera,W.Hub,W.Update,W.Generic,W.Weather,W.Container,W.Image,W.PetFeeder,new Set(Object.values(W));var yW={[W.Camera]:{icon:dL,label:`Camera`},[W.Hub]:{icon:sR,label:`Hub`},[W.Light]:{icon:WL,label:`Light`},[W.Siren]:{icon:xR,label:`Siren`},[W.Switch]:{icon:PR,label:`Switch`},[W.Sensor]:{icon:$I,label:`Sensor`},[W.Thermostat]:{icon:NR,label:`Thermostat`},[W.Climate]:{icon:eL,label:`Air conditioner`},[W.Button]:{icon:_L,label:`Button`},[W.EventEmitter]:{icon:YR,label:`Event Emitter`},[W.Update]:{icon:mR,label:`Update`},[W.Generic]:{icon:uL,label:`Generic`},[W.Notifier]:{icon:oL,label:`Notifier`},[W.Script]:{icon:gR,label:`Script`},[W.Automation]:{icon:qR,label:`Automation`},[W.Lock]:{icon:YL,label:`Lock`},[W.Cover]:{icon:sL,label:`Cover`},[W.Valve]:{icon:uR,label:`Valve`},[W.Humidifier]:{icon:UR,label:`Humidifier`},[W.WaterHeater]:{icon:rL,label:`Water heater`},[W.Fan]:{icon:ML,label:`Fan`},[W.MediaPlayer]:{icon:eR,label:`Media player`},[W.AlarmPanel]:{icon:_R,label:`Alarm panel`},[W.Control]:{icon:wR,label:`Control`},[W.Presence]:{icon:ZL,label:`Presence`},[W.Weather]:{icon:CL,label:`Weather`},[W.Vacuum]:{icon:lL,label:`Vacuum`},[W.LawnMower]:{icon:FR,label:`Lawn mower`},[W.Container]:{icon:uL,label:`Container`},[W.Image]:{icon:HL,label:`Image`},[W.PetFeeder]:{icon:cL,label:`Pet feeder`}},bW={[G.Siren]:{icon:xR,label:`Siren`},[G.Floodlight]:{icon:WL,label:`Floodlight`},[G.Spotlight]:{icon:FL,label:`Spotlight`},[G.PirSensor]:{icon:pR,label:`PIR sensor`},[G.Chime]:{icon:oL,label:`Chime`},[G.Autotrack]:{icon:TL,label:`Auto-track`},[G.Nightvision]:{icon:tR,label:`Night vision`},[G.PrivacyMask]:{icon:jL,label:`Privacy mask`},[G.Doorbell]:{icon:EL,label:`Doorbell`},[G.BinaryHelper]:{icon:PR,label:`Binary helper`},[G.MotionSensor]:{icon:LL,label:`Motion sensor`},[G.ContactSensor]:{icon:DL,label:`Contact sensor`},[G.LeakSensor]:{icon:kL,label:`Leak sensor`},[G.SmokeSensor]:{icon:tL,label:`Smoke sensor`},[G.COSensor]:{icon:KR,label:`CO sensor`},[G.GasSensor]:{icon:PL,label:`Gas sensor`},[G.TamperSensor]:{icon:_R,label:`Tamper sensor`},[G.VibrationSensor]:{icon:BR,label:`Vibration sensor`},[G.ConnectivitySensor]:{icon:GR,label:`Connectivity`},[G.SoundSensor]:{icon:VR,label:`Sound sensor`},[G.BinarySensor]:{icon:PR,label:`Binary sensor`},[G.TemperatureSensor]:{icon:NR,label:`Temperature`},[G.HumiditySensor]:{icon:AL,label:`Humidity`},[G.AmbientLightSensor]:{icon:jR,label:`Ambient light`},[G.PressureSensor]:{icon:RL,label:`Pressure`},[G.WindSensor]:{icon:KR,label:`Wind`},[G.RainSensor]:{icon:xL,label:`Rain`},[G.UvSensor]:{icon:AR,label:`UV index`},[G.SolarRadiationSensor]:{icon:MR,label:`Solar radiation`},[G.SoilMoistureSensor]:{icon:OR,label:`Soil moisture`},[G.PowerSensor]:{icon:YR,label:`Power`},[G.EnergySensor]:{icon:YR,label:`Energy`},[G.VoltageSensor]:{icon:YR,label:`Voltage`},[G.CurrentSensor]:{icon:YR,label:`Current`},[G.AirQualitySensor]:{icon:KR,label:`Air quality`},[G.BatterySensor]:{icon:RL,label:`Battery`},[G.NumericSensor]:{icon:zL,label:`Numeric sensor`},[G.EnumSensor]:{icon:KL,label:`Enum sensor`},[G.DateTimeSensor]:{icon:vL,label:`Date / time`},[G.GenericSensor]:{icon:RL,label:`Sensor`},[G.NumericControl]:{icon:wR,label:`Numeric control`},[G.SelectControl]:{icon:GL,label:`Select control`},[G.TextControl]:{icon:RR,label:`Text control`},[G.DateTimeControl]:{icon:vL,label:`Date / time control`},[G.MobilePushNotifier]:{icon:TR,label:`Mobile push`},[G.MessagingNotifier]:{icon:$L,label:`Messaging`},[G.EmailNotifier]:{icon:XL,label:`Email`},[G.GenericNotifier]:{icon:oL,label:`Notifier`}},xW=new Set(Object.values(W));new Set(Object.values(G));function SW(e){return xW.has(e)}var CW=yW[W.Generic];bW[G.GenericSensor];function wW(e){return SW(e)?yW[e]??CW:CW}Object.values(W).map(e=>{let t=wW(e);return{id:e,label:t.label,icon:t.icon}}),(0,S.createContext)(null),new Set([W.Sensor,W.Presence]),Object.freeze([]);var TW={face:`#a855f7`,plate:`#ec4899`};Object.freeze({...Object.fromEntries(Object.values(Kc).filter(e=>e.category===`detection`||e.kind===`motion`).map(e=>[e.kind,e.color])),...TW});var EW=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},DW=class{constructor(e){this.generateIdentifier=e,this.kv=new EW}register(e,t){this.kv.getByValue(e)||(t||=this.generateIdentifier(e),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},OW=class extends DW{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t==`object`?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function kW(e){if(`values`in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function AW(e,t){let n=kW(e);if(`find`in n)return n.find(t);let r=n;for(let e=0;e<r.length;e++){let n=r[e];if(t(n))return n}}function jW(e,t){Object.entries(e).forEach(([e,n])=>t(n,e))}function MW(e,t){return e.indexOf(t)!==-1}function NW(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var PW=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return AW(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},FW=e=>Object.prototype.toString.call(e).slice(8,-1),IW=e=>e===void 0,LW=e=>e===null,RW=e=>typeof e!=`object`||!e||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,zW=e=>RW(e)&&Object.keys(e).length===0,BW=e=>Array.isArray(e),VW=e=>typeof e==`string`,HW=e=>typeof e==`number`&&!isNaN(e),UW=e=>typeof e==`boolean`,WW=e=>e instanceof RegExp,GW=e=>e instanceof Map,KW=e=>e instanceof Set,qW=e=>FW(e)===`Symbol`,JW=e=>e instanceof Date&&!isNaN(e.valueOf()),YW=e=>e instanceof Error,XW=e=>typeof e==`number`&&isNaN(e),ZW=e=>UW(e)||LW(e)||IW(e)||HW(e)||VW(e)||qW(e),QW=e=>typeof e==`bigint`,$W=e=>e===1/0||e===-1/0,eG=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),tG=e=>e instanceof URL,nG=e=>e.replace(/\\/g,`\\\\`).replace(/\./g,`\\.`),rG=e=>e.map(String).map(nG).join(`.`),iG=(e,t)=>{let n=[],r=``;for(let a=0;a<e.length;a++){let o=e.charAt(a);if(!t&&o===`\\`){let t=e.charAt(a+1);if(t===`\\`){r+=`\\`,a++;continue}else if(t!==`.`)throw Error(`invalid path`)}if(o===`\\`&&e.charAt(a+1)===`.`){r+=`.`,a++;continue}if(o===`.`){n.push(r),r=``;continue}r+=o}let a=r;return n.push(a),n};function aG(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var oG=[aG(IW,`undefined`,()=>null,()=>void 0),aG(QW,`bigint`,e=>e.toString(),e=>typeof BigInt<`u`?BigInt(e):(console.error(`Please add a BigInt polyfill.`),e)),aG(JW,`Date`,e=>e.toISOString(),e=>new Date(e)),aG(YW,`Error`,(e,t)=>{let n={name:e.name,message:e.message};return`cause`in e&&(n.cause=e.cause),t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n},(e,t)=>{let n=Error(e.message,{cause:e.cause});return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n}),aG(WW,`regexp`,e=>``+e,e=>{let t=e.slice(1,e.lastIndexOf(`/`)),n=e.slice(e.lastIndexOf(`/`)+1);return new RegExp(t,n)}),aG(KW,`set`,e=>[...e.values()],e=>new Set(e)),aG(GW,`map`,e=>[...e.entries()],e=>new Map(e)),aG(e=>XW(e)||$W(e),`number`,e=>XW(e)?`NaN`:e>0?`Infinity`:`-Infinity`,Number),aG(e=>e===0&&1/e==-1/0,`number`,()=>`-0`,Number),aG(tG,`URL`,e=>e.toString(),e=>new URL(e))];function sG(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var cG=sG((e,t)=>qW(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>[`symbol`,t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown symbol`);return r}),lG=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),uG=sG(eG,e=>[`typed-array`,e.constructor.name],e=>[...e],(e,t)=>{let n=lG[t[1]];if(!n)throw Error(`Trying to deserialize unknown typed array`);return new n(e)});function dG(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var fG=sG(dG,(e,t)=>[`class`,t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(t=>{r[t]=e[t]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),pG=sG((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>[`custom`,t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw Error(`Trying to deserialize unknown custom value`);return r.deserialize(e)}),mG=[fG,cG,pG,uG],hG=(e,t)=>{let n=NW(mG,n=>n.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=NW(oG,n=>n.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},gG={};oG.forEach(e=>{gG[e.annotation]=e});var _G=(e,t,n)=>{if(BW(t))switch(t[0]){case`symbol`:return cG.untransform(e,t,n);case`class`:return fG.untransform(e,t,n);case`custom`:return pG.untransform(e,t,n);case`typed-array`:return uG.untransform(e,t,n);default:throw Error(`Unknown transformation: `+t)}else{let r=gG[t];if(!r)throw Error(`Unknown transformation: `+t);return r.untransform(e,n)}},vG=(e,t)=>{if(t>e.size)throw Error(`index out of bounds`);let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function yG(e){if(MW(e,`__proto__`))throw Error(`__proto__ is not allowed as a property`);if(MW(e,`prototype`))throw Error(`prototype is not allowed as a property`);if(MW(e,`constructor`))throw Error(`constructor is not allowed as a property`)}var bG=(e,t)=>{yG(t);for(let n=0;n<t.length;n++){let r=t[n];if(KW(e))e=vG(e,+r);else if(GW(e)){let a=+r,o=+t[++n]==0?`key`:`value`,s=vG(e,a);switch(o){case`key`:e=s;break;case`value`:e=e.get(s);break}}else e=e[r]}return e},xG=(e,t,n)=>{if(yG(t),t.length===0)return n(e);let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(BW(r)){let e=+n;r=r[e]}else if(RW(r))r=r[n];else if(KW(r)){let e=+n;r=vG(r,e)}else if(GW(r)){if(e===t.length-2)break;let a=+n,o=+t[++e]==0?`key`:`value`,s=vG(r,a);switch(o){case`key`:r=s;break;case`value`:r=r.get(s);break}}}let a=t[t.length-1];if(BW(r)?r[+a]=n(r[+a]):RW(r)&&(r[a]=n(r[a])),KW(r)){let e=vG(r,+a),t=n(e);e!==t&&(r.delete(e),r.add(t))}if(GW(r)){let e=+t[t.length-2],o=vG(r,e);switch(+a==0?`key`:`value`){case`key`:{let e=n(o);r.set(e,r.get(o)),e!==o&&r.delete(o);break}case`value`:r.set(o,n(r.get(o)));break}}return e},SG=e=>e<1;function CG(e,t,n,r=[]){if(!e)return;let a=SG(n);if(!BW(e)){jW(e,(e,o)=>CG(e,t,n,[...r,...iG(o,a)]));return}let[o,s]=e;s&&jW(s,(e,o)=>{CG(e,t,n,[...r,...iG(o,a)])}),t(o,r)}function wG(e,t,n,r){return CG(t,(t,n)=>{e=xG(e,n,e=>_G(e,t,r))},n),e}function TG(e,t,n){let r=SG(n);function a(t,n){let a=bG(e,iG(n,r));t.map(e=>iG(e,r)).forEach(t=>{e=xG(e,t,()=>a)})}if(BW(t)){let[n,o]=t;n.forEach(t=>{e=xG(e,iG(t,r),()=>e)}),o&&jW(o,a)}else jW(t,a);return e}var EG=(e,t)=>RW(e)||BW(e)||GW(e)||KW(e)||YW(e)||dG(e,t);function DG(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function OG(e,t){let n={},r;return e.forEach(e=>{if(e.length<=1)return;t||(e=e.map(e=>e.map(String)).sort((e,t)=>e.length-t.length));let[a,...o]=e;a.length===0?r=o.map(rG):n[rG(a)]=o.map(rG)}),r?zW(n)?[r]:[r,n]:zW(n)?void 0:n}var kG=(e,t,n,r,a=[],o=[],s=new Map)=>{let c=ZW(e);if(!c){DG(e,a,t);let n=s.get(e);if(n)return r?{transformedValue:null}:n}if(!EG(e,n)){let t=hG(e,n),r=t?{transformedValue:t.value,annotations:[t.type]}:{transformedValue:e};return c||s.set(e,r),r}if(MW(o,e))return{transformedValue:null};let l=hG(e,n),u=l?.value??e,d=BW(u)?[]:{},f={};jW(u,(c,l)=>{if(l===`__proto__`||l===`constructor`||l===`prototype`)throw Error(`Detected property ${l}. This is a prototype pollution risk, please remove it from your object.`);let u=kG(c,t,n,r,[...a,l],[...o,e],s);d[l]=u.transformedValue,BW(u.annotations)?f[nG(l)]=u.annotations:RW(u.annotations)&&jW(u.annotations,(e,t)=>{f[nG(l)+`.`+t]=e})});let p=zW(f)?{transformedValue:d,annotations:l?[l.type]:void 0}:{transformedValue:d,annotations:l?[l.type,f]:f};return c||s.set(e,p),p};function AG(e){return Object.prototype.toString.call(e).slice(8,-1)}function jG(e){return AG(e)===`Array`}function MG(e){if(AG(e)!==`Object`)return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function NG(e,t,n,r,a){let o={}.propertyIsEnumerable.call(r,t)?`enumerable`:`nonenumerable`;o===`enumerable`&&(e[t]=n),a&&o===`nonenumerable`&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function PG(e,t={}){if(jG(e))return e.map(e=>PG(e,t));if(!MG(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((n,r)=>{if(r===`__proto__`||jG(t.props)&&!t.props.includes(r))return n;let a=e[r];return NG(n,r,PG(a,t),e,t.nonenumerable),n},{})}var FG=class{constructor({dedupe:e=!1}={}){this.classRegistry=new OW,this.symbolRegistry=new DW(e=>e.description??``),this.customTransformerRegistry=new PW,this.allowedErrorProps=[],this.dedupe=e}serialize(e){let t=new Map,n=kG(e,t,this,this.dedupe),r={json:n.transformedValue};n.annotations&&(r.meta={...r.meta,values:n.annotations});let a=OG(t,this.dedupe);return a&&(r.meta={...r.meta,referentialEqualities:a}),r.meta&&(r.meta.v=1),r}deserialize(e,t){let{json:n,meta:r}=e,a=t?.inPlace?n:PG(n);return r?.values&&(a=wG(a,r.values,r.v??0,this)),r?.referentialEqualities&&(a=TG(a,r.referentialEqualities,r.v??0)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};FG.defaultInstance=new FG,FG.serialize=FG.defaultInstance.serialize.bind(FG.defaultInstance),FG.deserialize=FG.defaultInstance.deserialize.bind(FG.defaultInstance),FG.stringify=FG.defaultInstance.stringify.bind(FG.defaultInstance),FG.parse=FG.defaultInstance.parse.bind(FG.defaultInstance),FG.registerClass=FG.defaultInstance.registerClass.bind(FG.defaultInstance),FG.registerSymbol=FG.defaultInstance.registerSymbol.bind(FG.defaultInstance),FG.registerCustom=FG.defaultInstance.registerCustom.bind(FG.defaultInstance),FG.allowErrorProps=FG.defaultInstance.allowErrorProps.bind(FG.defaultInstance),FG.serialize,FG.deserialize,FG.stringify,FG.parse,FG.registerClass,FG.registerCustom,FG.registerSymbol,FG.allowErrorProps,(0,S.createContext)(null),ZM(`camstack:custom-field-renderers`,{}),ZM(`camstack:device-context`,null),ZM(`camstack:widget-registry`,null);function IG({title:e,icon:t,headerRight:n,collapsible:r=!1,defaultOpen:a=!0,bodyClassName:o=`p-3`,children:s}){let[c,l]=(0,S.useState)(a),u=!r||c,d=(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`span`,{className:`flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground`,children:[t,e]}),r?c?(0,C.jsx)(pL,{className:`h-3.5 w-3.5 text-foreground-subtle`}):(0,C.jsx)(mL,{className:`h-3.5 w-3.5 text-foreground-subtle`}):n]}),f=`px-4 py-2 flex items-center justify-between ${u?`border-b border-border`:``}`;return(0,C.jsxs)(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r?(0,C.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`w-full text-left ${f}`,children:d}):(0,C.jsx)(`div`,{className:f,children:d}),u?(0,C.jsx)(`div`,{className:o,children:s}):null]})}ZM(`camstack:vod-playback`,{request:null,play:()=>{},clear:()=>{}}),ZM(`camstack:recorded-playback`,{bindControlChannel:null,channelOpen:!1,mode:`live`,positionMs:null,send:()=>!1}),(0,S.lazy)(()=>fs(()=>import(`./MotionZonesSettings-NcxxQN8r-o7HcwAxC.js`).then(e=>({default:e.MotionZonesSettings})),__vite__mapDeps([0,1]),import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./PrivacyMaskSettings-APgPLF7p-B2TnFjvh.js`).then(e=>({default:e.PrivacyMaskSettings})),__vite__mapDeps([2,1]),import.meta.url));var LG=Object.defineProperty,RG=Object.getOwnPropertySymbols,zG=Object.prototype.hasOwnProperty,BG=Object.prototype.propertyIsEnumerable,VG=(e,t,n)=>t in e?LG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,HG=(e,t)=>{for(var n in t||={})zG.call(t,n)&&VG(e,n,t[n]);if(RG)for(var n of RG(t))BG.call(t,n)&&VG(e,n,t[n]);return e},UG=(e,t)=>{var n={};for(var r in e)zG.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&RG)for(var r of RG(e))t.indexOf(r)<0&&BG.call(e,r)&&(n[r]=e[r]);return n},WG;(e=>{let t=class t{constructor(e,n,r,o){if(this.version=e,this.errorCorrectionLevel=n,this.modules=[],this.isFunction=[],e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version value out of range`);if(o<-1||o>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let s=[];for(let e=0;e<this.size;e++)s.push(!1);for(let e=0;e<this.size;e++)this.modules.push(s.slice()),this.isFunction.push(s.slice());this.drawFunctionPatterns();let c=this.addEccAndInterleave(r);if(this.drawCodewords(c),o==-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(o=t,e=n),this.applyMask(t)}}a(0<=o&&o<=7),this.mask=o,this.applyMask(o),this.drawFormatBits(o),this.isFunction=[]}static encodeText(n,r){let a=e.QrSegment.makeSegments(n);return t.encodeSegments(a,r)}static encodeBinary(n,r){let a=e.QrSegment.makeBytes(n);return t.encodeSegments([a],r)}static encodeSegments(e,r,o=1,c=40,l=-1,u=!0){if(!(t.MIN_VERSION<=o&&o<=c&&c<=t.MAX_VERSION)||l<-1||l>7)throw RangeError(`Invalid value`);let d,f;for(d=o;;d++){let n=t.getNumDataCodewords(d,r)*8,a=s.getTotalBits(e,d);if(a<=n){f=a;break}if(d>=c)throw RangeError(`Data too long`)}for(let e of[t.Ecc.MEDIUM,t.Ecc.QUARTILE,t.Ecc.HIGH])u&&f<=t.getNumDataCodewords(d,e)*8&&(r=e);let p=[];for(let t of e){n(t.mode.modeBits,4,p),n(t.numChars,t.mode.numCharCountBits(d),p);for(let e of t.getData())p.push(e)}a(p.length==f);let m=t.getNumDataCodewords(d,r)*8;a(p.length<=m),n(0,Math.min(4,m-p.length),p),n(0,(8-p.length%8)%8,p),a(p.length%8==0);for(let e=236;p.length<m;e^=253)n(e,8,p);let h=[];for(;h.length*8<p.length;)h.push(0);return p.forEach((e,t)=>h[t>>>3]|=e<<7-(t&7)),new t(d,r,h,l)}getModule(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]}getModules(){return this.modules}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n==0&&r==0||n==0&&r==t-1||n==t-1&&r==0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.errorCorrectionLevel.formatBits<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let o=(t<<10|n)^21522;a(o>>>15==0);for(let e=0;e<=5;e++)this.setFunctionModule(8,e,r(o,e));this.setFunctionModule(8,7,r(o,6)),this.setFunctionModule(8,8,r(o,7)),this.setFunctionModule(7,8,r(o,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,r(o,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,r(o,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,r(o,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;a(t>>>18==0);for(let e=0;e<18;e++){let n=r(t,e),a=this.size-11+e%3,o=Math.floor(e/3);this.setFunctionModule(a,o,n),this.setFunctionModule(o,a,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let a=Math.max(Math.abs(r),Math.abs(n)),o=e+r,s=t+n;0<=o&&o<this.size&&0<=s&&s<this.size&&this.setFunctionModule(o,s,a!=2&&a!=4)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!=1)}setFunctionModule(e,t,n){this.modules[t][e]=n,this.isFunction[t][e]=!0}addEccAndInterleave(e){let n=this.version,r=this.errorCorrectionLevel;if(e.length!=t.getNumDataCodewords(n,r))throw RangeError(`Invalid argument`);let o=t.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][n],s=t.ECC_CODEWORDS_PER_BLOCK[r.ordinal][n],c=Math.floor(t.getNumRawDataModules(n)/8),l=o-c%o,u=Math.floor(c/o),d=[],f=t.reedSolomonComputeDivisor(s);for(let n=0,r=0;n<o;n++){let a=e.slice(r,r+u-s+(n<l?0:1));r+=a.length;let o=t.reedSolomonComputeRemainder(a,f);n<l&&a.push(0),d.push(a.concat(o))}let p=[];for(let e=0;e<d[0].length;e++)d.forEach((t,n)=>{(e!=u-s||n>=l)&&p.push(t[e])});return a(p.length==c),p}drawCodewords(e){if(e.length!=Math.floor(t.getNumRawDataModules(this.version)/8))throw RangeError(`Invalid argument`);let n=0;for(let t=this.size-1;t>=1;t-=2){t==6&&(t=5);for(let a=0;a<this.size;a++)for(let o=0;o<2;o++){let s=t-o,c=t+1&2?a:this.size-1-a;!this.isFunction[c][s]&&n<e.length*8&&(this.modules[c][s]=r(e[n>>>3],7-(n&7)),n++)}}a(n==e.length*8)}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.isFunction[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let n=0;n<this.size;n++){let r=!1,a=0,o=[0,0,0,0,0,0,0];for(let s=0;s<this.size;s++)this.modules[n][s]==r?(a++,a==5?e+=t.PENALTY_N1:a>5&&e++):(this.finderPenaltyAddHistory(a,o),r||(e+=this.finderPenaltyCountPatterns(o)*t.PENALTY_N3),r=this.modules[n][s],a=1);e+=this.finderPenaltyTerminateAndCount(r,a,o)*t.PENALTY_N3}for(let n=0;n<this.size;n++){let r=!1,a=0,o=[0,0,0,0,0,0,0];for(let s=0;s<this.size;s++)this.modules[s][n]==r?(a++,a==5?e+=t.PENALTY_N1:a>5&&e++):(this.finderPenaltyAddHistory(a,o),r||(e+=this.finderPenaltyCountPatterns(o)*t.PENALTY_N3),r=this.modules[s][n],a=1);e+=this.finderPenaltyTerminateAndCount(r,a,o)*t.PENALTY_N3}for(let n=0;n<this.size-1;n++)for(let r=0;r<this.size-1;r++){let a=this.modules[n][r];a==this.modules[n][r+1]&&a==this.modules[n+1][r]&&a==this.modules[n+1][r+1]&&(e+=t.PENALTY_N2)}let n=0;for(let e of this.modules)n=e.reduce((e,t)=>e+ +!!t,n);let r=this.size*this.size,o=Math.ceil(Math.abs(n*20-r*10)/r)-1;return a(0<=o&&o<=9),e+=o*t.PENALTY_N4,a(0<=e&&e<=2568888),e}getAlignmentPatternPositions(){if(this.version==1)return[];{let e=Math.floor(this.version/7)+2,t=this.version==32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}static getNumRawDataModules(e){if(e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version number out of range`);let n=(16*e+128)*e+64;if(e>=2){let t=Math.floor(e/7)+2;n-=(25*t-10)*t-55,e>=7&&(n-=36)}return a(208<=n&&n<=29648),n}static getNumDataCodewords(e,n){return Math.floor(t.getNumRawDataModules(e)/8)-t.ECC_CODEWORDS_PER_BLOCK[n.ordinal][e]*t.NUM_ERROR_CORRECTION_BLOCKS[n.ordinal][e]}static reedSolomonComputeDivisor(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let n=[];for(let t=0;t<e-1;t++)n.push(0);n.push(1);let r=1;for(let a=0;a<e;a++){for(let e=0;e<n.length;e++)n[e]=t.reedSolomonMultiply(n[e],r),e+1<n.length&&(n[e]^=n[e+1]);r=t.reedSolomonMultiply(r,2)}return n}static reedSolomonComputeRemainder(e,n){let r=n.map(e=>0);for(let a of e){let e=a^r.shift();r.push(0),n.forEach((n,a)=>r[a]^=t.reedSolomonMultiply(n,e))}return r}static reedSolomonMultiply(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return a(n>>>8==0),n}finderPenaltyCountPatterns(e){let t=e[1];a(t<=this.size*3);let n=t>0&&e[2]==t&&e[3]==t*3&&e[4]==t&&e[5]==t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]==0&&(e+=this.size),t.pop(),t.unshift(e)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function n(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function r(e,t){return(e>>>t&1)!=0}function a(e){if(!e)throw Error(`Assertion error`)}let o=class e{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}static makeBytes(t){let r=[];for(let e of t)n(e,8,r);return new e(e.Mode.BYTE,t.length,r)}static makeNumeric(t){if(!e.isNumeric(t))throw RangeError(`String contains non-numeric characters`);let r=[];for(let e=0;e<t.length;){let a=Math.min(t.length-e,3);n(parseInt(t.substring(e,e+a),10),a*3+1,r),e+=a}return new e(e.Mode.NUMERIC,t.length,r)}static makeAlphanumeric(t){if(!e.isAlphanumeric(t))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let r=[],a;for(a=0;a+2<=t.length;a+=2){let o=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a))*45;o+=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a+1)),n(o,11,r)}return a<t.length&&n(e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a)),6,r),new e(e.Mode.ALPHANUMERIC,t.length,r)}static makeSegments(t){return t==``?[]:e.isNumeric(t)?[e.makeNumeric(t)]:e.isAlphanumeric(t)?[e.makeAlphanumeric(t)]:[e.makeBytes(e.toUtf8ByteArray(t))]}static makeEci(t){let r=[];if(t<0)throw RangeError(`ECI assignment value out of range`);if(t<128)n(t,8,r);else if(t<16384)n(2,2,r),n(t,14,r);else if(t<1e6)n(6,3,r),n(t,21,r);else throw RangeError(`ECI assignment value out of range`);return new e(e.Mode.ECI,0,r)}static isNumeric(t){return e.NUMERIC_REGEX.test(t)}static isAlphanumeric(t){return e.ALPHANUMERIC_REGEX.test(t)}getData(){return this.bitData.slice()}static getTotalBits(e,t){let n=0;for(let r of e){let e=r.mode.numCharCountBits(t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}static toUtf8ByteArray(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)==`%`?(t.push(parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}};o.NUMERIC_REGEX=/^[0-9]*$/,o.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,o.ALPHANUMERIC_CHARSET=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`;let s=o;e.QrSegment=o})(WG||={}),(e=>{(e=>{let t=class{constructor(e,t){this.ordinal=e,this.formatBits=t}};t.LOW=new t(0,1),t.MEDIUM=new t(1,0),t.QUARTILE=new t(2,3),t.HIGH=new t(3,2),e.Ecc=t})(e.QrCode||={})})(WG||={}),(e=>{(e=>{let t=class{constructor(e,t){this.modeBits=e,this.numBitsCharCount=t}numCharCountBits(e){return this.numBitsCharCount[Math.floor((e+7)/17)]}};t.NUMERIC=new t(1,[10,12,14]),t.ALPHANUMERIC=new t(2,[9,11,13]),t.BYTE=new t(4,[8,16,16]),t.KANJI=new t(8,[8,10,12]),t.ECI=new t(7,[0,0,0]),e.Mode=t})(e.QrSegment||={})})(WG||={});var GG=WG,KG={L:GG.QrCode.Ecc.LOW,M:GG.QrCode.Ecc.MEDIUM,Q:GG.QrCode.Ecc.QUARTILE,H:GG.QrCode.Ecc.HIGH},qG=128,JG=`L`,YG=`#FFFFFF`,XG=`#000000`,ZG=!1,QG=1,$G=4,eK=0,tK=.1;function nK(e,t=0){let n=[];return e.forEach(function(e,r){let a=null;e.forEach(function(o,s){if(!o&&a!==null){n.push(`M${a+t} ${r+t}h${s-a}v1H${a+t}z`),a=null;return}if(s===e.length-1){if(!o)return;a===null?n.push(`M${s+t},${r+t} h1v1H${s+t}z`):n.push(`M${a+t},${r+t} h${s+1-a}v1H${a+t}z`);return}o&&a===null&&(a=s)})}),n.join(``)}function rK(e,t){return e.slice().map((e,n)=>n<t.y||n>=t.y+t.h?e:e.map((e,n)=>n<t.x||n>=t.x+t.w?e:!1))}function iK(e,t,n,r){if(r==null)return null;let a=e.length+n*2,o=Math.floor(t*tK),s=a/t,c=(r.width||o)*s,l=(r.height||o)*s,u=r.x==null?e.length/2-c/2:r.x*s,d=r.y==null?e.length/2-l/2:r.y*s,f=r.opacity==null?1:r.opacity,p=null;if(r.excavate){let e=Math.floor(u),t=Math.floor(d);p={x:e,y:t,w:Math.ceil(c+u-e),h:Math.ceil(l+d-t)}}let m=r.crossOrigin;return{x:u,y:d,h:l,w:c,excavation:p,opacity:f,crossOrigin:m}}function aK(e,t){return t==null?e?$G:eK:Math.max(Math.floor(t),0)}function oK({value:e,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:o,size:s,boostLevel:c}){let l=S.useMemo(()=>{let r=(Array.isArray(e)?e:[e]).reduce((e,t)=>(e.push(...GG.QrSegment.makeSegments(t)),e),[]);return GG.QrCode.encodeSegments(r,KG[t],n,void 0,void 0,c)},[e,t,n,c]),{cells:u,margin:d,numCells:f,calculatedImageSettings:p}=S.useMemo(()=>{let e=l.getModules(),t=aK(r,a);return{cells:e,margin:t,numCells:e.length+t*2,calculatedImageSettings:iK(e,s,t,o)}},[l,s,o,r,a]);return{qrcode:l,margin:d,cells:u,numCells:f,calculatedImageSettings:p}}var sK=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),cK=S.forwardRef(function(e,t){let n=e,{value:r,size:a=qG,level:o=JG,bgColor:s=YG,fgColor:c=XG,includeMargin:l=ZG,minVersion:u=QG,boostLevel:d,marginSize:f,imageSettings:p}=n,m=UG(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`marginSize`,`imageSettings`]),{style:h}=m,g=UG(m,[`style`]),_=p?.src,v=S.useRef(null),y=S.useRef(null),b=S.useCallback(e=>{v.current=e,typeof t==`function`?t(e):t&&(t.current=e)},[t]),[x,C]=S.useState(!1),{margin:w,cells:T,numCells:E,calculatedImageSettings:D}=oK({value:r,level:o,minVersion:u,boostLevel:d,includeMargin:l,marginSize:f,imageSettings:p,size:a});S.useEffect(()=>{if(v.current!=null){let e=v.current,t=e.getContext(`2d`);if(!t)return;let n=T,r=y.current,o=D!=null&&r!==null&&r.complete&&r.naturalHeight!==0&&r.naturalWidth!==0;o&&D.excavation!=null&&(n=rK(T,D.excavation));let l=window.devicePixelRatio||1;e.height=e.width=a*l;let u=a/E*l;t.scale(u,u),t.fillStyle=s,t.fillRect(0,0,E,E),t.fillStyle=c,sK?t.fill(new Path2D(nK(n,w))):T.forEach(function(e,n){e.forEach(function(e,r){e&&t.fillRect(r+w,n+w,1,1)})}),D&&(t.globalAlpha=D.opacity),o&&t.drawImage(r,D.x+w,D.y+w,D.w,D.h)}}),S.useEffect(()=>{C(!1)},[_]);let ee=HG({height:a,width:a},h),te=null;return _!=null&&(te=S.createElement(`img`,{src:_,key:_,style:{display:`none`},onLoad:()=>{C(!0)},ref:y,crossOrigin:D?.crossOrigin})),S.createElement(S.Fragment,null,S.createElement(`canvas`,HG({style:ee,height:a,width:a,ref:b,role:`img`},g)),te)});cK.displayName=`QRCodeCanvas`;var lK=S.forwardRef(function(e,t){let n=e,{value:r,size:a=qG,level:o=JG,bgColor:s=YG,fgColor:c=XG,includeMargin:l=ZG,minVersion:u=QG,boostLevel:d,title:f,marginSize:p,imageSettings:m}=n,h=UG(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`title`,`marginSize`,`imageSettings`]),{margin:g,cells:_,numCells:v,calculatedImageSettings:y}=oK({value:r,level:o,minVersion:u,boostLevel:d,includeMargin:l,marginSize:p,imageSettings:m,size:a}),b=_,x=null;m!=null&&y!=null&&(y.excavation!=null&&(b=rK(_,y.excavation)),x=S.createElement(`image`,{href:m.src,height:y.h,width:y.w,x:y.x+g,y:y.y+g,preserveAspectRatio:`none`,opacity:y.opacity,crossOrigin:y.crossOrigin}));let C=nK(b,g);return S.createElement(`svg`,HG({height:a,width:a,viewBox:`0 0 ${v} ${v}`,ref:t,role:`img`},h),!!f&&S.createElement(`title`,null,f),S.createElement(`path`,{fill:s,d:`M0,0 h${v}v${v}H0z`,shapeRendering:`crispEdges`}),S.createElement(`path`,{fill:c,d:C,shapeRendering:`crispEdges`}),x)});lK.displayName=`QRCodeSVG`;function uK(){return typeof window>`u`?!1:window.matchMedia(`(hover: none) and (pointer: coarse)`).matches||typeof navigator<`u`&&navigator.maxTouchPoints>0||`ontouchstart`in window}function dK(e,t,n){let r=0;for(let a=0;a<8;a++)for(let o=0;o<8;o++){let s=Math.min(t-1,Math.floor((o+.5)/8*t)),c=Math.min(n-1,Math.floor((a+.5)/8*n)),{data:l}=e.getImageData(s,c,1,1);.2126*(l[0]??0)+.7152*(l[1]??0)+.0722*(l[2]??0)>12&&r++}return r<=1}function fK(e){let t={};if(typeof window<`u`){if(e){let n=e.getBoundingClientRect();n.width>0&&n.height>0&&(t.viewportWidth=Math.round(n.width),t.viewportHeight=Math.round(n.height))}t.viewportWidth===void 0&&(t.viewportWidth=window.innerWidth,t.viewportHeight=window.innerHeight),t.devicePixelRatio=window.devicePixelRatio||1;let n=navigator.connection;n?.downlink&&n.downlink>0&&(t.downlinkMbps=n.downlink)}return t}var pK=1500,mK=15e3,hK=40,gK=8e3;function _K({serverUrl:e,streamKey:t,label:n,autoPlay:r=!0,muted:a=!0,showControls:o=!0,showStats:s=!1,onPlaybackStats:c,onClientNetworkSample:l,onConnectTiming:u,className:d=``,onStateChange:f,onError:p,overlay:m,createSession:h,sendAnswer:g,handleOffer:_,getIceServers:v,addIceCandidate:y,getIceCandidates:b,closeSession:x,getSessionState:w,reoffer:T,posterUrl:E,hintsOverride:D,reconnectSignal:ee,onControlChannel:te}){let O=(0,S.useRef)(null),ne=(0,S.useRef)(null),re=(0,S.useRef)(null),ie=(0,S.useRef)(new Set),ae=(0,S.useRef)(null),oe=(0,S.useRef)(null),se=(0,S.useRef)(0),k=(0,S.useRef)(!0),A=(0,S.useRef)(te);A.current=te;let ce=(0,S.useRef)(null),le=(0,S.useRef)(null),ue=(0,S.useRef)(0),de=(0,S.useRef)(!1),j=(0,S.useRef)(async()=>{}),[M,fe]=(0,S.useState)(`idle`),[pe,me]=(0,S.useState)(``),[he,ge]=(0,S.useState)(a),[_e,N]=(0,S.useState)(!1),[ve,ye]=(0,S.useState)(!1),be=uK(),[xe,Se]=(0,S.useState)(!0),Ce=(0,S.useRef)(null),we=(0,S.useRef)(!1);(g||h)&&(we.current=!0);let Te=we.current,Ee=(0,S.useRef)(!1);_&&(Ee.current=!0);let De=Ee.current,[Oe,ke]=(0,S.useState)(!1),Ae=(0,S.useRef)(null),[je,Me]=(0,S.useState)(null),[Ne,Pe]=(0,S.useState)(!1),Fe=(0,S.useCallback)(()=>{let e=O.current;if(!(!e||e.readyState<2||!e.videoWidth||!e.videoHeight))try{let t=document.createElement(`canvas`);t.width=e.videoWidth,t.height=e.videoHeight;let n=t.getContext(`2d`);if(!n||(n.drawImage(e,0,0),dK(n,t.width,t.height)))return;Ae.current=t.toDataURL(`image/jpeg`,.6)}catch{}},[]),Ie=(0,S.useCallback)(e=>{fe(e),e===`playing`&&ke(!0),f?.(e)},[f]),Le=(0,S.useCallback)(()=>{if(ae.current?.abort(),ae.current=null,oe.current&&=(clearTimeout(oe.current),null),le.current&&=(clearTimeout(le.current),null),ce.current=null,de.current=!1,ue.current=0,re.current&&=(re.current.close(),null),x&&ie.current.size>0){for(let e of ie.current)x(e).catch(()=>{});ie.current.clear()}},[x]),Re=(0,S.useCallback)(()=>{ae.current?.abort(),ae.current=null,oe.current&&=(clearTimeout(oe.current),null),le.current&&=(clearTimeout(le.current),null),ce.current=null,de.current=!1,ue.current=0},[]),ze=1e3,Be=(0,S.useCallback)(e=>{if(!w||!T)return;le.current&&=(clearTimeout(le.current),null);let t=async()=>{if(k.current&&ce.current===e){if(!de.current)try{let{pendingRenegotiation:t}=await w(e);if(k.current&&ce.current===e&&t&&t.epoch>ue.current&&!de.current){ue.current=t.epoch,await j.current(e,t.target);return}}catch{}!k.current||ce.current!==e||(le.current=setTimeout(()=>{t()},ze))}};le.current=setTimeout(()=>{t()},ze)},[w,T]),Ve=(0,S.useCallback)(async(e=!1)=>{if(!k.current||!h||!g)return;let t=e?re.current:null,n=e?new Set(ie.current):null;e?Re():Le(),Ie(`connecting`);let r=new AbortController;ae.current=r;try{let{sessionId:a,sdpOffer:o,iceServers:s}=await h({...fK(ne.current),...D});if(ie.current.add(a),!k.current||r.signal.aborted){x?.(a).catch(()=>{}),ie.current.delete(a);return}let c=new RTCPeerConnection({iceServers:[...s??[],{urls:`stun:stun.l.google.com:19302`}]});e||(re.current=c);let l=new MediaStream,u=!1,d=()=>{if(!(u||!k.current)){if(u=!0,re.current=c,O.current&&(O.current.srcObject=l,O.current.play().catch(()=>{})),t&&t!==c)try{t.close()}catch{}if(n)for(let e of n)ie.current.delete(e),x?.(e).catch(()=>{})}};c.ontrack=t=>{if(console.debug(`[WebRTC] ontrack`,t.track.kind,t.track.readyState),l.addTrack(t.track),e){d();return}O.current&&(O.current.srcObject=l,O.current.play().catch(()=>{}))},c.oniceconnectionstatechange=()=>{if(!k.current)return;let t=c.iceConnectionState;if(console.debug(`[WebRTC] ICE state:`,t),t===`connected`||t===`completed`)se.current=0,e&&d(),Ie(`playing`),O.current?.paused&&(console.debug(`[WebRTC] video was paused at ICE connected — calling play()`),O.current.play().catch(()=>{}));else if(t===`failed`||t===`disconnected`||t===`closed`){if(e&&!u)try{c.close()}catch{}Ie(`disconnected`),Ke()}},c.onicecandidateerror=e=>{console.debug(`[WebRTC] ICE candidate error:`,e)},console.debug(`[WebRTC] Setting remote description (server offer)...`),await c.setRemoteDescription({type:`offer`,sdp:o});let f=await c.createAnswer();if(await c.setLocalDescription(f),console.debug(`[WebRTC] Local description set, waiting for ICE gathering...`),await yK(c),!k.current)return;let p=(c.localDescription?.sdp??``).split(`
|
|
111
|
-
`).filter(e=>e.startsWith(`a=candidate:`)).length;console.debug(`[WebRTC] Sending answer to server`,{localCandidates:p,sessionId:a.slice(0,8)}),await g(a,c.localDescription?.sdp??``),console.debug(`[WebRTC] Answer sent successfully`);let m=c,_=()=>{let e=m.connectionState;if(e===`closed`||e===`failed`)return;let t=O.current;t&&t.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${m.iceConnectionState})`)};setTimeout(_,3e3),setTimeout(_,8e3)}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}},[e,t,h,g,Le,Re,x,Ie,p,D]),He=(0,S.useCallback)(async()=>{if(k.current){Le(),Ie(`connecting`);try{let n=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});re.current=n,n.addTransceiver(`video`,{direction:`recvonly`}),n.addTransceiver(`audio`,{direction:`recvonly`});let r=new MediaStream;n.ontrack=e=>{r.addTrack(e.track),O.current&&(O.current.srcObject=r,O.current.play().catch(()=>{}))},n.oniceconnectionstatechange=()=>{if(!k.current)return;let e=n.iceConnectionState;e===`connected`||e===`completed`?(se.current=0,Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})):(e===`failed`||e===`disconnected`||e===`closed`)&&(Ie(`disconnected`),Ke())};let a=await n.createOffer();if(await n.setLocalDescription(a),await yK(n),!k.current)return;let o=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,s=await fetch(o,{method:`POST`,headers:{"Content-Type":`application/sdp`},body:n.localDescription?.sdp??``});if(!s.ok)throw Error(`WHEP ${s.status}: ${s.statusText}`);let c=await s.text();await n.setRemoteDescription({type:`answer`,sdp:c})}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}}},[e,t,Le,Ie,p]),Ue=(0,S.useCallback)(async(e=!1)=>{if(!k.current||!_)return;let n=e?re.current:null,r=e?new Set(ie.current):null;e?Re():Le(),Ie(`connecting`);let a=new AbortController;ae.current=a;let o=performance.now(),s=()=>Math.round(performance.now()-o),c={};try{let o=await v?.();if(c.iceServersMs=s(),!k.current||a.signal.aborted)return;let l=new RTCPeerConnection({iceServers:[...o??[],{urls:`stun:stun.l.google.com:19302`}]});e||(re.current=l);let d=new MediaStream,f=!1,p=()=>{if(!(f||!k.current)){if(f=!0,re.current=l,O.current&&(O.current.srcObject=d,O.current.play().catch(()=>{})),n&&n!==l)try{n.close()}catch{}if(r)for(let e of r)ie.current.delete(e),x?.(e).catch(()=>{})}};l.ontrack=t=>{if(c.firstTrackMs===void 0&&(c.firstTrackMs=s()),console.debug(`[WebRTC] ontrack (client-offer)`,t.track.kind,t.track.readyState),d.addTrack(t.track),e){p();return}O.current&&(O.current.srcObject=d,O.current.play().catch(()=>{}))};let m=!1;l.oniceconnectionstatechange=()=>{if(!k.current)return;let n=l.iceConnectionState;if(console.debug(`[WebRTC] ICE state (client-offer):`,n),n===`connected`||n===`completed`){if(!m){m=!0,c.iceConnectedMs=s(),console.info(`[WebRTC timing] client-offer connected`,{streamKey:t,...c}),u?.({...c});let e=O.current;e&&`requestVideoFrameCallback`in e&&(e.requestVideoFrameCallback(()=>{c.firstFrameMs=s(),console.info(`[WebRTC timing] first decoded frame`,{streamKey:t,firstFrameMs:c.firstFrameMs}),u?.({...c})}),setTimeout(()=>{k.current&&c.firstFrameMs===void 0&&console.warn(`[WebRTC timing] NO decoded frame (stalled)`,{streamKey:t,sinceIceConnectedMs:s()-(c.iceConnectedMs??0),iceConnectedMs:c.iceConnectedMs,firstTrackMs:c.firstTrackMs})},gK))}se.current=0,e&&p(),Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})}else if(n===`failed`||n===`disconnected`||n===`closed`){if(e&&!f)try{l.close()}catch{}Ie(`disconnected`),Ke()}};let h=null,g=[];if(l.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();h&&y?y(h,t).catch(()=>{}):g.push(t)},l.addTransceiver(`video`,{direction:`recvonly`}),l.addTransceiver(`audio`,{direction:`recvonly`}),A.current){let e=l.createDataChannel(`camstack-control`);A.current(e)}let S=await l.createOffer();if(c.offerCreatedMs=s(),await l.setLocalDescription(S),c.localSetMs=s(),!k.current||a.signal.aborted)return;let C={...fK(ne.current),...D},w=s(),{sessionId:T,sdpAnswer:E}=await _(l.localDescription?.sdp??S.sdp??``,void 0,C);if(c.signalingRttMs=s()-w,h=T,ie.current.add(T),ce.current=T,!k.current||a.signal.aborted){x?.(T).catch(()=>{}),ie.current.delete(T);return}if(y)for(let e of g)y(T,e).catch(()=>{});if(g.length=0,await l.setRemoteDescription({type:`answer`,sdp:E}),c.answerSetMs=s(),console.debug(`[WebRTC] Client-offer answer set (trickle)`,{sessionId:T.slice(0,8)}),b){let e=new Set,t=Date.now(),n=async()=>{if(!(!k.current||a.signal.aborted)&&!(l.connectionState===`closed`||l.signalingState===`closed`)){try{let{candidates:n,done:r}=await b(T);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),l.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let a=l.iceConnectionState;if(r||Date.now()-t>1e4||a===`connected`||a===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Be(T)}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}},[_,v,y,b,x,Le,Re,Ie,p,Be,D]);j.current=(0,S.useCallback)(async(e,t)=>{let n=T;if(!k.current||!n)return;let r=re.current;de.current=!0;try{let a=await v?.();if(!k.current)return;let o=new RTCPeerConnection({iceServers:[...a??[],{urls:`stun:stun.l.google.com:19302`}]}),s=new MediaStream,c=!1,l=!1,u=null,d,f,p=()=>{f!==void 0&&(clearTimeout(f),f=void 0);let e=u;if(u=null,e){d!==void 0&&typeof e.cancelVideoFrameCallback==`function`&&e.cancelVideoFrameCallback(d),e.removeEventListener(`loadeddata`,m);try{e.srcObject=null}catch{}e.remove()}};function m(){if(c||!k.current){p();return}c=!0,re.current=o,O.current&&(O.current.srcObject=s,O.current.play().catch(()=>{})),r&&r!==o&&r.close(),p()}let h=()=>{if(l||c||!k.current)return;if(l=!0,typeof document>`u`){m();return}let e=document.createElement(`video`);e.muted=!0,e.playsInline=!0,e.autoplay=!0,e.style.cssText=`position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;`,e.srcObject=s,u=e,(ne.current??document.body).appendChild(e),e.play().catch(()=>{}),typeof e.requestVideoFrameCallback==`function`&&(d=e.requestVideoFrameCallback(()=>m())),e.addEventListener(`loadeddata`,m,{once:!0}),f=setTimeout(()=>m(),1800)};o.ontrack=e=>{console.debug(`[WebRTC] ontrack (reoffer)`,e.track.kind,e.track.readyState),s.addTrack(e.track),h()},o.oniceconnectionstatechange=()=>{if(!k.current)return;let e=o.iceConnectionState;console.debug(`[WebRTC] ICE state (reoffer):`,e),e===`connected`||e===`completed`?(se.current=0,h(),Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})):(e===`failed`||e===`closed`)&&(p(),!c&&e===`failed`&&o.close(),Ie(`disconnected`),Ke())};let g=null,_=[];if(o.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();g&&y?y(g,t).catch(()=>{}):_.push(t)},o.addTransceiver(`video`,{direction:`recvonly`}),o.addTransceiver(`audio`,{direction:`recvonly`}),A.current){let e=o.createDataChannel(`camstack-control`);A.current(e)}let x=await o.createOffer();if(await o.setLocalDescription(x),!k.current){o.close();return}let S={...fK(ne.current),...D},{sessionId:C,sdpAnswer:w}=await n(e,o.localDescription?.sdp??x.sdp??``,t,S);if(!k.current){o.close();return}if(g=C,ie.current.add(C),ce.current=C,y)for(let e of _)y(C,e).catch(()=>{});if(_.length=0,await o.setRemoteDescription({type:`answer`,sdp:w}),b){let e=new Set,t=Date.now(),n=async()=>{if(k.current&&!(o.connectionState===`closed`||o.signalingState===`closed`)){try{let{candidates:n,done:r}=await b(C);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),o.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let a=o.iceConnectionState;if(r||Date.now()-t>1e4||a===`connected`||a===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Be(C)}catch(t){console.debug(`[WebRTC] reoffer failed; keeping last frame, re-arming poll`,t instanceof Error?t.message:String(t)),Be(e)}finally{de.current=!1}},[T,v,y,b,Ie,Be,D]);let We=De?Ue:Te?Ve:He,Ge=(0,S.useRef)(()=>{});Ge.current=We;let Ke=(0,S.useCallback)(()=>{if(!k.current||se.current>=hK)return;let e=se.current;se.current+=1;let t=Math.min(mK,pK*2**e),n=Math.round(t*(.8+Math.random()*.4));oe.current=setTimeout(()=>{k.current&&Ge.current()},n)},[]);(0,S.useEffect)(()=>(k.current=!0,se.current=0,r&&We(),()=>{k.current=!1,Le()}),[e,t]);let qe=(0,S.useRef)(!1);(0,S.useEffect)(()=>{if(r){if(De){if(!_)return}else if(Te){if(!h||!g)return}else return;qe.current||re.current||(qe.current=!0,We())}},[r,De,Te,_,h,g,We]);let Je=()=>{se.current=0,We()},Ye=()=>{if(se.current=0,re.current&&De){Ue(!0);return}if(re.current&&Te){Ve(!0);return}We()},Xe=(0,S.useRef)(ee);(0,S.useEffect)(()=>{Xe.current!==ee&&(Xe.current=ee,k.current&&Ye())},[ee]);let Ze=()=>{O.current&&(O.current.muted=!O.current.muted,ge(O.current.muted))},Qe=async()=>{if(ne.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(ne.current.requestFullscreen){await ne.current.requestFullscreen();return}let e=O.current;e?.webkitEnterFullscreen&&e.webkitEnterFullscreen()}catch(e){console.warn(`Fullscreen toggle failed: ${e instanceof Error?e.message:e}`)}},$e=async()=>{let e=O.current;if(e)try{if(typeof e.webkitSetPresentationMode==`function`){e.webkitSetPresentationMode(e.webkitPresentationMode===`picture-in-picture`?`inline`:`picture-in-picture`);return}document.pictureInPictureElement?await document.exitPictureInPicture():await e.requestPictureInPicture()}catch(e){console.warn(`PiP toggle failed: ${e instanceof Error?e.message:String(e)}`)}},et=()=>{if(!O.current)return;let e=document.createElement(`canvas`);e.width=O.current.videoWidth||1280,e.height=O.current.videoHeight||720;let n=e.getContext(`2d`);if(!n)return;n.drawImage(O.current,0,0);let r=document.createElement(`a`);r.download=`${t.replace(/[/:]/g,`-`)}-${Date.now()}.jpg`,r.href=e.toDataURL(`image/jpeg`,.92),r.click()};(0,S.useEffect)(()=>{let e=()=>N(!!document.fullscreenElement);document.addEventListener(`fullscreenchange`,e);let t=O.current;return t?.addEventListener(`webkitbeginfullscreen`,e),t?.addEventListener(`webkitendfullscreen`,e),()=>{document.removeEventListener(`fullscreenchange`,e),t?.removeEventListener(`webkitbeginfullscreen`,e),t?.removeEventListener(`webkitendfullscreen`,e)}},[]),(0,S.useEffect)(()=>{let e=O.current,t=typeof document<`u`&&document.pictureInPictureEnabled===!0,n=e!==null&&typeof e.webkitSetPresentationMode==`function`;ye(t||n)},[]);let[tt,nt]=(0,S.useState)(``),rt=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!s){nt(``),rt.current=null;return}let e=async()=>{let e=re.current;if(e)try{let t=await e.getStats(),n=0,r=0,a=0,o=0,s=0,c=0;t.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`?(n=t.bytesReceived??0,r=t.timestamp,a=t.framesPerSecond??0,o=t.frameWidth??0,s=t.frameHeight??0):t.type===`candidate-pair`&&t.nominated&&typeof t.currentRoundTripTime==`number`&&(c=t.currentRoundTripTime)});let l=0;rt.current&&r>rt.current.ts&&(l=Math.round((n-rt.current.bytes)*8/(r-rt.current.ts))),rt.current={bytes:n,ts:r};let u=[];o&&s&&u.push(`${o}×${s}`),a&&u.push(`${Math.round(a)}fps`),l>0&&u.push(`${l} kbps`),c&&u.push(`${Math.round(c*1e3)}ms`),nt(u.join(` · `))}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[s]);let it=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!l){it.current=null;return}let e=async()=>{let e=re.current;if(e)try{let t=await e.getStats(),n=0,r=0,a=0,o=0,s=0,c=0;t.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`?(n=t.packetsLost??0,r=t.packetsReceived??0,a=t.bytesReceived??0,o=t.timestamp,s=t.jitter??0):t.type===`candidate-pair`&&t.nominated&&typeof t.currentRoundTripTime==`number`&&(c=t.currentRoundTripTime)});let u=it.current;if(it.current={lost:n,recv:r,bytes:a,ts:o},!u||o<=u.ts)return;let d=Math.max(0,n-u.lost),f=d+Math.max(0,r-u.recv),p=f>0?Math.min(100,d/f*100):0,m=Math.max(0,Math.round((a-u.bytes)*8/(o-u.ts)));l({rttMs:Math.round(c*1e3),jitterMs:Math.round(s*1e3),estimatedBandwidthKbps:m,packetLossPercent:p})}catch{}},t=setInterval(()=>{e()},2e3);return()=>clearInterval(t)},[l]);let at=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!c){at.current=null;return}let e=async()=>{let e=re.current,t=O.current;if(e)try{let n=await e.getStats(),r=0,a=0,o=0,s=0,l=0,u=0,d=0,f=0;n.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`&&(r=t.framesReceived??0,a=t.framesDecoded??0,o=t.framesDropped??0,s=t.framesPerSecond??0,l=t.freezeCount??0,u=t.totalFreezesDuration??0,d=t.jitterBufferDelay??0,f=t.jitterBufferEmittedCount??0)});let p=t?.currentTime??0,m=Date.now(),h=at.current,g=f>0?Math.round(d/f*1e3):0;h&&c({dRecv:r-h.recv,dDec:a-h.dec,dDrop:o-h.drop,fps:Math.round(s),dFreeze:l-h.freeze,freezeTotalMs:Math.round(u*1e3),avgJitterMs:g,dCtMs:Math.round((p-h.ct)*1e3),dtMs:m-h.ts,readyState:t?.readyState??-1}),at.current={recv:r,dec:a,drop:o,freeze:l,ct:p,ts:m}}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[c]),(0,S.useEffect)(()=>{ge(a);let e=O.current;e&&(e.muted=a,a||e.play().catch(()=>{}))},[a]);let ot=()=>{be||(Se(!0),Ce.current&&clearTimeout(Ce.current),Ce.current=setTimeout(()=>Se(!1),3e3))},st=()=>{Se(e=>!e),Ce.current&&clearTimeout(Ce.current)};(0,S.useEffect)(()=>{if(M===`playing`){Fe();let e=setInterval(Fe,2e3);return()=>clearInterval(e)}Oe&&Ae.current&&Me(Ae.current)},[M,Oe,Fe]),(0,S.useEffect)(()=>{if(M!==`playing`){Pe(!1);return}let e=O.current;if(!e)return;let t=!1,n=()=>{t||Pe(!0)},r;typeof e.requestVideoFrameCallback==`function`&&(r=e.requestVideoFrameCallback(()=>n())),e.addEventListener(`loadeddata`,n,{once:!0});let a=setTimeout(n,12e3);return()=>{t=!0,clearTimeout(a),r!==void 0&&typeof e.cancelVideoFrameCallback==`function`&&e.cancelVideoFrameCallback(r),e.removeEventListener(`loadeddata`,n)}},[M]);let ct=Oe&&je?je:E??null,lt=!Ne&&ct!==null;return(0,C.jsxs)(`div`,{ref:ne,className:`relative isolate bg-black overflow-hidden group ${d}`,onMouseMove:ot,onMouseEnter:ot,onTouchStart:st,children:[(0,C.jsx)(`video`,{ref:O,autoPlay:r,muted:he,playsInline:!0,className:`w-full h-full object-contain relative z-0`}),lt&&ct&&(0,C.jsx)(`img`,{src:ct,alt:``,className:`absolute inset-0 w-full h-full object-contain z-[5] transform-gpu pointer-events-none`}),n&&M===`playing`&&(0,C.jsx)(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium`,children:n}),s&&tt&&(0,C.jsx)(`div`,{className:`absolute top-2 right-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-mono`,children:tt}),m,!ct&&M===`connecting`&&(0,C.jsxs)(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[(0,C.jsx)(`svg`,{className:`h-6 w-6 text-white/60 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:(0,C.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})}),(0,C.jsx)(`span`,{className:`text-xs text-white/60`,children:`Connecting…`})]}),!ct&&(M===`error`||M===`disconnected`)&&(0,C.jsxs)(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[(0,C.jsx)(`svg`,{className:`h-6 w-6 text-red-400`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:(0,C.jsx)(`path`,{d:`M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36`,strokeLinecap:`round`})}),(0,C.jsx)(`span`,{className:`text-xs text-red-400 text-center px-4`,children:M===`error`?pe||`Connection failed`:`Disconnected`}),(0,C.jsx)(`button`,{onClick:Je,className:`mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors`,children:`Reconnect`})]}),ct&&(M===`connecting`||M===`disconnected`)&&(0,C.jsx)(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55`,children:(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5 text-white/90 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:(0,C.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})})}),ct&&M===`error`&&(0,C.jsx)(`button`,{onClick:Je,title:pe||`Reconnect`,className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white/90 hover:bg-black/75 transition-colors`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,C.jsx)(`path`,{d:`M23 4v6h-6M1 20v-6h6`}),(0,C.jsx)(`path`,{d:`M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15`})]})}),o&&M!==`idle`&&M!==`error`&&(0,C.jsxs)(`div`,{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${be||xe?`opacity-100 pointer-events-auto`:`opacity-0 pointer-events-none`}`,children:[(0,C.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,C.jsx)(vK,{onClick:Ze,title:he?`Unmute`:`Mute`,children:he?(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`line`,{x1:`23`,y1:`9`,x2:`17`,y2:`15`}),(0,C.jsx)(`line`,{x1:`17`,y1:`9`,x2:`23`,y2:`15`})]}):(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`path`,{d:`M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07`})]})})}),(0,C.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,C.jsx)(vK,{onClick:et,title:`Take snapshot`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`path`,{d:`M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z`}),(0,C.jsx)(`circle`,{cx:`12`,cy:`13`,r:`4`})]})}),ve&&(0,C.jsx)(vK,{onClick:$e,title:`Picture-in-Picture`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,C.jsx)(`path`,{d:`M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4`}),(0,C.jsx)(`rect`,{width:`10`,height:`7`,x:`12`,y:`13`,rx:`2`})]})}),(0,C.jsx)(vK,{onClick:Qe,title:_e?`Exit fullscreen`:`Fullscreen`,children:_e?(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:(0,C.jsx)(`path`,{d:`M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3`})}):(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:(0,C.jsx)(`path`,{d:`M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3`})})})]})]})]})}function vK({onClick:e,title:t,children:n}){return(0,C.jsx)(`button`,{onClick:e,title:t,className:`rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors`,children:n})}async function yK(e){if(e.iceGatheringState!==`complete`)return new Promise(t=>{let n=!1,r,a=()=>{n||(n=!0,r&&clearInterval(r),e.removeEventListener(`icegatheringstatechange`,o),t())},o=()=>{e.iceGatheringState===`complete`&&a()};e.addEventListener(`icegatheringstatechange`,o);let s=Date.now();r=setInterval(()=>{let t=e.localDescription?.sdp??``;/ typ host/.test(t)&&Date.now()-s>=600&&a()},100),setTimeout(a,2500)})}ZM(`camstack:player-overlays-state`,null);var bK=ZM(`camstack:player-overlays-actions`,null);function xK(e){let t=(0,S.useContext)(bK);(0,S.useEffect)(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}B({id:F(),stableId:P(),addonId:P(),type:P(),name:P(),online:I(),disabled:I(),parentDeviceId:F().nullable(),role:P().nullable().optional(),features:z(P()).optional(),isCamera:I().optional(),sourceInfo:Cd.optional()}),w.AddonStarted,w.AddonInstalled,w.AddonRestarted,w.AddonUpdated,w.AddonStopped,w.AddonUninstalled,w.AddonCrashed,w.AddonError,w.DetectionPhaseTransition,w.DetectionResult,w.DetectionEvent,w.DetectionCameraNative,w.ProviderMotion,w.MotionOnMotionChanged,w.MotionAnalysis,w.MotionZonesRaw,w.ProviderDetection,w.PipelineAudioInferenceResult,w.AgentOnline,w.AgentOffline,w.DeviceRegistered,w.DeviceUnregistered,w.DeviceStateChanged,w.EventEmitted;var SK=Object.freeze([...new Set(Object.values(w))].toSorted()),CK=Object.freeze([w.PipelineCameraMetricsSnapshot,w.PipelineRunnerLoadSnapshot,w.PipelineEngineMetricsSnapshot,w.PipelineInferenceResult,w.PipelineTrace,w.PipelineProgress,w.StreamBrokerMetricsSnapshot,w.MetricsNodeResourcesSnapshot,w.MetricsNodeProcessesSnapshot,w.ClusterTopologySnapshot,w.MotionAnalysis,w.MotionZonesRaw,w.DetectionResult,w.PipelineAudioInferenceResult,w.PlatformProbePhase,w.BenchmarkProgress,w.ModelDownloadProgress]),wK=new Set(CK);Object.freeze(SK.filter(e=>!wK.has(e))),Object.freeze([...new Set(eT.filter(e=>e.scope===`device`).map(e=>e.name))].toSorted()),ZM(`camstack:zone-editing`,null);var TK=500,EK=800;function DK(e,t,n){try{let r=e.live;if(!r)return null;let a=r.onEvent;return!a||typeof a.subscribe!=`function`?null:a.subscribe({category:t},{onData:n})}catch{return null}}function OK(e,t){return e?.id===t}function kK(e,t){let[n,r]=(0,S.useState)(null),[a,o]=(0,S.useState)(null),[s,c]=(0,S.useState)(null),[l,u]=(0,S.useState)(`watching`),d=(0,S.useRef)(void 0),f=(0,S.useRef)(void 0),p=(0,S.useRef)(void 0),m=(0,S.useRef)(0);return(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.motion-analysis`,e=>{let n=e;if(!OK(n?.source,t))return;let a=n.data;!a?.regions||a.regions.length===0||(r({zones:a.regions.map(e=>({...e.bbox,intensity:e.intensity})),frameWidth:a.frameWidth,frameHeight:a.frameHeight}),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>r(null),TK))});return()=>{n?.unsubscribe(),d.current&&clearTimeout(d.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.motion-zones-raw`,e=>{let n=e;if(!OK(n?.source,t))return;let r=n.data;r?.zones&&(o({boxes:r.zones.map(e=>({bbox:e.bbox,changeScore:e.changeScore})),frameWidth:r.frameSize?.width??0,frameHeight:r.frameSize?.height??0,motionScore:r.zones.length>0?r.zones.reduce((e,t)=>e+t.changeScore,0)/r.zones.length:0}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>o(null),TK))});return()=>{n?.unsubscribe(),f.current&&clearTimeout(f.current)}},[e,t]),(0,S.useEffect)(()=>{if(m.current=0,t===null)return;let n=DK(e,`pipeline-analytics.frame-tracked`,e=>{let n=e?.data;!n||n.deviceId!==t||n.detections?.length&&typeof n.detections[0]?.kind==`string`&&(m.current=Date.now(),c({detections:n.detections,frameWidth:n.frameWidth,frameHeight:n.frameHeight}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>c(null),EK))});return()=>{n?.unsubscribe(),p.current&&clearTimeout(p.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.result`,e=>{let n=e;if(!OK(n?.source,t)||Date.now()-m.current<EK)return;let r=n.data?.frame;r?.detections?.length&&(c({detections:r.detections,frameWidth:r.width,frameHeight:r.height}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>c(null),EK))});return()=>{n?.unsubscribe(),p.current&&clearTimeout(p.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.phase-transition`,e=>{let n=e;OK(n?.source,t)&&n.data?.to&&u(n.data.to)});return()=>{n?.unsubscribe()}},[e,t]),{motion:n,motionRaw:a,detection:s,phase:l}}function AK(e,t,n=5e3){let[r,a]=(0,S.useState)([]);(0,S.useEffect)(()=>{if(t===null)return;let r=!1,o=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(e=>{r||a(e)}).catch(()=>{})};o();let s=setInterval(o,n);return()=>{r=!0,clearInterval(s)}},[e,t,n]);let[o,s]=(0,S.useState)(null);(0,S.useEffect)(()=>{if(t===null)return;let n=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(e=>{n||!e||s({phase:e.phase,detectionFps:e.actualFps,avgInferenceMs:e.avgInferenceTimeMs,droppedFrames:e.droppedFrames})}).catch(()=>{}),()=>{n=!0}},[e,t]),Mz(`pipeline.camera-metrics-snapshot`,e=>{if(t===null)return;let n=e.data;n.deviceId!==t||!n.metrics||s({phase:n.metrics.phase,detectionFps:n.metrics.actualFps,avgInferenceMs:n.metrics.avgInferenceTimeMs,droppedFrames:n.metrics.droppedFrames})});let{streams:c,hasWebrtc:l}=(0,S.useMemo)(()=>t===null||r.length===0?{streams:[],hasWebrtc:!1}:{streams:r.map(e=>({id:e.id,label:e.label,target:e.target,status:e.status,inputFps:e.inputFps,decodeFps:e.decodeFps,bitrateKbps:e.bitrateKbps})),hasWebrtc:!0},[t,r]),u=(0,S.useCallback)(async()=>{if(e.turnProvider)try{return(await e.turnProvider.getTurnServers.query()).map(e=>({urls:typeof e.urls==`string`?e.urls:[...e.urls],...e.username===void 0?{}:{username:e.username},...e.credential===void 0?{}:{credential:e.credential}}))}catch{return}},[e]),d=(0,S.useCallback)(async(n,r)=>{if(t===null)throw Error(`No device selected`);let a=await e.webrtcSession.createSession.mutate({deviceId:t,target:n,hints:r}),o=await u();return{sessionId:a.sessionId,sdpOffer:a.sdpOffer,...o?{iceServers:o}:{}}},[e,t,u]),f=(0,S.useCallback)(async(n,r,a,o)=>{if(t===null)throw Error(`No device selected`);return e.webrtcSession.handleOffer.mutate({deviceId:t,target:n,sdpOffer:r,...a===void 0?{}:{sessionId:a},...o===void 0?{}:{hints:o}})},[e,t]),p=(0,S.useCallback)(async(n,r)=>{if(t===null)throw Error(`No device selected`);await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:n,sdpAnswer:r})},[e,t]);return{streams:c,hasWebrtc:l,pipelineMetrics:o,createSession:d,handleOffer:f,getIceServers:u,addIceCandidate:(0,S.useCallback)(async(n,r)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:n,candidate:r.candidate??``,sdpMid:r.sdpMid??null,sdpMLineIndex:r.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:(0,S.useCallback)(async n=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:n}),[e,t]),sendAnswer:p,closeSession:(0,S.useCallback)(async n=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:n}).catch(()=>{})},[e,t]),getSessionState:(0,S.useCallback)(async n=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:n})}catch{return{pendingRenegotiation:null}}},[e,t])}}(0,S.lazy)(()=>fs(()=>import(`./MaskShapeCanvas-DI4BY7W2-CaRFwVIZ.js`).then(e=>({default:e.MaskShapeCanvas})),[],import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./MotionZonesSettings-NcxxQN8r-o7HcwAxC.js`).then(e=>({default:e.MotionZonesSettings})),__vite__mapDeps([0,1]),import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./PrivacyMaskSettings-APgPLF7p-B2TnFjvh.js`).then(e=>({default:e.PrivacyMaskSettings})),__vite__mapDeps([2,1]),import.meta.url));var jK=H([`auto`,`high`,`medium`,`low`]),MK=Co([U(`auto`),F().int().min(1)]),NK=B({enabled:I(),motion:I(),motionHoldSec:F().optional(),audio:H([`off`,`sensor`,`level`]),audioDb:F(),audioHoldSec:F(),detection:I(),detectionHoldSec:F(),detectionClasses:z(P()).optional(),appearance:B({motionColor:P(),audioColor:P(),detectionColor:P(),thickness:F()}).optional()}),PK=B({serverUrl:P().min(1),token:P().min(1),devices:z(F().int().nonnegative()).min(1),layout:MK,quality:jK,showName:I(),showBadges:I(),muted:I(),paused:I(),highlight:NK.optional(),activeOnly:I().optional(),showBoxes:I().optional(),audioOnIds:z(F().int().nonnegative()).optional(),pausedIds:z(F().int().nonnegative()).optional(),snapshots:V(P(),P()).optional(),ptzIds:z(F().int().nonnegative()).optional()});function FK(e){if(e==null)return{ok:!1,error:`config is required`};let t=PK.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}var IK=1e4;function LK(){try{return window.parent!==window}catch{return!0}}function RK(e){let t=window.ReactNativeWebView;if(t){t.postMessage(JSON.stringify(e));return}LK()&&window.parent.postMessage(e,`*`)}function zK(e){let t=t=>{let n=t.data;if(typeof n!=`object`||!n)return;let r=n;r.type!==`embed-command`||typeof r.command!=`object`||r.command===null||e(r.command)};return window.addEventListener(`message`,t),()=>window.removeEventListener(`message`,t)}function BK(e,t,n,r){let a=t();if(a!=null)return Promise.resolve(n(a));if(!LK()){let t=r===void 0?null:r();return t===null?Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`}):Promise.resolve(t)}return new Promise(t=>{let r,a=e=>{let o=e.data;if(typeof o!=`object`||!o)return;let s=o;s.type===`embed-config`&&(clearTimeout(r),window.removeEventListener(`message`,a),t(n(s.config)))};window.addEventListener(`message`,a),r=setTimeout(()=>{window.removeEventListener(`message`,a),t({ok:!1,error:`config handshake timed out`})},IK),window.parent.postMessage({type:`embed-ready`,mode:e},`*`)})}function VK(e,t,n,r){let[a,o]=(0,S.useState)(null),s=(0,S.useRef)(t);s.current=t;let c=(0,S.useRef)(n);c.current=n;let l=(0,S.useRef)(r);return l.current=r,(0,S.useEffect)(()=>{let t=!0;return BK(e,()=>s.current(),e=>c.current(e),()=>l.current===void 0?null:l.current()).then(e=>{t&&o(e)}),()=>{t=!1}},[e]),a}var HK=H([`auto`,`high`,`medium`,`low`]),UK=Co([U(`auto`),F().int().min(1)]),WK=B({enabled:I(),motion:I(),audio:H([`off`,`sensor`,`level`]),audioDb:F(),audioHoldSec:F(),detection:I(),detectionHoldSec:F(),detectionClasses:z(P()).optional(),appearance:B({motionColor:P(),audioColor:P(),detectionColor:P(),thickness:F()}).optional()}),GK=B({devices:z(F().int().nonnegative()).min(1),layout:UK,quality:HK,showName:I(),audioOnIds:z(F().int().nonnegative()).optional(),activeOnly:I().optional(),boxes:I().optional(),highlight:WK.optional()}),KK=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function qK(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===void 0)return null;let a,o;if(r<128)a=r,o=0;else if((r&224)==192)a=r&31,o=1;else if((r&240)==224)a=r&15,o=2;else if((r&248)==240)a=r&7,o=3;else return null;for(let t=1;t<=o;t++){let r=e[n+t];if(r===void 0||(r&192)!=128)return null;a=a<<6|r&63}n+=o+1,t+=String.fromCodePoint(a)}return t}function JK(e){if(e.length%4==1)return null;let t=[];for(let n of e){let e=KK.indexOf(n);if(e<0)return null;t.push(e)}let n=[];for(let e=0;e<t.length;e+=4){let r=t[e],a=t[e+1];if(r===void 0||a===void 0)return null;let o=t[e+2],s=t[e+3];n.push(r<<2|a>>4),o!==void 0&&n.push((a&15)<<4|o>>2),s!==void 0&&o!==void 0&&n.push((o&3)<<6|s)}let r=qK(n);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}function YK(e,t){return e.startsWith(t)?e.slice(t.length):e}function XK(e){let t=new URLSearchParams(YK(e,`#`)).get(`t`);return t!==null&&t.length>0?t:null}function ZK(e,t){return new URLSearchParams(YK(e,`?`)).has(`v`)||XK(t)!==null}function QK(e){if(e.length===0)return null;let t=[];for(let n of e.split(`,`)){if(!/^\d+$/.test(n))return null;t.push(Number(n))}return t}function $K(e){return{ok:!1,error:e}}function eq(e,t){let n=new URLSearchParams(YK(e,`?`)),r=n.get(`mode`);if(r!==null&&r!==`grid`)return $K(`unsupported mode "${r}"`);let a=n.get(`v`);if(a===null)return $K(`missing share-link version (v)`);if(a!==`1`)return $K(`unsupported share-link version "${a}"`);let o=n.get(`devices`),s=o===null?null:QK(o);if(s===null||s.length===0)return $K(`invalid or missing devices list`);let c=n.get(`layout`),l;if(c===null||c===`auto`)l=`auto`;else if(/^\d+$/.test(c)&&Number(c)>=1)l=Number(c);else return $K(`invalid layout "${c}"`);let u=n.get(`q`)??`auto`,d=HK.safeParse(u);if(!d.success)return $K(`invalid quality "${u}"`);let f=n.get(`names`)??`0`;if(f!==`0`&&f!==`1`)return $K(`invalid names flag "${f}"`);let p=n.get(`audio`),m;if(p!==null){let e=QK(p);if(e===null)return $K(`invalid audio list "${p}"`);m=e}let h=n.get(`activeOnly`);if(h!==null&&h!==`0`&&h!==`1`)return $K(`invalid activeOnly flag "${h}"`);let g=h===`1`,_=n.get(`boxes`);if(_!==null&&_!==`0`&&_!==`1`)return $K(`invalid boxes flag "${_}"`);let v=_===`1`,y=n.get(`hl`),b;if(y!==null){let e=JK(y),t=WK.safeParse(e);if(e===null||!t.success)return $K(`invalid highlight config (hl)`);b=t.data}let x={devices:[...s],layout:l,quality:d.data,showName:f===`1`,...m!==void 0&&m.length>0?{audioOnIds:[...m]}:{},...g?{activeOnly:!0}:{},...v?{boxes:!0}:{},...b===void 0?{}:{highlight:b}},S=GK.safeParse(x);return S.success?{ok:!0,params:S.data,token:XK(t)}:$K(S.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `))}function tq(e,t,n){if(!ZK(e,t))return null;let r=eq(e,t);if(!r.ok)return{ok:!1,error:r.error};if(r.token===null)return{ok:!1,error:`share token missing — the link must end with #t=<token>`};let a=r.params;return FK({serverUrl:n,token:r.token,devices:[...a.devices],layout:a.layout,quality:a.quality,showName:a.showName,showBadges:!0,muted:!0,paused:!1,...a.highlight===void 0?{}:{highlight:a.highlight},...a.activeOnly===!0?{activeOnly:!0}:{},...a.boxes===!0?{showBoxes:!0}:{},...a.audioOnIds!==void 0&&a.audioOnIds.length>0?{audioOnIds:[...a.audioOnIds]}:{}})}function nq(){let e=tq(location.search,location.hash,location.origin);return e!==null&&location.hash!==``&&history.replaceState(null,``,location.pathname+location.search),e}var rq=16/9;function iq(e,t,n,r){if(e<=0||t<=0||n<=0)return{cols:0,rows:0,cellW:0,cellH:0};if(typeof r==`number`&&r>=1){let a=Math.floor(r),o=Math.ceil(e/a),s=Math.min(t/a,n/o*rq);return{cols:a,rows:o,cellW:s,cellH:s/rq}}let a={cols:1,rows:e,cellW:0,cellH:0},o=-1;for(let r=1;r<=e;r++){let s=Math.ceil(e/r),c=Math.min(t/r,n/s*rq),l=c/rq,u=c*l;u>o&&(o=u,a={cols:r,rows:s,cellW:c,cellH:l})}return a}function aq(){let[e,t]=(0,S.useState)(null),[n,r]=(0,S.useState)(`idle`),a=(0,S.useRef)(null),o=(0,S.useRef)(null),s=(0,S.useRef)(null),c=(0,S.useRef)(0),l=(0,S.useRef)(null),u=lB(),d=uB(),f=dB(),p=(0,S.useRef)({start:u.mutateAsync,answer:d.mutateAsync,stop:f.mutateAsync});p.current={start:u.mutateAsync,answer:d.mutateAsync,stop:f.mutateAsync};let m=(0,S.useCallback)(()=>{if(a.current){try{a.current.close()}catch{}a.current=null}if(o.current){for(let e of o.current.getTracks())try{e.stop()}catch{}o.current=null}},[]),h=(0,S.useCallback)(async()=>{let e=s.current;if(s.current=null,m(),e)try{await p.current.stop({deviceId:e.deviceId,sessionId:e.sessionId})}catch{}},[m]),g=(0,S.useCallback)(async e=>{if(l.current===e){c.current+=1,l.current=null,t(null),r(`idle`),await h();return}c.current+=1;let n=c.current;l.current=e,t(e),r(`starting`);let u;try{u=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{n===c.current&&(l.current=null,t(null),r(`error`));return}if(n!==c.current){for(let e of u.getTracks())e.stop();return}if(await h(),n!==c.current){for(let e of u.getTracks())e.stop();return}let d=null;try{o.current=u;let f=await p.current.start({deviceId:e});if(n!==c.current){try{await p.current.stop({deviceId:e,sessionId:f.sessionId})}catch{}m();return}s.current={deviceId:e,sessionId:f.sessionId},d=new RTCPeerConnection,a.current=d,d.oniceconnectionstatechange=()=>{if(n!==c.current||!d)return;let e=d.iceConnectionState;e===`connected`||e===`completed`?r(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&(l.current=null,t(null),r(`idle`),h())};for(let e of u.getAudioTracks())d.addTrack(e,u);await d.setRemoteDescription({type:`offer`,sdp:f.sdpOffer});let g=await d.createAnswer();if(await d.setLocalDescription(g),n!==c.current)return;await p.current.answer({deviceId:e,sessionId:f.sessionId,sdpAnswer:d.localDescription?.sdp??g.sdp??``})}catch{if(d)try{d.close()}catch{}m();let e=s.current;if(s.current=null,e)try{await p.current.stop({deviceId:e.deviceId,sessionId:e.sessionId})}catch{}n===c.current&&(l.current=null,t(null),r(`error`))}},[h,m]),_=(0,S.useCallback)(e=>{if(e===null){c.current+=1,l.current=null,t(null),r(`idle`),h();return}l.current!==e&&g(e)},[h,g]);return(0,S.useEffect)(()=>()=>{c.current+=1,h()},[h]),{activeMicId:e,micState:n,toggleMic:e=>{g(e)},setActiveMic:_}}var oq=6e3,sq=500;function cq(e,t){let n=(0,S.useRef)(new Map),[,r]=(0,S.useState)(0),a=t?.motion??!1,o=t?.audio??`off`,s=t?.audioDb??-30,c=t?.audioHoldSec??3,l=t?.detection??!1,u=t?.detectionHoldSec??3,d=t?.detectionClasses??[],f=(e,t)=>{n.current.set(e,Date.now()+t),r(e=>e+1)};Mz(w.MotionOnMotionChanged,e=>{if(!a)return;let t=e.data;t&&t.detected&&f(t.deviceId,oq)}),Mz(w.PipelineAudioInferenceResult,e=>{if(o===`off`)return;let t=e.data;t&&(o===`sensor`?t.frame.detections.length>0:(t.frame.level?.dbfs??-1/0)>=s)&&f(t.deviceId,c*1e3)}),Mz(w.DetectionResult,e=>{if(!l)return;let t=e.data;t&&t.frame.detections.some(e=>d.length===0||d.includes(e.macroClass))&&f(t.frame.deviceId,u*1e3)}),(0,S.useEffect)(()=>{let e=setInterval(()=>r(e=>e+1),sq);return()=>clearInterval(e)},[]);let p=Date.now(),m=new Set;for(let t of e){let e=n.current.get(t);e!==void 0&&p<e&&m.add(t)}return m}function lq(e){return{type:`tileOpen`,deviceId:e}}function uq(e){return{type:`audioToggle`,deviceId:e}}function dq(e){return{type:`pauseToggle`,deviceId:e}}function fq(e){return{type:`ptzOpen`,deviceId:e}}function pq(e,t){return t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t}}function mq(e){return{type:`layout`,tiles:e}}function hq(e){RK(e)}function gq(e,t,n,r){let a=Number.isFinite(e)&&e>0?e:0,o=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0)return{width:a,height:o};let s=Math.min(a/n,o/r);return{width:n*s,height:r*s}}function _q(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?0:Math.max(0,(n*t-e)/2)}function vq(e,t,n,r){if(!Number.isFinite(e))return 0;let a=_q(t,n,r);return Math.max(-a,Math.min(a,e))}var yq=4,bq=8,xq=300;function Sq(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Cq({children:e,onTap:t}){let n=(0,S.useRef)(null),r=(0,S.useRef)(null),a=(0,S.useRef)(new Map),o=(0,S.useRef)(1),s=(0,S.useRef)(0),c=(0,S.useRef)(0),l=(0,S.useRef)(null),u=(0,S.useRef)(null),d=(0,S.useRef)(0),f=()=>{let e=r.current;e&&(e.style.transform=`translate(${s.current}px, ${c.current}px) scale(${o.current})`)},p=()=>{let e=n.current?.getBoundingClientRect();if(!e||e.width<=0||e.height<=0)return;let t=r.current?.querySelector(`video`)??null,a=t?null:r.current?.querySelector(`img`)??null,l=t?.videoWidth??a?.naturalWidth??0,u=t?.videoHeight??a?.naturalHeight??0,d=gq(e.width,e.height,l,u);s.current=vq(s.current,e.width,d.width,o.current),c.current=vq(c.current,e.height,d.height,o.current)},m=()=>{o.current=1,s.current=0,c.current=0,f()},h=e=>{try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}if(a.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),a.current.size===2){let e=[...a.current.values()],t=e[0],n=e[1];t&&n&&(l.current={dist:Sq(t,n),scale:o.current,cx:(t.x+n.x)/2,cy:(t.y+n.y)/2,tx:s.current,ty:c.current}),u.current=null}else a.current.size===1&&(u.current={x:e.clientX,y:e.clientY,tx:s.current,ty:c.current,moved:!1})},g=e=>{if(!a.current.has(e.pointerId))return;if(a.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),a.current.size>=2&&l.current){let e=[...a.current.values()],t=e[0],n=e[1];if(!t||!n)return;let r=Sq(t,n);l.current.dist>0&&(o.current=Math.max(1,Math.min(yq,l.current.scale*(r/l.current.dist))));let u=(t.x+n.x)/2,d=(t.y+n.y)/2;s.current=l.current.tx+(u-l.current.cx),c.current=l.current.ty+(d-l.current.cy),p(),f();return}let t=u.current;if(a.current.size===1&&t){let n=e.clientX-t.x,r=e.clientY-t.y;(Math.abs(n)>bq||Math.abs(r)>bq)&&(t.moved=!0),o.current>1&&(s.current=t.tx+n,c.current=t.ty+r,p(),f())}},_=e=>{let n=a.current.size===1,r=u.current;if(a.current.delete(e.pointerId),a.current.size<2&&(l.current=null),a.current.size===0&&(u.current=null,n&&r&&!r.moved)){let e=Date.now();e-d.current<xq?(d.current=0,m()):(d.current=e,t())}};return(0,C.jsx)(`div`,{ref:n,style:{position:`absolute`,inset:0,overflow:`hidden`,touchAction:`none`},onPointerDown:h,onPointerMove:g,onPointerUp:_,onPointerCancel:_,children:(0,C.jsx)(`div`,{ref:r,style:{width:`100%`,height:`100%`,transformOrigin:`center center`,willChange:`transform`},children:e})})}var wq=2500,Tq={person:`#f59e0b`,vehicle:`#3b82f6`,animal:`#22c55e`,face:`#a855f7`,plate:`#ec4899`},Eq=`#ef4444`;function Dq(e){return Tq[e]??Eq}function Oq(e){return e<0?0:e>1?1:e}function kq(e){if(e.width<=0||e.height<=0)return[];let t=[];for(let n of e.detections){let{bbox:r}=n,a=Oq(r.x/e.width),o=Oq(r.y/e.height),s=Oq((r.x+r.width)/e.width),c=Oq((r.y+r.height)/e.height);s<=a||c<=o||t.push({label:n.macroClass,score:n.score,x1:a,y1:o,x2:s,y2:c})}return t}function Aq({deviceId:e}){let[t,n]=(0,S.useState)([]),r=(0,S.useRef)(void 0);return Mz(w.DetectionResult,t=>{let a=t.data;!a||a.frame.deviceId!==e||(n(kq(a.frame)),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>n([]),wq))}),(0,S.useEffect)(()=>()=>{r.current&&clearTimeout(r.current),n([])},[e]),t.length===0?null:(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,overflow:`hidden`,pointerEvents:`none`},children:t.map((e,t)=>{let n=Dq(e.label),r=Math.round(e.score*100);return(0,C.jsx)(`div`,{style:{position:`absolute`,left:`${e.x1*100}%`,top:`${e.y1*100}%`,width:`${(e.x2-e.x1)*100}%`,height:`${(e.y2-e.y1)*100}%`,border:`2px solid ${n}`,borderRadius:3},children:(0,C.jsx)(`span`,{style:{position:`absolute`,left:-2,bottom:`100%`,background:n,color:`#fff`,fontSize:10,fontWeight:700,fontFamily:`system-ui, sans-serif`,lineHeight:`14px`,padding:`0 4px`,borderRadius:3,whiteSpace:`nowrap`},children:`${e.label} ${r}%`})},`${e.label}-${t}`)})})}var jq=500;function Mq(e,t,n){let{motion:r,detection:a}=kK(e.trpcClient,t),o=(0,S.useRef)(0),s=(0,S.useRef)(0),c=(0,S.useRef)(0),l=(0,S.useRef)(!1),[,u]=(0,S.useState)(0),d=n?.audio??`off`,f=n?.audioDb??-30,p=n?.audioHoldSec??3,m=n?.motionHoldSec??0,h=n?.detectionHoldSec??3,g=n?.detectionClasses??[],_=g.join(`,`);if(Mz(w.MotionOnMotionChanged,e=>{let r=e.data;!r||r.deviceId!==t||!n?.motion||(r.detected===!0?(c.current=Date.now()+Math.max(1,m)*1e3,l.current=!0,u(e=>e+1)):r.detected===!1&&l.current&&(c.current=Date.now()+m*1e3,l.current=!1,u(e=>e+1)))}),Mz(w.PipelineAudioInferenceResult,e=>{let n=e.data;!n||n.deviceId!==t||d===`off`||(d===`sensor`?n.frame.detections.length>0:(n.frame.level?.dbfs??-1/0)>=f)&&(o.current=Date.now()+p*1e3,u(e=>e+1))}),(0,S.useEffect)(()=>{a&&a.detections.some(e=>g.length===0||g.includes(e.macroClass))&&(s.current=Date.now()+h*1e3,u(e=>e+1))},[a,h,_]),(0,S.useEffect)(()=>{let e=r!==null;(e||l.current)&&(c.current=Date.now()+m*1e3,e||u(e=>e+1)),l.current=e},[r,m]),(0,S.useEffect)(()=>{let e=setInterval(()=>u(e=>e+1),jq);return()=>clearInterval(e)},[]),!n?.enabled)return null;let v=Date.now();return n.detection&&v<s.current?`detection`:d!==`off`&&v<o.current?`audio`:n.motion&&(r!==null||v<c.current)?`motion`:null}var Nq={motion:`#DC2626`,audio:`#3B82F6`,detection:`#22C55E`},Pq=3500;function Fq(e){return e===`auto`?{kind:`adaptive`}:{kind:`profile`,profile:e===`medium`?`mid`:e}}function Iq({system:e,deviceId:t,name:n,online:r,quality:a,muted:o,paused:s,showName:c,audioActive:l,micActive:u,onTogglePause:d,onToggleAudio:f,onToggleMic:p,onOpen:m,ptzSupported:h,onPtz:g,highlight:_,showBoxes:v,reconnectSignal:y,posterUrl:b}){let{handleOffer:x,getIceServers:w,addIceCandidate:T,getIceCandidates:E,closeSession:D,getSessionState:ee}=AK(e.trpcClient,t),te=Mq(e,t,_),[O,ne]=(0,S.useState)(void 0);(0,S.useEffect)(()=>{if(b||s)return;let n=!1;return e.trpcClient.snapshot.getSnapshot.query({deviceId:t}).then(e=>{!n&&e?.base64&&ne(`data:${e.contentType??`image/jpeg`};base64,${e.base64}`)}).catch(()=>{}),()=>{n=!0}},[b,s,e,t]);let re=b??O,ie=(0,S.useMemo)(()=>Fq(a),[a]),ae=`grid:${t}:${a}`,oe=(0,S.useMemo)(()=>(e,t)=>x(ie,e,t),[x,ie]),se=(0,S.useMemo)(()=>(e,t,n)=>x(n,t,e),[x]),[k,A]=(0,S.useState)(!1),ce=(0,S.useRef)(null),le=()=>{ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>A(!1),Pq)},ue=()=>{A(!0),le()},de=()=>{A(e=>{let t=!e;return t&&le(),t})},j=e=>{e.stopPropagation(),ue()};return(0,S.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current)},[]),(0,C.jsxs)(`div`,{style:{position:`relative`,width:`100%`,height:`100%`,background:`#000`},children:[(0,C.jsx)(Cq,{onTap:de,children:s?(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fafaf9`},children:(0,C.jsx)(zq,{size:28})}):(0,C.jsx)(_K,{serverUrl:e.serverUrl,streamKey:ae,autoPlay:!0,muted:o,showControls:!1,className:`w-full h-full`,handleOffer:oe,reoffer:se,getSessionState:ee,getIceServers:w,addIceCandidate:T,getIceCandidates:E,closeSession:D,reconnectSignal:y,posterUrl:re,onClientNetworkSample:a===`auto`?n=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...n}).catch(()=>{})}:void 0},ae)}),v&&!s?(0,C.jsx)(Aq,{deviceId:t}):null,te&&(()=>{let e=_?.appearance,t=te===`motion`?e?.motionColor??Nq.motion:te===`audio`?e?.audioColor??Nq.audio:e?.detectionColor??Nq.detection;return(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,border:`${e?.thickness??3}px solid ${t}`,boxShadow:`inset 0 0 12px ${t}`,pointerEvents:`none`}})})(),(c||k)&&(0,C.jsxs)(`div`,{style:{position:`absolute`,left:0,right:0,top:0,display:`flex`,alignItems:`center`,gap:6,padding:`4px 8px`,background:`rgba(0,0,0,0.6)`,color:`#fafaf9`,fontSize:12,fontWeight:600,fontFamily:`system-ui, sans-serif`,pointerEvents:`none`,opacity:c||k?1:0,transition:`opacity 150ms ease`},children:[(0,C.jsx)(`span`,{style:{width:8,height:8,borderRadius:4,background:r?`#34d399`:`#71717a`}}),(0,C.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:n})]}),(0,C.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!k,transition:`opacity 150ms ease`,pointerEvents:`none`},children:[(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,pointerEvents:`none`},children:(0,C.jsx)(Lq,{label:s?`Play`:`Pause`,big:!0,enabled:k,onClick:e=>{j(e),d(t)},children:s?(0,C.jsx)(zq,{size:22}):(0,C.jsx)(Bq,{size:22})})}),(0,C.jsxs)(`div`,{style:{position:`absolute`,left:8,bottom:8,display:`flex`,gap:8,pointerEvents:`none`},children:[(0,C.jsx)(Lq,{label:l?`Mute`:`Listen`,active:l,enabled:k,onClick:e=>{j(e),f(t)},children:l?(0,C.jsx)(Vq,{size:18}):(0,C.jsx)(Hq,{size:18})}),(0,C.jsx)(Lq,{label:u?`Stop talk`:`Talk`,active:u,enabled:k,onClick:e=>{j(e),p(t)},children:(0,C.jsx)(Uq,{size:18,muted:!u})}),h&&g?(0,C.jsx)(Lq,{label:`PTZ`,enabled:k,onClick:e=>{j(e),g(t)},children:(0,C.jsx)(Gq,{size:18})}):null]}),(0,C.jsx)(`div`,{style:{position:`absolute`,right:8,bottom:8,pointerEvents:`none`},children:(0,C.jsx)(Lq,{label:`Open`,enabled:k,onClick:e=>{j(e),m(t)},children:(0,C.jsx)(Wq,{size:18})})})]})]})}function Lq({children:e,label:t,onClick:n,big:r=!1,active:a=!1,enabled:o=!0}){let s=r?52:40;return(0,C.jsx)(`button`,{type:`button`,"aria-label":t,onClick:n,style:{width:s,height:s,borderRadius:s/2,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:a?`rgba(59,130,246,0.85)`:`rgba(0,0,0,0.55)`,color:`#fafaf9`,cursor:`pointer`,padding:0,WebkitTapHighlightColor:`transparent`,pointerEvents:o?`auto`:`none`},children:e})}var Rq={fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`};function zq({size:e}){return(0,C.jsx)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,children:(0,C.jsx)(`polygon`,{points:`6 4 20 12 6 20 6 4`,fill:`currentColor`})})}function Bq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,children:[(0,C.jsx)(`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,fill:`currentColor`}),(0,C.jsx)(`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,fill:`currentColor`})]})}function Vq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`path`,{d:`M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07`})]})}function Hq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`line`,{x1:`23`,y1:`9`,x2:`17`,y2:`15`}),(0,C.jsx)(`line`,{x1:`17`,y1:`9`,x2:`23`,y2:`15`})]})}function Uq({size:e,muted:t}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`path`,{d:`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`}),(0,C.jsx)(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2M12 19v4`}),t&&(0,C.jsx)(`line`,{x1:`3`,y1:`3`,x2:`21`,y2:`21`})]})}function Wq({size:e}){return(0,C.jsx)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:(0,C.jsx)(`path`,{d:`M15 3h6v6M21 3l-9 9M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5`})})}function Gq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`path`,{d:`M12 2v20M2 12h20`}),(0,C.jsx)(`path`,{d:`M12 2l-3 3M12 2l3 3M12 22l-3-3M12 22l3-3M2 12l3-3M2 12l3 3M22 12l-3-3M22 12l-3 3`})]})}function Kq({message:e}){return(0,S.useEffect)(()=>hq(pq(`error`,e)),[e]),(0,C.jsxs)(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Grid embed config error: `,e]})}function qq({system:e,config:t}){let[n,r]=(0,S.useState)(()=>new Set(t.audioOnIds??[])),a=aq(),o=(0,S.useRef)(a.setActiveMic);o.current=a.setActiveMic;let[s,c]=(0,S.useState)(()=>new Set(t.pausedIds??[])),[l,u]=(0,S.useState)(t.highlight),[d,f]=(0,S.useState)(t.activeOnly??!1),[p,m]=(0,S.useState)(t.showBoxes??!1),h=cq(t.devices,l),g=(0,S.useMemo)(()=>d?t.devices.filter(e=>h.has(e)):t.devices,[d,t.devices,h]),[_,v]=(0,S.useState)(t.quality),[y,b]=(0,S.useState)(t.layout),[x,w]=(0,S.useState)(t.showName),[T,E]=(0,S.useState)(0),[D,ee]=(0,S.useState)(()=>t.snapshots??{}),te=(0,S.useMemo)(()=>new Set(t.ptzIds??[]),[t.ptzIds]),[O,ne]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),[re,ie]=(0,S.useState)({});(0,S.useEffect)(()=>{let t=!1;return e.trpcClient.deviceManager.listAll.query({}).then(e=>{if(t)return;let n={};for(let t of e)n[t.id]={name:t.name??`Camera ${t.id}`,online:t.online??!1};ie(n)}).catch(()=>{}),()=>{t=!0}},[e]),(0,S.useEffect)(()=>(window.__camstackGrid={setAudioOn:e=>r(new Set(e)),setMutedAll:e=>{e&&r(new Set)},setActiveMic:e=>o.current(e),setHighlight:e=>u(e),setActiveOnly:e=>f(e),setShowBoxes:e=>m(e),setPaused:e=>c(new Set(e)),setQuality:e=>v(e),setLayout:e=>b(e),setShowName:w,setShowBadges:()=>{},setSnapshots:e=>ee(e),fit:(e,t)=>ne({w:e,h:t}),reconnect:()=>E(e=>e+1)},hq(pq(`ready`)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackGrid;if(t)switch(e.kind){case`setAudioOn`:t.setAudioOn(e.value);break;case`setMutedAll`:t.setMutedAll(e.value);break;case`setActiveMic`:t.setActiveMic(e.value);break;case`setHighlight`:t.setHighlight(e.value);break;case`setActiveOnly`:t.setActiveOnly(e.value);break;case`setShowBoxes`:t.setShowBoxes(e.value===!0);break;case`setPaused`:t.setPaused(e.value);break;case`setQuality`:t.setQuality(e.value);break;case`setLayout`:t.setLayout(e.value);break;case`setShowName`:t.setShowName(e.value);break;case`setShowBadges`:t.setShowBadges(e.value);break;case`setSnapshots`:t.setSnapshots(e.value);break;case`fit`:t.fit(e.w,e.h);break;case`reconnect`:t.reconnect();break;default:break}}),[]);let ae=(0,S.useMemo)(()=>iq(g.length,O.w,O.h,y),[g.length,O.w,O.h,y]),oe=(0,S.useRef)(null);return(0,S.useEffect)(()=>{let e=oe.current;if(!e)return;let t=[];e.querySelectorAll(`[data-device-id]`).forEach(e=>{let n=Number(e.dataset.deviceId),r=e.getBoundingClientRect();t.push({deviceId:n,rect:{x:r.x,y:r.y,w:r.width,h:r.height}})}),t.length&&hq(mq(t))},[ae,g]),(0,C.jsxs)(`div`,{ref:oe,style:{position:`fixed`,inset:0,background:`#000`,display:`flex`,flexWrap:`wrap`,alignItems:`center`,justifyContent:`center`},children:[d&&g.length===0&&(0,C.jsx)(`div`,{style:{color:`#a1a1aa`,fontFamily:`system-ui, sans-serif`,fontSize:14,padding:24,textAlign:`center`},children:`No active cameras`}),g.map(t=>(0,C.jsx)(`div`,{"data-device-id":t,style:{width:ae.cellW,height:ae.cellH},children:(0,C.jsx)(Iq,{system:e,deviceId:t,name:re[t]?.name??`Camera ${t}`,online:re[t]?.online??!1,quality:_,muted:!n.has(t),paused:s.has(t),showName:x,audioActive:n.has(t),micActive:a.activeMicId===t,onTogglePause:e=>hq(dq(e)),onToggleAudio:e=>hq(uq(e)),onToggleMic:a.toggleMic,onOpen:e=>hq(lq(e)),ptzSupported:te.has(t),onPtz:e=>hq(fq(e)),highlight:l,showBoxes:p,reconnectSignal:T,posterUrl:D[String(t)]})},t))]})}function Jq(){let e=VK(`grid`,()=>window.__CAMSTACK_GRID__,FK,nq),t=(0,S.useMemo)(()=>e===null||!e.ok?null:{system:XA({serverUrl:e.config.serverUrl,token:e.config.token}),queryClient:new hE({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}})},[e]);return(0,S.useEffect)(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?(0,C.jsx)(Az,{system:t.system,children:(0,C.jsx)(vE,{client:t.queryClient,children:(0,C.jsx)($.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:(0,C.jsx)(qq,{system:t.system,config:e.config})})})}):(0,C.jsx)(Kq,{message:`Failed to initialise the grid embed`}):(0,C.jsx)(Kq,{message:e.error})}var Yq=class{capacity;dispose;map=new Map;constructor(e,t){this.capacity=e,this.dispose=t}has(e){return this.map.has(e)}get(e){if(!this.map.has(e))return;let t=this.map.get(e);return this.map.delete(e),t!==void 0&&this.map.set(e,t),t}set(e,t){if(this.map.has(e)){let t=this.map.get(e);this.map.delete(e),t!==void 0&&this.dispose?.(t)}for(this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;let t=this.map.get(e);this.map.delete(e),t!==void 0&&this.dispose?.(t)}}clear(){this.map.forEach(e=>this.dispose?.(e)),this.map.clear()}};function Xq(e){try{return new URL(e).toString()}catch{let t=typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost`;return new URL(e,t).toString()}}function Zq(e,t){return new URL(t,e).toString()}function Qq(e){let t=(e.split(`/`).pop()??``).match(/^(\d+)-(\d+)(?:-\d+)?\.m4s$/);return t?{startMs:Number(t[1]),durMs:Number(t[2])}:null}function $q(e,t){let n=e.split(`
|
|
110
|
+
`;function MH({trpc:e,deviceId:t,layout:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s;if(n===`compact`)return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`span`,{className:Z(`text-xs tabular-nums font-medium`,bH[c.mode]),children:c.target===null?c.currentTemp===null?null:(0,C.jsxs)(`span`,{className:`text-foreground-subtle`,children:[c.currentTemp,`°`]}):(0,C.jsxs)(C.Fragment,{children:[c.target,`°`,c.currentTemp!==null&&(0,C.jsxs)(`span`,{className:`text-foreground-subtle font-normal`,children:[` `,`(`,c.currentTemp,`°)`]})]})}),c.target!==null&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Decrease target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target-1;l({target:e}),a.setTarget({target:e})}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`−`}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Increase target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target+1;l({target:e}),a.setTarget({target:e})}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`+`})]}),(0,C.jsx)(`select`,{"aria-label":`Mode`,value:c.mode,disabled:u,onChange:e=>{e.stopPropagation();let t=c.availableModes.find(t=>t===e.target.value);!u&&t&&(l({mode:t}),a.setMode({mode:t}))},className:Z(`bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer`,u&&`opacity-40 cursor-not-allowed`),children:c.availableModes.map(e=>(0,C.jsx)(`option`,{value:e,children:CH[e]},e))})]});let d=TH[c.mode],f=c.mode!==`off`,p=kH(c.preset),m=c.preset===`turbo`,h=Math.max(.55,AH(c.fanMode)*(m?.6:1)),g=c.swingVertical!==null,_=c.swingHorizontal!==null,v=f&&(c.swingVertical===!0||c.swingHorizontal===!0);return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:Z(`relative flex flex-col items-stretch gap-2.5 overflow-hidden rounded-lg border p-3 transition-colors`,yH[c.mode]),children:[(0,C.jsx)(`style`,{children:jH}),(0,C.jsxs)(`div`,{className:`relative z-10 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-lg border border-border/50 bg-surface/30 px-3 py-3`,children:[(0,C.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-60`,children:(0,C.jsx)(RH,{mode:c.mode,accent:d,periodSec:h,swaying:v})}),(0,C.jsx)(`div`,{className:`pointer-events-none absolute inset-0 bg-gradient-to-b from-surface/50 via-transparent to-surface/50`}),f&&(0,C.jsx)(`span`,{"aria-hidden":!0,className:`acv-glow pointer-events-none absolute left-1/2 top-1/2 h-16 w-16 -translate-x-1/2 -translate-y-1/2 rounded-full blur-2xl`,style:{background:d,animation:`acv-glow 3.2s ease-in-out infinite`}}),(0,C.jsxs)(`div`,{className:`relative z-10 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide`,style:{color:d},children:[(0,C.jsx)(PH,{mode:c.mode,className:`h-3.5 w-3.5`}),CH[c.mode],c.currentTemp!==null&&(0,C.jsxs)(`span`,{className:`normal-case text-foreground-subtle`,children:[`· `,c.currentTemp,`° now`]}),c.currentHumidity!==null&&(0,C.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 normal-case text-foreground-subtle`,children:[(0,C.jsx)(AL,{className:`h-3 w-3`}),c.currentHumidity,`%`]})]}),c.target===null?(0,C.jsxs)(`div`,{className:`relative z-10 flex items-baseline gap-0.5`,children:[(0,C.jsx)(`span`,{className:`text-4xl font-bold leading-none tabular-nums text-foreground`,children:c.currentTemp??`—`}),(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle`,children:`°`})]}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{className:`relative z-10 flex items-center gap-3`,children:[(0,C.jsx)(IH,{label:`Decrease target`,symbol:`−`,disabled:u,onClick:()=>{if(u||c.target===null)return;let e=c.target-1;l({target:e}),a.setTarget({target:e})}}),(0,C.jsxs)(`div`,{className:`flex items-baseline gap-0.5`,children:[(0,C.jsx)(`span`,{className:`text-4xl font-bold leading-none tabular-nums`,style:{color:d},children:c.target}),(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle`,children:`°`})]}),(0,C.jsx)(IH,{label:`Increase target`,symbol:`+`,disabled:u,onClick:()=>{if(u||c.target===null)return;let e=c.target+1;l({target:e}),a.setTarget({target:e})}})]}),(0,C.jsx)(`div`,{className:`relative z-10 w-36`,children:(0,C.jsx)(LH,{value:c.target,min:EH,max:DH,accent:d})})]})]}),(0,C.jsxs)(`div`,{className:`relative z-10 grid grid-cols-3 gap-2`,children:[(0,C.jsx)(FH,{label:`Mode`,icon:(0,C.jsx)(`span`,{style:{color:d},className:`flex`,children:(0,C.jsx)(PH,{mode:c.mode,className:`h-4 w-4`})}),value:c.mode,options:c.availableModes.map(e=>({value:e,label:CH[e]})),disabled:u,onChange:e=>{let t=c.availableModes.find(t=>t===e);t&&(l({mode:t}),a.setMode({mode:t}))}}),c.availableFanModes.length>0&&(0,C.jsx)(FH,{label:`Fan`,icon:(0,C.jsx)(KR,{className:`h-4 w-4 text-sky-500`}),value:c.fanMode,options:c.availableFanModes.map(e=>({value:e,label:OH(e)})),disabled:u,onChange:e=>{l({fanMode:e}),a.setFanMode({fanMode:e})}}),c.availablePresets.length>0&&(0,C.jsx)(FH,{label:`Preset`,icon:(0,C.jsx)(p,{className:`h-4 w-4 text-emerald-500`}),value:c.preset,options:c.availablePresets.map(e=>({value:e,label:OH(e)})),disabled:u,onChange:e=>{l({preset:e}),a.setPreset({preset:e})}})]}),(g||_)&&(0,C.jsx)(NH,{label:`Swing`,children:(0,C.jsxs)(`div`,{className:`grid grid-cols-2 gap-1`,children:[g&&(0,C.jsx)(BH,{axis:`vertical`,on:c.swingVertical??!1,busy:u,onToggle:e=>{l({swingVertical:e}),a.setSwingVertical({on:e})}}),_&&(0,C.jsx)(BH,{axis:`horizontal`,on:c.swingHorizontal??!1,busy:u,onToggle:e=>{l({swingHorizontal:e}),a.setSwingHorizontal({on:e})}})]})})]})}function NH({label:e,children:t}){return(0,C.jsxs)(`div`,{className:`relative z-10 flex flex-col gap-1`,children:[(0,C.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e}),t]})}function PH({mode:e,className:t}){let n=wH[e];return(0,C.jsx)(n,{className:t,"aria-hidden":!0})}function FH({label:e,icon:t,value:n,options:r,disabled:a,onChange:o}){return(0,C.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,C.jsx)(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e}),(0,C.jsxs)(`div`,{className:Z(`flex items-center gap-1 overflow-hidden rounded-lg border border-border/60 bg-surface-subtle px-1.5 py-1.5`,a&&`opacity-40`),children:[(0,C.jsx)(`span`,{className:`flex shrink-0`,children:t}),(0,C.jsx)(`select`,{"aria-label":e,value:n,disabled:a,onChange:e=>{e.stopPropagation(),a||o(e.target.value)},className:`min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent text-xs font-medium text-foreground outline-none`,children:r.map(e=>(0,C.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,C.jsx)(pL,{className:`h-3 w-3 shrink-0 text-foreground-subtle`})]})]})}function IH({label:e,symbol:t,disabled:n,onClick:r}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,disabled:n,onClick:r,className:Z(`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-surface text-lg leading-none text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground active:scale-95`,n&&`opacity-40 cursor-not-allowed`),children:t})}function LH({value:e,min:t,max:n,accent:r}){let a=`${Math.min(1,Math.max(0,(e-t)/(n-t)))*100}%`;return(0,C.jsxs)(`div`,{className:`mt-2 w-full`,children:[(0,C.jsxs)(`div`,{className:`relative h-1.5 w-full rounded-full bg-surface-subtle`,children:[(0,C.jsx)(`div`,{className:`absolute inset-y-0 left-0 rounded-full`,style:{width:a,background:r}}),(0,C.jsx)(`div`,{className:`absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface shadow`,style:{left:a,background:r}})]}),(0,C.jsxs)(`div`,{className:`mt-0.5 flex justify-between text-[9px] tabular-nums text-foreground-subtle`,children:[(0,C.jsxs)(`span`,{children:[t,`°`]}),(0,C.jsxs)(`span`,{children:[n,`°`]})]})]})}function RH({mode:e,accent:t,periodSec:n,swaying:r}){let a=[0,1,2,3,4,5],o=e===`heat`,s=e===`dry`;return(0,C.jsx)(`div`,{"aria-hidden":!0,className:`absolute inset-0 overflow-hidden`,children:e===`off`?(0,C.jsx)(`div`,{className:`flex h-full items-center justify-center gap-2 opacity-30`,children:a.map(e=>(0,C.jsx)(`span`,{className:`h-8 w-1 rounded-full bg-foreground-subtle opacity-40`},e))}):e===`fan_only`?(0,C.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,C.jsx)(zH,{color:t,periodSec:Math.max(.5,n*.7),size:56})}):(0,C.jsx)(`div`,{className:Z(`acv-sway-wrap absolute inset-0`,r&&`acv-sway`),style:r?{animation:`acv-sway 2.6s ease-in-out infinite`}:void 0,children:a.map(e=>(0,C.jsx)(`span`,{className:`acv-streak absolute rounded-full`,style:{left:`${8+e*15}%`,width:s?`0.4rem`:`0.3rem`,height:s?`0.4rem`:`1.9rem`,background:t,boxShadow:`0 0 6px ${t}`,animationName:o?`acv-rise`:`acv-fall`,animationTimingFunction:`linear`,animationIterationCount:`infinite`,animationDuration:`${n}s`,animationDelay:`${e%3*(n/3)+e*.05}s`}},e))})})}function zH({color:e,periodSec:t,size:n}){return(0,C.jsxs)(`svg`,{width:n,height:n,viewBox:`0 0 100 100`,className:`acv-fan`,style:{animation:`acv-spin ${t}s linear infinite`,transformOrigin:`50% 50%`},"aria-hidden":!0,children:[[0,120,240].map(t=>(0,C.jsx)(`path`,{d:`M50 50 C 58 30, 78 26, 84 12 C 66 20, 54 34, 50 50 Z`,fill:e,opacity:.85,transform:`rotate(${t} 50 50)`},t)),(0,C.jsx)(`circle`,{cx:`50`,cy:`50`,r:`7`,fill:e})]})}function BH({axis:e,on:t,busy:n,onToggle:r}){let a=e===`vertical`?`Vertical`:`Horizontal`,o=e===`vertical`?iR:rR,s=e===`vertical`?`acv-swing-v`:`acv-swing-h`;return(0,C.jsxs)(`button`,{type:`button`,"aria-label":`${a} swing`,"aria-pressed":t,disabled:n,onClick:()=>{n||r(!t)},className:Z(`flex items-center justify-center gap-2 rounded-lg border px-2 py-1.5 text-xs font-medium transition-colors`,t?`border-transparent bg-indigo-400 text-indigo-950 shadow-sm`:`border-border/60 bg-surface-subtle text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,n&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(o,{className:`acv-swing h-4 w-4`,"aria-hidden":!0,style:t?{animation:`${s} 1.4s ease-in-out infinite`}:void 0}),a]})}var VH={playing:`border-green-400 bg-green-50 dark:bg-green-950`,paused:`border-amber-400 bg-amber-50 dark:bg-amber-950`,buffering:`border-blue-400 bg-blue-50 dark:bg-blue-950`,on:`border-slate-400 bg-slate-50 dark:bg-slate-950`,idle:`border-slate-400 bg-slate-50 dark:bg-slate-950`,off:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`,standby:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`},HH={playing:`bg-green-500`,paused:`bg-amber-400`,buffering:`bg-blue-400`,on:`bg-slate-400`,idle:`bg-slate-400`,off:`bg-zinc-300`,standby:`bg-zinc-300`},UH=[`off`,`all`,`one`];function WH(e){return UH.includes(e)}var GH={off:`Off`,all:`All`,one:`One`};function KH(e){return e===`playing`||e===`buffering`?`pause`:`play`}function qH({trpc:e,deviceId:t,features:n,layout:r,optimistic:a}){let{cap:o,slice:s,available:c}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:l,applyOptimistic:u}=Yz(s,{enabled:a??!0});if(l===void 0)return null;let d=!c,f=KH(l.state);return(0,C.jsxs)(`div`,{"data-state":l.state,className:Z(`inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors`,VH[l.state],r===`full`&&`flex-col items-stretch gap-3`),children:[(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(`span`,{role:`status`,"aria-label":l.state,className:Z(`inline-block h-2 w-2 rounded-full flex-shrink-0`,HH[l.state])}),(0,C.jsx)(`button`,{type:`button`,"aria-label":f===`play`?`Play`:`Pause`,disabled:d,onClick:e=>{e.stopPropagation(),!d&&(f===`play`?(u({state:`playing`}),o?.play({})):(u({state:`paused`}),o?.pause({})))},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:f===`play`?`▶`:`⏸`})]}),r===`full`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Previous`,disabled:d,onClick:e=>{e.stopPropagation(),d||o?.previous({})},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:`⏮`}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Next`,disabled:d,onClick:e=>{e.stopPropagation(),d||o?.next({})},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,d&&`opacity-40 cursor-not-allowed`),children:`⏭`})]}),l.volumeLevel!==null&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Vol`}),(0,C.jsx)(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,value:l.volumeLevel,disabled:d,onChange:e=>{let t=Number(e.target.value);u({volumeLevel:t}),d||o?.setVolume({volumeLevel:t})}}),(0,C.jsxs)(`span`,{className:`tabular-nums w-8 text-right`,children:[l.volumeLevel,`%`]})]}),l.isMuted!==null&&(0,C.jsx)(`button`,{type:`button`,"aria-label":l.isMuted?`Unmute`:`Mute`,disabled:d,onClick:e=>{if(e.stopPropagation(),!d&&l.isMuted!==null){let e=!l.isMuted;u({isMuted:e}),o?.setMute({muted:e})}},className:Z(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,l.isMuted?`bg-amber-400 text-amber-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,d&&`opacity-40 cursor-not-allowed`),children:l.isMuted?`🔇`:`🔊`}),l.availableSources.length>0&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Source`}),(0,C.jsxs)(`select`,{"aria-label":`Source`,value:l.source,disabled:d,onChange:e=>{let t=e.target.value;!d&&t&&(u({source:t}),o?.selectSource({source:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:[(0,C.jsx)(`option`,{value:``,disabled:!0,children:`—`}),l.availableSources.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))]})]}),l.shuffle!==null&&(0,C.jsx)(`button`,{type:`button`,"aria-label":`Shuffle`,disabled:d,onClick:e=>{if(e.stopPropagation(),!d&&l.shuffle!==null){let e=!l.shuffle;u({shuffle:e}),o?.setShuffle({shuffle:e})}},className:Z(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,l.shuffle?`bg-green-400 text-green-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,d&&`opacity-40 cursor-not-allowed`),children:`⇌ Shuffle`}),l.repeat!==null&&(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Repeat`}),(0,C.jsx)(`select`,{"aria-label":`Repeat`,value:l.repeat,disabled:d,onChange:e=>{let t=e.target.value;!d&&WH(t)&&(u({repeat:t}),o?.setRepeat({repeat:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:UH.map(e=>(0,C.jsx)(`option`,{value:e,children:GH[e]},e))})]})]})]})}function JH(e){return e.slice(0,10)}function YH(e){return e.slice(0,5)}function XH(e){return(e.includes(`T`)?e:e.replace(` `,`T`)).slice(0,16)}function ZH({value:e,busy:t,onCommit:n,unit:r,min:a,max:o,step:s,precision:c}){let[l,u]=(0,S.useState)(GM(e,c)),d=Number(l),f=l!==``&&!Number.isNaN(d),p=s??1,m=e=>{let t=e;return a!==void 0&&(t=Math.max(a,t)),o!==void 0&&(t=Math.min(o,t)),t},h=()=>{!t&&f&&n(m(d))};return(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-1`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Decrement`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=m(e-p);u(GM(t,c)),n(t)}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`−`}),(0,C.jsx)(`input`,{"aria-label":`Numeric value`,type:`number`,disabled:t,value:l,onChange:e=>{u(e.target.value);let r=Number(e.target.value);e.target.value!==``&&!Number.isNaN(r)&&(t||n(m(r)))},onBlur:h,onKeyDown:e=>{e.key===`Enter`&&h()},className:Z(`w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center`,t&&`opacity-40 cursor-not-allowed`)}),r!==void 0&&(0,C.jsx)(`span`,{className:`text-foreground-subtle text-xs`,children:r}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Increment`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=m(e+p);u(GM(t,c)),n(t)}},className:Z(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`+`})]})}function QH({value:e,busy:t,onCommit:n}){let[r,a]=(0,S.useState)(e);return(0,C.jsx)(`input`,{type:`text`,disabled:t,value:r,onChange:e=>a(e.target.value),onBlur:()=>{t||n(r)},onKeyDown:e=>{e.key===`Enter`&&!t&&n(r)},className:Z(`rounded border border-border bg-surface px-2 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}function $H({slice:e,busy:t,setValueFn:n,layout:r}){switch(e.kind){case`numeric`:return(0,C.jsx)(ZH,{value:typeof e.value==`number`?e.value:Number(e.value),busy:t,onCommit:e=>{n({control:{kind:`numeric`,value:e}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case`select`:return(0,C.jsx)(`select`,{"aria-label":`Control value`,disabled:t,value:String(e.value),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`select`,value:e.target.value}})},className:Z(`w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`),children:e.options.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))});case`text`:return(0,C.jsx)(QH,{value:String(e.value),busy:t,onCommit:e=>{n({control:{kind:`text`,value:e}})}});case`datetime`:{let a=String(e.value),o=e.format??`datetime`;return r===`compact`?a===``?(0,C.jsx)(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground-subtle`,children:`—`}):(0,C.jsx)(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground`,children:WM(a,o)}):(0,C.jsx)(`input`,{type:o===`date`?`date`:o===`time`?`time`:`datetime-local`,"aria-label":`Control value`,disabled:t,value:o===`date`?JH(a):o===`time`?YH(a):XH(a),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`datetime`,value:e.target.value}})},className:Z(`rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}default:return null}}function eU({trpc:e,deviceId:t,features:n,layout:r,optimistic:a}){let{cap:o,slice:s,available:c}=Iz({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control}),{display:l,applyOptimistic:u}=Yz(s,{enabled:a??!0});if(l===void 0)return null;let d=!c;return(0,C.jsx)(`div`,{"data-kind":l.kind,className:`inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors`,children:(0,C.jsx)($H,{slice:l,busy:d,setValueFn:e=>{!d&&o&&(u({value:e.control.value}),o.setValue(e))},layout:r})})}var tU=5,nU=35;function rU(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function iU(e,t,n){return Math.round(t+e*(n-t))}var aU=176,oU=76,sU=2*Math.PI*oU,cU=270/360*sU,lU=aU/2-oU-10;function uU(e){let t=aU/2,n=aU/2,r=sU-cU,a=e.mode===`band`?(()=>{let t=e.band.from*cU,n=Math.max(0,(e.band.to-e.band.from)*cU);return{dasharray:`${n} ${sU-n}`,dashoffset:-t}})():(()=>{let t=e.fraction*cU;return{dasharray:`${t} ${sU-t}`,dashoffset:void 0}})();return(0,C.jsxs)(`svg`,{width:aU,height:aU,viewBox:`0 0 ${aU} ${aU}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[(0,C.jsx)(`circle`,{cx:t,cy:n,r:oU,fill:`none`,stroke:`var(--color-border)`,strokeWidth:12,strokeDasharray:`${cU} ${r}`,strokeLinecap:`round`}),(0,C.jsx)(`circle`,{cx:t,cy:n,r:oU,fill:`none`,stroke:e.color,strokeWidth:12,strokeDasharray:a.dasharray,...a.dashoffset===void 0?{}:{strokeDashoffset:a.dashoffset},strokeLinecap:`round`})]})}var dU={heat:`#f59e0b`,cool:`#60a5fa`,auto:`#c084fc`,heat_cool:`#e879f9`,fan_only:`#94a3b8`,dry:`#22d3ee`,off:`#d4d4d8`};function fU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s,d=dU[c.mode],f=c.mode===`heat_cool`||c.targetLow!==null&&c.targetHigh!==null,p=tU,m=nU,h=!f&&c.target!==null?rU(c.target,p,m):0,g=f&&c.targetLow!==null?rU(c.targetLow,p,m):0,_=f&&c.targetHigh!==null?rU(c.targetHigh,p,m):0;return(0,C.jsxs)(`div`,{"data-mode":c.mode,className:Z(`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors`,yH[c.mode]),children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,C.jsxs)(`div`,{className:`relative`,style:{width:aU,height:aU},children:[f?(0,C.jsx)(uU,{mode:`band`,band:{from:g,to:_},color:d}):(0,C.jsx)(uU,{mode:`fill`,fraction:h,color:d}),f?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:g,color:d,knobTopPx:lU,onDragFraction:e=>{if(u||c.targetHigh===null)return;let t=Math.min(iU(e,p,m),c.targetHigh);l({targetLow:t}),a.setTargetRange({targetLow:t,targetHigh:c.targetHigh})}})}),(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:_,color:d,knobTopPx:lU,onDragFraction:e=>{if(u||c.targetLow===null)return;let t=Math.max(iU(e,p,m),c.targetLow);l({targetHigh:t}),a.setTargetRange({targetLow:c.targetLow,targetHigh:t})}})})]}):(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:h,color:d,knobTopPx:lU,onDragFraction:e=>{if(u)return;let t=iU(e,p,m);l({target:t}),a.setTarget({target:t})}})}),(0,C.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:[(0,C.jsxs)(`div`,{"data-testid":`current-temp`,className:`text-4xl font-bold tabular-nums text-foreground leading-none`,children:[c.currentTemp===null?`—`:c.currentTemp,(0,C.jsx)(`span`,{className:`text-lg text-foreground-subtle font-normal ml-0.5`,children:`°`})]}),!f&&c.target!==null&&(0,C.jsxs)(`div`,{className:`text-xs font-semibold`,style:{color:d},children:[`set `,c.target,`°`]}),f&&c.targetLow!==null&&c.targetHigh!==null&&(0,C.jsxs)(`div`,{className:`text-xs font-semibold`,style:{color:d},children:[c.targetLow,`° – `,c.targetHigh,`°`]})]})]}),!f&&c.target!==null&&(0,C.jsx)(`div`,{className:`w-[200px]`,children:(0,C.jsx)(Lz,{value:`${c.target}°`,onDelta:e=>{if(u||c.target===null)return;let t=c.target+e;l({target:t}),a.setTarget({target:t})}})})]}),(0,C.jsx)(`select`,{"aria-label":`Mode`,value:c.mode,disabled:u,onChange:e=>{e.stopPropagation();let t=e.target.value;!u&&t&&(l({mode:c.availableModes.find(e=>e===t)??c.mode}),a.setMode({mode:c.availableModes.find(e=>e===t)??c.mode}))},className:Z(`w-full rounded border border-border bg-surface px-3 py-1.5 text-sm`,u&&`opacity-40 cursor-not-allowed`),children:c.availableModes.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))})]})}function pU(e){return e===`locked`||e===`locking`}function mU(e){return e===`jammed`}var hU={locked:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},locking:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},unlocked:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},unlocking:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},jammed:{colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`locked`}};function gU({state:e}){let t=hU[e];return(0,C.jsx)(`div`,{"data-testid":`lock-glyph`,"data-state":e,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2`,t.colorClass),children:t.icon===`locked`?(0,C.jsx)(YL,{className:`h-8 w-8`,"aria-hidden":`true`}):(0,C.jsx)(JL,{className:`h-8 w-8`,"aria-hidden":`true`})})}function _U({state:e}){return(0,C.jsx)(`span`,{className:Z(`text-sm font-medium capitalize`,mU(e)?`text-danger`:`text-foreground-muted`),children:e})}function vU({busy:e,onOpen:t}){return(0,C.jsxs)(`button`,{type:`button`,"aria-label":`Open (unlatch)`,title:`Open (unlatch)`,disabled:e,onClick:e=>{e.stopPropagation(),t()},className:Z(`inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium`,`text-foreground-muted hover:bg-surface-hover transition-colors`,e&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(DL,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Open`]})}function yU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=pU(c.state),d=mU(c.state)||!s,f=n?.includes(js.LockOpen)===!0,p=()=>{d||(u?(l({state:`unlocking`}),a.unlock({})):(l({state:`locking`}),a.lock({})))},m=()=>{d||a.open({})},h=u?`Unlock`:`Lock`;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,C.jsx)(gU,{state:c.state}),(0,C.jsx)(_U,{state:c.state})]}),(0,C.jsx)(`div`,{className:Z(d&&`pointer-events-none opacity-40`),children:(0,C.jsx)(Rz,{on:u,targetLabel:h,onConfirm:p})}),f&&(0,C.jsx)(`div`,{className:`flex justify-center`,children:(0,C.jsx)(vU,{busy:d,onOpen:m})})]})}var bU=150,xU=64,SU=bU/2,CU=2*Math.PI*xU,wU=270/360*CU;function TU({fraction:e,color:t,children:n,onDragFraction:r}){let a=Math.min(1,Math.max(0,e)),o=bU/2,s=bU/2,c=CU-wU,l=a*wU;return(0,C.jsxs)(`div`,{className:`relative`,style:{width:bU,height:bU},children:[(0,C.jsxs)(`svg`,{width:bU,height:bU,viewBox:`0 0 ${bU} ${bU}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[(0,C.jsx)(`circle`,{cx:o,cy:s,r:xU,fill:`none`,stroke:`var(--color-border)`,strokeWidth:11,strokeDasharray:`${wU} ${c}`,strokeLinecap:`round`}),(0,C.jsx)(`circle`,{cx:o,cy:s,r:xU,fill:`none`,stroke:t,strokeWidth:11,strokeDasharray:`${l} ${CU-l}`,strokeLinecap:`round`})]}),(0,C.jsx)(`div`,{"data-testid":`arc-knob`,children:(0,C.jsx)(Uz,{fraction:a,color:t,knobTopPx:SU-xU-10,...r===void 0?{}:{onDragFraction:r}})}),(0,C.jsx)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:n})]})}function EU({on:e,busy:t,onToggle:n}){let r={transform:e?`translateX(30px)`:`translateX(3px)`};return(0,C.jsx)(`button`,{type:`button`,"aria-pressed":e,title:e?`Turn off`:`Turn on`,disabled:t,onClick:e=>{e.stopPropagation(),n()},className:Z(`relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0`,e?`bg-success/30 border-success/50`:`bg-surface-hover border-border`,t&&`opacity-60 cursor-not-allowed`),children:(0,C.jsx)(`span`,{className:Z(`absolute h-6 w-6 rounded-full transition-all`,e?`bg-success`:`bg-foreground-subtle`),style:r})})}var DU=500,OU=150,kU=`linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)`;function AU(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function jU(e){return AU(e,OU,DU)}var MU=`#f4b740`,NU=`#d4d4d8`;function PU({trpc:e,deviceId:t,features:n,optimistic:r}){let a=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),o=Iz({trpc:e,deviceId:t,cap:e=>e.brightness,slice:e=>e.state.brightness}),s=Iz({trpc:e,deviceId:t,cap:e=>e.color,slice:e=>e.state.color}),c=Yz(a.slice,{enabled:r??!0}),l=Yz(o.slice,{enabled:r??!0}),u=Yz(s.slice,{enabled:r??!0});if(a.cap===void 0||c.display===void 0)return null;let d=c.display.on===!0,f=!a.available,p=l.display?.percentage??0,m=!o.available,h=d?p/100:0,g=d?MU:NU,_=(n?.includes(js.LightColorMired)??!1)&&s.cap!==void 0,v=u.display?.mireds,y=!s.available;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,C.jsxs)(TU,{fraction:h,color:g,children:[(0,C.jsxs)(`div`,{"data-testid":`brightness-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[p,(0,C.jsx)(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),(0,C.jsx)(WL,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}),o.cap!==void 0&&(0,C.jsxs)(`label`,{className:`flex w-full items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{className:`w-16`,children:`Brightness`}),(0,C.jsx)(`input`,{"aria-label":`Brightness`,type:`range`,min:0,max:100,step:1,className:`flex-1`,value:p,disabled:m||!d,onChange:e=>{let t=Number(e.target.value);l.applyOptimistic({percentage:t}),m||o.cap?.setBrightness({percentage:t})}}),(0,C.jsxs)(`span`,{className:`tabular-nums w-9 text-right`,children:[p,`%`]})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:d?`On`:`Off`}),(0,C.jsx)(EU,{on:d,busy:f,onToggle:()=>{if(f)return;let e=!d;c.applyOptimistic({on:e}),a.cap?.setState({on:e})}})]}),_&&(0,C.jsxs)(`div`,{className:`flex items-center gap-2`,"data-testid":`color-temp-strip`,children:[(0,C.jsx)(NR,{className:`h-4 w-4 text-foreground-subtle`,"aria-hidden":`true`}),(0,C.jsxs)(`label`,{className:`flex-1`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Colour temperature`}),(0,C.jsx)(`input`,{"aria-label":`Colour temperature`,type:`range`,min:OU,max:DU,step:1,className:`w-full`,value:v??DU,disabled:y||!d,onChange:e=>{let t=Number(e.target.value);u.applyOptimistic({mode:`mired`,mireds:t}),y||s.cap?.setColor({color:{mode:`mired`,mireds:t}})}}),(0,C.jsx)(`div`,{className:`pointer-events-none mt-1`,children:(0,C.jsx)(Wz,{fraction:v===void 0?.5:jU(v),color:kU})})]})]})]})}var FU=`#3aa6a0`,IU=`#d4d4d8`;function LU({trpc:e,deviceId:t,features:n,optimistic:r}){let a=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),o=Iz({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl}),s=Yz(a.slice,{enabled:r??!0}),c=Yz(o.slice,{enabled:r??!0});if(a.cap===void 0||s.display===void 0)return null;let l=s.display.on===!0,u=!a.available,d=c.display?.percentage??0,f=!o.available,p=l?d/100:0,m=l?FU:IU,h=n?.includes(js.FanSpeed)??!1,g=(n?.includes(js.FanOscillating)??!1)&&o.cap!==void 0,_=c.display?.availablePresets??[],v=(n?.includes(js.FanPreset)??!1)&&o.cap!==void 0&&_.length>0,y=c.display?.preset??``,b=c.display?.oscillating===!0,x=()=>{if(u)return;let e=!l;s.applyOptimistic({on:e}),a.cap?.setState({on:e})},S=()=>{if(f)return;let e=!b;c.applyOptimistic({oscillating:e}),o.cap?.setOscillating({oscillating:e})},w=e=>{if(f)return;let t=c.display;if(t===void 0)return;let n=t.percentageStep!==void 0&&t.percentageStep>0?t.percentageStep:1,r=Math.min(100,Math.max(0,Math.round(e*100/n)*n));c.applyOptimistic({percentage:r}),o.cap?.setPercentage({percentage:r})},T=e=>{f||e===``||(c.applyOptimistic({preset:e}),o.cap?.setPreset({preset:e}))};return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[(0,C.jsx)(`div`,{className:`flex flex-col items-center gap-3`,children:h?(0,C.jsxs)(TU,{fraction:p,color:m,onDragFraction:w,children:[(0,C.jsxs)(`div`,{"data-testid":`speed-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[d,(0,C.jsx)(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),(0,C.jsx)(ML,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}):(0,C.jsx)(`div`,{"data-testid":`fan-onoff-icon`,className:`flex h-[150px] w-[150px] items-center justify-center`,children:(0,C.jsx)(ML,{className:`h-16 w-16`,style:{color:m},"aria-hidden":`true`})})}),v&&(0,C.jsx)(`div`,{className:`flex justify-center`,children:(0,C.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:`Preset`}),(0,C.jsxs)(`select`,{"aria-label":`Fan preset`,value:y,disabled:f,onChange:e=>{e.stopPropagation(),T(e.target.value)},className:Z(`bg-surface border border-border rounded px-1 py-0.5`,f&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(`option`,{value:``,disabled:!0,children:`—`}),_.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))]})]})}),(0,C.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[g?(0,C.jsxs)(`button`,{type:`button`,"aria-label":`Oscillate`,"aria-pressed":b,disabled:f,onClick:e=>{e.stopPropagation(),S()},className:Z(`inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors`,b?`border-success/50 bg-success/10 text-success`:`border-border text-foreground-muted hover:bg-surface-hover`,f&&`opacity-40 cursor-not-allowed`),children:[(0,C.jsx)(mR,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Oscillate`]}):(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l?`On`:`Off`}),(0,C.jsx)(EU,{on:l,busy:u,onToggle:x})]})]})}function RU({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:a,available:o}=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),{display:s,applyOptimistic:c}=Yz(a,{enabled:n??!0});if(r===void 0||s===void 0)return null;let l=s.on===!0,u=!o;return(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsx)(`div`,{"data-testid":`switch-glyph`,"data-state":l?`on`:`off`,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors`,l?`border-success/30 bg-success/10 text-success`:`border-border bg-surface-subtle text-foreground-subtle`),children:(0,C.jsx)(fR,{className:`h-8 w-8`,"aria-hidden":`true`})}),(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l?`On`:`Off`}),(0,C.jsx)(EU,{on:l,busy:u,onToggle:()=>{if(u)return;let e=!l;c({on:e}),r.setState({on:e})}})]})}function zU(e){return e===`playing`||e===`buffering`?`pause`:`play`}function BU(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function VU(e){if(e===null)return`--:--`;let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}function HU({title:e,subtitle:t}){return(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,C.jsx)(aR,{className:`h-6 w-6 text-foreground-subtle`,"aria-hidden":`true`}),(0,C.jsx)(`span`,{className:`text-base font-semibold text-foreground line-clamp-1`,children:e??`Nothing playing`}),t&&(0,C.jsx)(`span`,{className:`text-xs text-foreground-subtle line-clamp-1`,children:t})]})}function UU({label:e,busy:t,onPress:n,children:r,primary:a}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),t||n()},className:Z(`inline-flex items-center justify-center rounded-full transition-colors`,a?`h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md`:`h-10 w-10 text-foreground-muted hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:r})}function WU({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:a,slice:o,available:s}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:c,applyOptimistic:l}=Yz(o,{enabled:r??!0});if(a===void 0||c===void 0)return null;let u=!s,d=zU(c.state),f=(n?.includes(js.MediaPlayerSeek)??!1)&&c.durationMs!==null&&c.durationMs>0,p=n?.includes(js.MediaPlayerNext)??!1,m=n?.includes(js.MediaPlayerPrevious)??!1,h=(n?.includes(js.MediaPlayerVolume)??!1)&&c.volumeLevel!==null,g=()=>{u||(d===`play`?(l({state:`playing`}),a.play({})):(l({state:`paused`}),a.pause({})))},_=c.currentMedia?.artist??c.currentMedia?.album??null,v=BU(c.positionMs,c.durationMs),y=c.volumeLevel??0;return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsx)(HU,{title:c.currentMedia?.title??null,subtitle:_}),f&&(0,C.jsxs)(`div`,{"data-testid":`media-seek`,className:`flex flex-col gap-1`,children:[(0,C.jsxs)(`label`,{className:`relative block`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Seek`}),(0,C.jsx)(`input`,{"aria-label":`Seek`,type:`range`,min:0,max:c.durationMs??0,step:1e3,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:c.positionMs??0,disabled:u,onChange:e=>{if(u)return;let t=Number(e.target.value);l({positionMs:t}),a.seek({positionMs:t})}}),(0,C.jsx)(`div`,{className:`pointer-events-none`,children:(0,C.jsx)(Wz,{fraction:v})})]}),(0,C.jsxs)(`div`,{className:`flex justify-between text-[11px] tabular-nums text-foreground-subtle`,children:[(0,C.jsx)(`span`,{children:VU(c.positionMs)}),(0,C.jsx)(`span`,{children:VU(c.durationMs)})]})]}),(0,C.jsxs)(`div`,{className:`flex items-center justify-center gap-4`,children:[m&&(0,C.jsx)(UU,{label:`Previous`,busy:u,onPress:()=>void a.previous({}),children:(0,C.jsx)(SR,{className:`h-5 w-5`,"aria-hidden":`true`})}),(0,C.jsx)(UU,{label:d===`play`?`Play`:`Pause`,busy:u,onPress:g,primary:!0,children:d===`play`?(0,C.jsx)(dR,{className:`h-6 w-6`,"aria-hidden":`true`}):(0,C.jsx)(cR,{className:`h-6 w-6`,"aria-hidden":`true`})}),p&&(0,C.jsx)(UU,{label:`Next`,busy:u,onPress:()=>void a.next({}),children:(0,C.jsx)(CR,{className:`h-5 w-5`,"aria-hidden":`true`})})]}),h&&(0,C.jsxs)(`div`,{"data-testid":`media-volume`,className:`flex items-center gap-2`,children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":c.isMuted===!0?`Unmute`:`Mute`,title:c.isMuted===!0?`Unmute`:`Mute`,disabled:u,onClick:e=>{if(e.stopPropagation(),u||c.isMuted===null)return;let t=!c.isMuted;l({isMuted:t}),a.setMute({muted:t})},className:Z(`inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,u&&`opacity-40 cursor-not-allowed`),children:c.isMuted===!0?(0,C.jsx)(HR,{className:`h-4 w-4`,"aria-hidden":`true`}):(0,C.jsx)(VR,{className:`h-4 w-4`,"aria-hidden":`true`})}),(0,C.jsxs)(`label`,{className:`relative block flex-1`,children:[(0,C.jsx)(`span`,{className:`sr-only`,children:`Volume`}),(0,C.jsx)(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:y,disabled:u,onChange:e=>{if(u)return;let t=Number(e.target.value);l({volumeLevel:t}),a.setVolume({volumeLevel:t})}}),(0,C.jsx)(`div`,{className:`pointer-events-none`,children:(0,C.jsx)(Wz,{fraction:y/100})})]}),(0,C.jsxs)(`span`,{className:`w-9 text-right text-[11px] tabular-nums text-foreground-subtle`,children:[y,`%`]})]})]})}var GU={disarmed:{label:`Disarmed`,colorClass:`border-border bg-surface-subtle text-foreground-subtle`,icon:`disarmed`},armed_home:{label:`Armed Home`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_away:{label:`Armed Away`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_night:{label:`Armed Night`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_vacation:{label:`Armed Vacation`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_custom_bypass:{label:`Armed (Bypass)`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},arming:{label:`Arming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},disarming:{label:`Disarming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},pending:{label:`Pending`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},triggered:{label:`Triggered`,colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`triggered`}},KU={home:`Home`,away:`Away`,night:`Night`,vacation:`Vacation`,custom_bypass:`Bypass`};function qU(e){return e.startsWith(`armed_`)}function JU(e){return e===`arming`||e===`disarming`}function YU({icon:e}){return e===`disarmed`?(0,C.jsx)(yR,{className:`h-8 w-8`,"aria-hidden":`true`}):e===`triggered`?(0,C.jsx)(_R,{className:`h-8 w-8`,"aria-hidden":`true`}):e===`pending`?(0,C.jsx)(bR,{className:`h-8 w-8`,"aria-hidden":`true`}):(0,C.jsx)(vR,{className:`h-8 w-8`,"aria-hidden":`true`})}function XU({label:e,active:t,busy:n,onSelect:r}){return(0,C.jsx)(`button`,{type:`button`,"aria-label":e,"aria-pressed":t,disabled:n,onClick:e=>{e.stopPropagation(),n||r()},className:Z(`flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors`,t?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-muted hover:bg-surface-hover`,n&&`opacity-40 cursor-not-allowed`),children:e})}function ZU({state:e,availableModes:t,busy:n,onDisarm:r,onArm:a}){let o=qU(e),s=JU(e);return(0,C.jsxs)(`div`,{className:`flex items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1`,children:[(0,C.jsx)(XU,{label:`Disarm`,active:!o&&!s,busy:n,onSelect:r}),t.map(t=>(0,C.jsx)(XU,{label:KU[t],active:!s&&e===`armed_${t}`,busy:n,onSelect:()=>a(t)},t))]})}function QU(e,t,n){let{cap:r,slice:a,available:o}=Iz({trpc:e,deviceId:t,cap:e=>e.alarmPanel,slice:e=>e.state.alarmPanel}),{display:s,applyOptimistic:c}=Yz(a,{enabled:n??!0}),l=!o;return{display:s,capPresent:r!==void 0,busy:l,handleDisarm:()=>{r===void 0||l||(c({state:`disarming`}),r.disarm({}))},handleArm:e=>{r===void 0||l||(c({state:`arming`}),r.arm({mode:e}))}}}function $U({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:a,busy:o,handleDisarm:s,handleArm:c}=QU(e,t,n);return!a||r===void 0?null:(0,C.jsx)(ZU,{state:r.state,availableModes:r.availableModes,busy:o,onDisarm:s,onArm:c})}function eW({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:a,busy:o,handleDisarm:s,handleArm:c}=QU(e,t,n);if(!a||r===void 0)return null;let l=GU[r.state];return(0,C.jsxs)(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[(0,C.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,C.jsx)(`div`,{"data-testid":`alarm-state`,"data-state":r.state,className:Z(`flex h-16 w-16 items-center justify-center rounded-full border-2`,l.colorClass),children:(0,C.jsx)(YU,{icon:l.icon})}),(0,C.jsx)(`span`,{className:`text-sm font-medium text-foreground-muted`,children:l.label})]}),(0,C.jsx)(ZU,{state:r.state,availableModes:r.availableModes,busy:o,onDisarm:s,onArm:c})]})}function tW({children:e}){return(0,C.jsx)(`div`,{className:`flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4`,children:e})}function nW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch});return n!==void 0}function rW({trpc:e,deviceId:t,features:n,optimistic:r}){return nW(e,t)?(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function iW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl});return n!==void 0}function aW({trpc:e,deviceId:t,features:n,optimistic:r}){return iW(e,t)?(0,C.jsx)(gH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function oW({trpc:e,deviceId:t,features:n,optimistic:r}){return nW(e,t)?(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),(0,C.jsx)(_H,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function sW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl});return n!==void 0}function cW({trpc:e,deviceId:t,features:n,optimistic:r}){return sW(e,t)?(0,C.jsxs)(`div`,{className:`inline-flex items-center gap-2`,children:[(0,C.jsx)(mH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),(0,C.jsx)(vH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function lW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl});return n!==void 0}function uW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(SH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function dW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(MH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function fW({trpc:e,deviceId:t,features:n,optimistic:r}){return lW(e,t)?(0,C.jsx)(MH,{trpc:e,deviceId:t,features:n,layout:`full`,optimistic:r}):null}function pW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer});return n!==void 0}function mW({trpc:e,deviceId:t,features:n,optimistic:r}){return pW(e,t)?(0,C.jsx)(qH,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function hW(e,t){let{cap:n}=Iz({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control});return n!==void 0}function gW({trpc:e,deviceId:t,features:n,optimistic:r}){return hW(e,t)?(0,C.jsx)(eU,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function _W({trpc:e,deviceId:t,features:n,optimistic:r}){return hW(e,t)?(0,C.jsx)(tW,{children:(0,C.jsx)(eU,{trpc:e,deviceId:t,features:n,layout:`full`,optimistic:r})}):null}var vW={cover:{InlineControl:$z,HeroCard:iB},valve:{InlineControl:gV,HeroCard:xV},humidifier:{InlineControl:wV,HeroCard:EV},"water-heater":{InlineControl:AV,HeroCard:MV},switch:{InlineControl:rW,HeroCard:RU},light:{InlineControl:oW,HeroCard:PU},fan:{InlineControl:cW,HeroCard:LU},sensor:{InlineControl:wB,HeroCard:NB},thermostat:{InlineControl:uW,HeroCard:fU},climate:{InlineControl:dW,HeroCard:fW},button:{InlineControl:Gz,HeroCard:Kz},update:{InlineControl:IB,HeroCard:LB},lock:{InlineControl:aW,HeroCard:yU},"media-player":{InlineControl:mW,HeroCard:WU},alarm:{InlineControl:$U,HeroCard:eW},control:{InlineControl:gW,HeroCard:_W},weather:{InlineControl:RV,HeroCard:UV},vacuum:{InlineControl:XB,HeroCard:QB},"lawn-mower":{InlineControl:lV,HeroCard:dV},image:{InlineControl:XV,HeroCard:ZV},"pet-feeder":{InlineControl:fH,HeroCard:pH},dummy:{InlineControl:aB,HeroCard:oB}};Object.fromEntries(Object.values(W).map(e=>[e,vW[Mh[e]]])),W.Cover,W.Valve,W.Thermostat,W.Climate,W.Control,W.Button,W.MediaPlayer,W.AlarmPanel,W.Lock,W.Vacuum,W.LawnMower,W.Humidifier,W.Switch,W.Siren,W.Light,W.Fan,W.WaterHeater,W.Sensor,W.Presence,W.EventEmitter,W.Notifier,W.Script,W.Automation,W.Camera,W.Hub,W.Update,W.Generic,W.Weather,W.Container,W.Image,W.PetFeeder,new Set(Object.values(W));var yW={[W.Camera]:{icon:dL,label:`Camera`},[W.Hub]:{icon:sR,label:`Hub`},[W.Light]:{icon:WL,label:`Light`},[W.Siren]:{icon:xR,label:`Siren`},[W.Switch]:{icon:PR,label:`Switch`},[W.Sensor]:{icon:$I,label:`Sensor`},[W.Thermostat]:{icon:NR,label:`Thermostat`},[W.Climate]:{icon:eL,label:`Air conditioner`},[W.Button]:{icon:_L,label:`Button`},[W.EventEmitter]:{icon:YR,label:`Event Emitter`},[W.Update]:{icon:mR,label:`Update`},[W.Generic]:{icon:uL,label:`Generic`},[W.Notifier]:{icon:oL,label:`Notifier`},[W.Script]:{icon:gR,label:`Script`},[W.Automation]:{icon:qR,label:`Automation`},[W.Lock]:{icon:YL,label:`Lock`},[W.Cover]:{icon:sL,label:`Cover`},[W.Valve]:{icon:uR,label:`Valve`},[W.Humidifier]:{icon:UR,label:`Humidifier`},[W.WaterHeater]:{icon:rL,label:`Water heater`},[W.Fan]:{icon:ML,label:`Fan`},[W.MediaPlayer]:{icon:eR,label:`Media player`},[W.AlarmPanel]:{icon:_R,label:`Alarm panel`},[W.Control]:{icon:wR,label:`Control`},[W.Presence]:{icon:ZL,label:`Presence`},[W.Weather]:{icon:CL,label:`Weather`},[W.Vacuum]:{icon:lL,label:`Vacuum`},[W.LawnMower]:{icon:FR,label:`Lawn mower`},[W.Container]:{icon:uL,label:`Container`},[W.Image]:{icon:HL,label:`Image`},[W.PetFeeder]:{icon:cL,label:`Pet feeder`}},bW={[G.Siren]:{icon:xR,label:`Siren`},[G.Floodlight]:{icon:WL,label:`Floodlight`},[G.Spotlight]:{icon:FL,label:`Spotlight`},[G.PirSensor]:{icon:pR,label:`PIR sensor`},[G.Chime]:{icon:oL,label:`Chime`},[G.Autotrack]:{icon:TL,label:`Auto-track`},[G.Nightvision]:{icon:tR,label:`Night vision`},[G.PrivacyMask]:{icon:jL,label:`Privacy mask`},[G.Doorbell]:{icon:EL,label:`Doorbell`},[G.BinaryHelper]:{icon:PR,label:`Binary helper`},[G.MotionSensor]:{icon:LL,label:`Motion sensor`},[G.ContactSensor]:{icon:DL,label:`Contact sensor`},[G.LeakSensor]:{icon:kL,label:`Leak sensor`},[G.SmokeSensor]:{icon:tL,label:`Smoke sensor`},[G.COSensor]:{icon:KR,label:`CO sensor`},[G.GasSensor]:{icon:PL,label:`Gas sensor`},[G.TamperSensor]:{icon:_R,label:`Tamper sensor`},[G.VibrationSensor]:{icon:BR,label:`Vibration sensor`},[G.ConnectivitySensor]:{icon:GR,label:`Connectivity`},[G.SoundSensor]:{icon:VR,label:`Sound sensor`},[G.BinarySensor]:{icon:PR,label:`Binary sensor`},[G.TemperatureSensor]:{icon:NR,label:`Temperature`},[G.HumiditySensor]:{icon:AL,label:`Humidity`},[G.AmbientLightSensor]:{icon:jR,label:`Ambient light`},[G.PressureSensor]:{icon:RL,label:`Pressure`},[G.WindSensor]:{icon:KR,label:`Wind`},[G.RainSensor]:{icon:xL,label:`Rain`},[G.UvSensor]:{icon:AR,label:`UV index`},[G.SolarRadiationSensor]:{icon:MR,label:`Solar radiation`},[G.SoilMoistureSensor]:{icon:OR,label:`Soil moisture`},[G.PowerSensor]:{icon:YR,label:`Power`},[G.EnergySensor]:{icon:YR,label:`Energy`},[G.VoltageSensor]:{icon:YR,label:`Voltage`},[G.CurrentSensor]:{icon:YR,label:`Current`},[G.AirQualitySensor]:{icon:KR,label:`Air quality`},[G.BatterySensor]:{icon:RL,label:`Battery`},[G.NumericSensor]:{icon:zL,label:`Numeric sensor`},[G.EnumSensor]:{icon:KL,label:`Enum sensor`},[G.DateTimeSensor]:{icon:vL,label:`Date / time`},[G.GenericSensor]:{icon:RL,label:`Sensor`},[G.NumericControl]:{icon:wR,label:`Numeric control`},[G.SelectControl]:{icon:GL,label:`Select control`},[G.TextControl]:{icon:RR,label:`Text control`},[G.DateTimeControl]:{icon:vL,label:`Date / time control`},[G.MobilePushNotifier]:{icon:TR,label:`Mobile push`},[G.MessagingNotifier]:{icon:$L,label:`Messaging`},[G.EmailNotifier]:{icon:XL,label:`Email`},[G.GenericNotifier]:{icon:oL,label:`Notifier`}},xW=new Set(Object.values(W));new Set(Object.values(G));function SW(e){return xW.has(e)}var CW=yW[W.Generic];bW[G.GenericSensor];function wW(e){return SW(e)?yW[e]??CW:CW}Object.values(W).map(e=>{let t=wW(e);return{id:e,label:t.label,icon:t.icon}}),(0,S.createContext)(null),new Set([W.Sensor,W.Presence]),Object.freeze([]);var TW={face:`#a855f7`,plate:`#ec4899`};Object.freeze({...Object.fromEntries(Object.values(Kc).filter(e=>e.category===`detection`||e.kind===`motion`).map(e=>[e.kind,e.color])),...TW});var EW=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},DW=class{constructor(e){this.generateIdentifier=e,this.kv=new EW}register(e,t){this.kv.getByValue(e)||(t||=this.generateIdentifier(e),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},OW=class extends DW{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t==`object`?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function kW(e){if(`values`in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function AW(e,t){let n=kW(e);if(`find`in n)return n.find(t);let r=n;for(let e=0;e<r.length;e++){let n=r[e];if(t(n))return n}}function jW(e,t){Object.entries(e).forEach(([e,n])=>t(n,e))}function MW(e,t){return e.indexOf(t)!==-1}function NW(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var PW=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return AW(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},FW=e=>Object.prototype.toString.call(e).slice(8,-1),IW=e=>e===void 0,LW=e=>e===null,RW=e=>typeof e!=`object`||!e||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,zW=e=>RW(e)&&Object.keys(e).length===0,BW=e=>Array.isArray(e),VW=e=>typeof e==`string`,HW=e=>typeof e==`number`&&!isNaN(e),UW=e=>typeof e==`boolean`,WW=e=>e instanceof RegExp,GW=e=>e instanceof Map,KW=e=>e instanceof Set,qW=e=>FW(e)===`Symbol`,JW=e=>e instanceof Date&&!isNaN(e.valueOf()),YW=e=>e instanceof Error,XW=e=>typeof e==`number`&&isNaN(e),ZW=e=>UW(e)||LW(e)||IW(e)||HW(e)||VW(e)||qW(e),QW=e=>typeof e==`bigint`,$W=e=>e===1/0||e===-1/0,eG=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),tG=e=>e instanceof URL,nG=e=>e.replace(/\\/g,`\\\\`).replace(/\./g,`\\.`),rG=e=>e.map(String).map(nG).join(`.`),iG=(e,t)=>{let n=[],r=``;for(let a=0;a<e.length;a++){let o=e.charAt(a);if(!t&&o===`\\`){let t=e.charAt(a+1);if(t===`\\`){r+=`\\`,a++;continue}else if(t!==`.`)throw Error(`invalid path`)}if(o===`\\`&&e.charAt(a+1)===`.`){r+=`.`,a++;continue}if(o===`.`){n.push(r),r=``;continue}r+=o}let a=r;return n.push(a),n};function aG(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var oG=[aG(IW,`undefined`,()=>null,()=>void 0),aG(QW,`bigint`,e=>e.toString(),e=>typeof BigInt<`u`?BigInt(e):(console.error(`Please add a BigInt polyfill.`),e)),aG(JW,`Date`,e=>e.toISOString(),e=>new Date(e)),aG(YW,`Error`,(e,t)=>{let n={name:e.name,message:e.message};return`cause`in e&&(n.cause=e.cause),t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n},(e,t)=>{let n=Error(e.message,{cause:e.cause});return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n}),aG(WW,`regexp`,e=>``+e,e=>{let t=e.slice(1,e.lastIndexOf(`/`)),n=e.slice(e.lastIndexOf(`/`)+1);return new RegExp(t,n)}),aG(KW,`set`,e=>[...e.values()],e=>new Set(e)),aG(GW,`map`,e=>[...e.entries()],e=>new Map(e)),aG(e=>XW(e)||$W(e),`number`,e=>XW(e)?`NaN`:e>0?`Infinity`:`-Infinity`,Number),aG(e=>e===0&&1/e==-1/0,`number`,()=>`-0`,Number),aG(tG,`URL`,e=>e.toString(),e=>new URL(e))];function sG(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var cG=sG((e,t)=>qW(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>[`symbol`,t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown symbol`);return r}),lG=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),uG=sG(eG,e=>[`typed-array`,e.constructor.name],e=>[...e],(e,t)=>{let n=lG[t[1]];if(!n)throw Error(`Trying to deserialize unknown typed array`);return new n(e)});function dG(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var fG=sG(dG,(e,t)=>[`class`,t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(t=>{r[t]=e[t]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),pG=sG((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>[`custom`,t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw Error(`Trying to deserialize unknown custom value`);return r.deserialize(e)}),mG=[fG,cG,pG,uG],hG=(e,t)=>{let n=NW(mG,n=>n.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=NW(oG,n=>n.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},gG={};oG.forEach(e=>{gG[e.annotation]=e});var _G=(e,t,n)=>{if(BW(t))switch(t[0]){case`symbol`:return cG.untransform(e,t,n);case`class`:return fG.untransform(e,t,n);case`custom`:return pG.untransform(e,t,n);case`typed-array`:return uG.untransform(e,t,n);default:throw Error(`Unknown transformation: `+t)}else{let r=gG[t];if(!r)throw Error(`Unknown transformation: `+t);return r.untransform(e,n)}},vG=(e,t)=>{if(t>e.size)throw Error(`index out of bounds`);let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function yG(e){if(MW(e,`__proto__`))throw Error(`__proto__ is not allowed as a property`);if(MW(e,`prototype`))throw Error(`prototype is not allowed as a property`);if(MW(e,`constructor`))throw Error(`constructor is not allowed as a property`)}var bG=(e,t)=>{yG(t);for(let n=0;n<t.length;n++){let r=t[n];if(KW(e))e=vG(e,+r);else if(GW(e)){let a=+r,o=+t[++n]==0?`key`:`value`,s=vG(e,a);switch(o){case`key`:e=s;break;case`value`:e=e.get(s);break}}else e=e[r]}return e},xG=(e,t,n)=>{if(yG(t),t.length===0)return n(e);let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(BW(r)){let e=+n;r=r[e]}else if(RW(r))r=r[n];else if(KW(r)){let e=+n;r=vG(r,e)}else if(GW(r)){if(e===t.length-2)break;let a=+n,o=+t[++e]==0?`key`:`value`,s=vG(r,a);switch(o){case`key`:r=s;break;case`value`:r=r.get(s);break}}}let a=t[t.length-1];if(BW(r)?r[+a]=n(r[+a]):RW(r)&&(r[a]=n(r[a])),KW(r)){let e=vG(r,+a),t=n(e);e!==t&&(r.delete(e),r.add(t))}if(GW(r)){let e=+t[t.length-2],o=vG(r,e);switch(+a==0?`key`:`value`){case`key`:{let e=n(o);r.set(e,r.get(o)),e!==o&&r.delete(o);break}case`value`:r.set(o,n(r.get(o)));break}}return e},SG=e=>e<1;function CG(e,t,n,r=[]){if(!e)return;let a=SG(n);if(!BW(e)){jW(e,(e,o)=>CG(e,t,n,[...r,...iG(o,a)]));return}let[o,s]=e;s&&jW(s,(e,o)=>{CG(e,t,n,[...r,...iG(o,a)])}),t(o,r)}function wG(e,t,n,r){return CG(t,(t,n)=>{e=xG(e,n,e=>_G(e,t,r))},n),e}function TG(e,t,n){let r=SG(n);function a(t,n){let a=bG(e,iG(n,r));t.map(e=>iG(e,r)).forEach(t=>{e=xG(e,t,()=>a)})}if(BW(t)){let[n,o]=t;n.forEach(t=>{e=xG(e,iG(t,r),()=>e)}),o&&jW(o,a)}else jW(t,a);return e}var EG=(e,t)=>RW(e)||BW(e)||GW(e)||KW(e)||YW(e)||dG(e,t);function DG(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function OG(e,t){let n={},r;return e.forEach(e=>{if(e.length<=1)return;t||(e=e.map(e=>e.map(String)).sort((e,t)=>e.length-t.length));let[a,...o]=e;a.length===0?r=o.map(rG):n[rG(a)]=o.map(rG)}),r?zW(n)?[r]:[r,n]:zW(n)?void 0:n}var kG=(e,t,n,r,a=[],o=[],s=new Map)=>{let c=ZW(e);if(!c){DG(e,a,t);let n=s.get(e);if(n)return r?{transformedValue:null}:n}if(!EG(e,n)){let t=hG(e,n),r=t?{transformedValue:t.value,annotations:[t.type]}:{transformedValue:e};return c||s.set(e,r),r}if(MW(o,e))return{transformedValue:null};let l=hG(e,n),u=l?.value??e,d=BW(u)?[]:{},f={};jW(u,(c,l)=>{if(l===`__proto__`||l===`constructor`||l===`prototype`)throw Error(`Detected property ${l}. This is a prototype pollution risk, please remove it from your object.`);let u=kG(c,t,n,r,[...a,l],[...o,e],s);d[l]=u.transformedValue,BW(u.annotations)?f[nG(l)]=u.annotations:RW(u.annotations)&&jW(u.annotations,(e,t)=>{f[nG(l)+`.`+t]=e})});let p=zW(f)?{transformedValue:d,annotations:l?[l.type]:void 0}:{transformedValue:d,annotations:l?[l.type,f]:f};return c||s.set(e,p),p};function AG(e){return Object.prototype.toString.call(e).slice(8,-1)}function jG(e){return AG(e)===`Array`}function MG(e){if(AG(e)!==`Object`)return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function NG(e,t,n,r,a){let o={}.propertyIsEnumerable.call(r,t)?`enumerable`:`nonenumerable`;o===`enumerable`&&(e[t]=n),a&&o===`nonenumerable`&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function PG(e,t={}){if(jG(e))return e.map(e=>PG(e,t));if(!MG(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((n,r)=>{if(r===`__proto__`||jG(t.props)&&!t.props.includes(r))return n;let a=e[r];return NG(n,r,PG(a,t),e,t.nonenumerable),n},{})}var FG=class{constructor({dedupe:e=!1}={}){this.classRegistry=new OW,this.symbolRegistry=new DW(e=>e.description??``),this.customTransformerRegistry=new PW,this.allowedErrorProps=[],this.dedupe=e}serialize(e){let t=new Map,n=kG(e,t,this,this.dedupe),r={json:n.transformedValue};n.annotations&&(r.meta={...r.meta,values:n.annotations});let a=OG(t,this.dedupe);return a&&(r.meta={...r.meta,referentialEqualities:a}),r.meta&&(r.meta.v=1),r}deserialize(e,t){let{json:n,meta:r}=e,a=t?.inPlace?n:PG(n);return r?.values&&(a=wG(a,r.values,r.v??0,this)),r?.referentialEqualities&&(a=TG(a,r.referentialEqualities,r.v??0)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};FG.defaultInstance=new FG,FG.serialize=FG.defaultInstance.serialize.bind(FG.defaultInstance),FG.deserialize=FG.defaultInstance.deserialize.bind(FG.defaultInstance),FG.stringify=FG.defaultInstance.stringify.bind(FG.defaultInstance),FG.parse=FG.defaultInstance.parse.bind(FG.defaultInstance),FG.registerClass=FG.defaultInstance.registerClass.bind(FG.defaultInstance),FG.registerSymbol=FG.defaultInstance.registerSymbol.bind(FG.defaultInstance),FG.registerCustom=FG.defaultInstance.registerCustom.bind(FG.defaultInstance),FG.allowErrorProps=FG.defaultInstance.allowErrorProps.bind(FG.defaultInstance),FG.serialize,FG.deserialize,FG.stringify,FG.parse,FG.registerClass,FG.registerCustom,FG.registerSymbol,FG.allowErrorProps,(0,S.createContext)(null),ZM(`camstack:custom-field-renderers`,{}),ZM(`camstack:device-context`,null),ZM(`camstack:widget-registry`,null);function IG({title:e,icon:t,headerRight:n,collapsible:r=!1,defaultOpen:a=!0,bodyClassName:o=`p-3`,children:s}){let[c,l]=(0,S.useState)(a),u=!r||c,d=(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`span`,{className:`flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground`,children:[t,e]}),r?c?(0,C.jsx)(pL,{className:`h-3.5 w-3.5 text-foreground-subtle`}):(0,C.jsx)(mL,{className:`h-3.5 w-3.5 text-foreground-subtle`}):n]}),f=`px-4 py-2 flex items-center justify-between ${u?`border-b border-border`:``}`;return(0,C.jsxs)(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r?(0,C.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`w-full text-left ${f}`,children:d}):(0,C.jsx)(`div`,{className:f,children:d}),u?(0,C.jsx)(`div`,{className:o,children:s}):null]})}ZM(`camstack:vod-playback`,{request:null,play:()=>{},clear:()=>{}}),ZM(`camstack:recorded-playback`,{bindControlChannel:null,channelOpen:!1,mode:`live`,positionMs:null,send:()=>!1}),(0,S.lazy)(()=>fs(()=>import(`./MotionZonesSettings-NcxxQN8r-C0-pVeBX.js`).then(e=>({default:e.MotionZonesSettings})),__vite__mapDeps([0,1]),import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./PrivacyMaskSettings-APgPLF7p-QVePTd0g.js`).then(e=>({default:e.PrivacyMaskSettings})),__vite__mapDeps([2,1]),import.meta.url));var LG=Object.defineProperty,RG=Object.getOwnPropertySymbols,zG=Object.prototype.hasOwnProperty,BG=Object.prototype.propertyIsEnumerable,VG=(e,t,n)=>t in e?LG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,HG=(e,t)=>{for(var n in t||={})zG.call(t,n)&&VG(e,n,t[n]);if(RG)for(var n of RG(t))BG.call(t,n)&&VG(e,n,t[n]);return e},UG=(e,t)=>{var n={};for(var r in e)zG.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&RG)for(var r of RG(e))t.indexOf(r)<0&&BG.call(e,r)&&(n[r]=e[r]);return n},WG;(e=>{let t=class t{constructor(e,n,r,o){if(this.version=e,this.errorCorrectionLevel=n,this.modules=[],this.isFunction=[],e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version value out of range`);if(o<-1||o>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let s=[];for(let e=0;e<this.size;e++)s.push(!1);for(let e=0;e<this.size;e++)this.modules.push(s.slice()),this.isFunction.push(s.slice());this.drawFunctionPatterns();let c=this.addEccAndInterleave(r);if(this.drawCodewords(c),o==-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(o=t,e=n),this.applyMask(t)}}a(0<=o&&o<=7),this.mask=o,this.applyMask(o),this.drawFormatBits(o),this.isFunction=[]}static encodeText(n,r){let a=e.QrSegment.makeSegments(n);return t.encodeSegments(a,r)}static encodeBinary(n,r){let a=e.QrSegment.makeBytes(n);return t.encodeSegments([a],r)}static encodeSegments(e,r,o=1,c=40,l=-1,u=!0){if(!(t.MIN_VERSION<=o&&o<=c&&c<=t.MAX_VERSION)||l<-1||l>7)throw RangeError(`Invalid value`);let d,f;for(d=o;;d++){let n=t.getNumDataCodewords(d,r)*8,a=s.getTotalBits(e,d);if(a<=n){f=a;break}if(d>=c)throw RangeError(`Data too long`)}for(let e of[t.Ecc.MEDIUM,t.Ecc.QUARTILE,t.Ecc.HIGH])u&&f<=t.getNumDataCodewords(d,e)*8&&(r=e);let p=[];for(let t of e){n(t.mode.modeBits,4,p),n(t.numChars,t.mode.numCharCountBits(d),p);for(let e of t.getData())p.push(e)}a(p.length==f);let m=t.getNumDataCodewords(d,r)*8;a(p.length<=m),n(0,Math.min(4,m-p.length),p),n(0,(8-p.length%8)%8,p),a(p.length%8==0);for(let e=236;p.length<m;e^=253)n(e,8,p);let h=[];for(;h.length*8<p.length;)h.push(0);return p.forEach((e,t)=>h[t>>>3]|=e<<7-(t&7)),new t(d,r,h,l)}getModule(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]}getModules(){return this.modules}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n==0&&r==0||n==0&&r==t-1||n==t-1&&r==0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.errorCorrectionLevel.formatBits<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let o=(t<<10|n)^21522;a(o>>>15==0);for(let e=0;e<=5;e++)this.setFunctionModule(8,e,r(o,e));this.setFunctionModule(8,7,r(o,6)),this.setFunctionModule(8,8,r(o,7)),this.setFunctionModule(7,8,r(o,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,r(o,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,r(o,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,r(o,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;a(t>>>18==0);for(let e=0;e<18;e++){let n=r(t,e),a=this.size-11+e%3,o=Math.floor(e/3);this.setFunctionModule(a,o,n),this.setFunctionModule(o,a,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let a=Math.max(Math.abs(r),Math.abs(n)),o=e+r,s=t+n;0<=o&&o<this.size&&0<=s&&s<this.size&&this.setFunctionModule(o,s,a!=2&&a!=4)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!=1)}setFunctionModule(e,t,n){this.modules[t][e]=n,this.isFunction[t][e]=!0}addEccAndInterleave(e){let n=this.version,r=this.errorCorrectionLevel;if(e.length!=t.getNumDataCodewords(n,r))throw RangeError(`Invalid argument`);let o=t.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][n],s=t.ECC_CODEWORDS_PER_BLOCK[r.ordinal][n],c=Math.floor(t.getNumRawDataModules(n)/8),l=o-c%o,u=Math.floor(c/o),d=[],f=t.reedSolomonComputeDivisor(s);for(let n=0,r=0;n<o;n++){let a=e.slice(r,r+u-s+(n<l?0:1));r+=a.length;let o=t.reedSolomonComputeRemainder(a,f);n<l&&a.push(0),d.push(a.concat(o))}let p=[];for(let e=0;e<d[0].length;e++)d.forEach((t,n)=>{(e!=u-s||n>=l)&&p.push(t[e])});return a(p.length==c),p}drawCodewords(e){if(e.length!=Math.floor(t.getNumRawDataModules(this.version)/8))throw RangeError(`Invalid argument`);let n=0;for(let t=this.size-1;t>=1;t-=2){t==6&&(t=5);for(let a=0;a<this.size;a++)for(let o=0;o<2;o++){let s=t-o,c=t+1&2?a:this.size-1-a;!this.isFunction[c][s]&&n<e.length*8&&(this.modules[c][s]=r(e[n>>>3],7-(n&7)),n++)}}a(n==e.length*8)}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.isFunction[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let n=0;n<this.size;n++){let r=!1,a=0,o=[0,0,0,0,0,0,0];for(let s=0;s<this.size;s++)this.modules[n][s]==r?(a++,a==5?e+=t.PENALTY_N1:a>5&&e++):(this.finderPenaltyAddHistory(a,o),r||(e+=this.finderPenaltyCountPatterns(o)*t.PENALTY_N3),r=this.modules[n][s],a=1);e+=this.finderPenaltyTerminateAndCount(r,a,o)*t.PENALTY_N3}for(let n=0;n<this.size;n++){let r=!1,a=0,o=[0,0,0,0,0,0,0];for(let s=0;s<this.size;s++)this.modules[s][n]==r?(a++,a==5?e+=t.PENALTY_N1:a>5&&e++):(this.finderPenaltyAddHistory(a,o),r||(e+=this.finderPenaltyCountPatterns(o)*t.PENALTY_N3),r=this.modules[s][n],a=1);e+=this.finderPenaltyTerminateAndCount(r,a,o)*t.PENALTY_N3}for(let n=0;n<this.size-1;n++)for(let r=0;r<this.size-1;r++){let a=this.modules[n][r];a==this.modules[n][r+1]&&a==this.modules[n+1][r]&&a==this.modules[n+1][r+1]&&(e+=t.PENALTY_N2)}let n=0;for(let e of this.modules)n=e.reduce((e,t)=>e+ +!!t,n);let r=this.size*this.size,o=Math.ceil(Math.abs(n*20-r*10)/r)-1;return a(0<=o&&o<=9),e+=o*t.PENALTY_N4,a(0<=e&&e<=2568888),e}getAlignmentPatternPositions(){if(this.version==1)return[];{let e=Math.floor(this.version/7)+2,t=this.version==32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}static getNumRawDataModules(e){if(e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version number out of range`);let n=(16*e+128)*e+64;if(e>=2){let t=Math.floor(e/7)+2;n-=(25*t-10)*t-55,e>=7&&(n-=36)}return a(208<=n&&n<=29648),n}static getNumDataCodewords(e,n){return Math.floor(t.getNumRawDataModules(e)/8)-t.ECC_CODEWORDS_PER_BLOCK[n.ordinal][e]*t.NUM_ERROR_CORRECTION_BLOCKS[n.ordinal][e]}static reedSolomonComputeDivisor(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let n=[];for(let t=0;t<e-1;t++)n.push(0);n.push(1);let r=1;for(let a=0;a<e;a++){for(let e=0;e<n.length;e++)n[e]=t.reedSolomonMultiply(n[e],r),e+1<n.length&&(n[e]^=n[e+1]);r=t.reedSolomonMultiply(r,2)}return n}static reedSolomonComputeRemainder(e,n){let r=n.map(e=>0);for(let a of e){let e=a^r.shift();r.push(0),n.forEach((n,a)=>r[a]^=t.reedSolomonMultiply(n,e))}return r}static reedSolomonMultiply(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return a(n>>>8==0),n}finderPenaltyCountPatterns(e){let t=e[1];a(t<=this.size*3);let n=t>0&&e[2]==t&&e[3]==t*3&&e[4]==t&&e[5]==t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]==0&&(e+=this.size),t.pop(),t.unshift(e)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function n(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function r(e,t){return(e>>>t&1)!=0}function a(e){if(!e)throw Error(`Assertion error`)}let o=class e{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}static makeBytes(t){let r=[];for(let e of t)n(e,8,r);return new e(e.Mode.BYTE,t.length,r)}static makeNumeric(t){if(!e.isNumeric(t))throw RangeError(`String contains non-numeric characters`);let r=[];for(let e=0;e<t.length;){let a=Math.min(t.length-e,3);n(parseInt(t.substring(e,e+a),10),a*3+1,r),e+=a}return new e(e.Mode.NUMERIC,t.length,r)}static makeAlphanumeric(t){if(!e.isAlphanumeric(t))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let r=[],a;for(a=0;a+2<=t.length;a+=2){let o=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a))*45;o+=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a+1)),n(o,11,r)}return a<t.length&&n(e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(a)),6,r),new e(e.Mode.ALPHANUMERIC,t.length,r)}static makeSegments(t){return t==``?[]:e.isNumeric(t)?[e.makeNumeric(t)]:e.isAlphanumeric(t)?[e.makeAlphanumeric(t)]:[e.makeBytes(e.toUtf8ByteArray(t))]}static makeEci(t){let r=[];if(t<0)throw RangeError(`ECI assignment value out of range`);if(t<128)n(t,8,r);else if(t<16384)n(2,2,r),n(t,14,r);else if(t<1e6)n(6,3,r),n(t,21,r);else throw RangeError(`ECI assignment value out of range`);return new e(e.Mode.ECI,0,r)}static isNumeric(t){return e.NUMERIC_REGEX.test(t)}static isAlphanumeric(t){return e.ALPHANUMERIC_REGEX.test(t)}getData(){return this.bitData.slice()}static getTotalBits(e,t){let n=0;for(let r of e){let e=r.mode.numCharCountBits(t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}static toUtf8ByteArray(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)==`%`?(t.push(parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}};o.NUMERIC_REGEX=/^[0-9]*$/,o.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,o.ALPHANUMERIC_CHARSET=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`;let s=o;e.QrSegment=o})(WG||={}),(e=>{(e=>{let t=class{constructor(e,t){this.ordinal=e,this.formatBits=t}};t.LOW=new t(0,1),t.MEDIUM=new t(1,0),t.QUARTILE=new t(2,3),t.HIGH=new t(3,2),e.Ecc=t})(e.QrCode||={})})(WG||={}),(e=>{(e=>{let t=class{constructor(e,t){this.modeBits=e,this.numBitsCharCount=t}numCharCountBits(e){return this.numBitsCharCount[Math.floor((e+7)/17)]}};t.NUMERIC=new t(1,[10,12,14]),t.ALPHANUMERIC=new t(2,[9,11,13]),t.BYTE=new t(4,[8,16,16]),t.KANJI=new t(8,[8,10,12]),t.ECI=new t(7,[0,0,0]),e.Mode=t})(e.QrSegment||={})})(WG||={});var GG=WG,KG={L:GG.QrCode.Ecc.LOW,M:GG.QrCode.Ecc.MEDIUM,Q:GG.QrCode.Ecc.QUARTILE,H:GG.QrCode.Ecc.HIGH},qG=128,JG=`L`,YG=`#FFFFFF`,XG=`#000000`,ZG=!1,QG=1,$G=4,eK=0,tK=.1;function nK(e,t=0){let n=[];return e.forEach(function(e,r){let a=null;e.forEach(function(o,s){if(!o&&a!==null){n.push(`M${a+t} ${r+t}h${s-a}v1H${a+t}z`),a=null;return}if(s===e.length-1){if(!o)return;a===null?n.push(`M${s+t},${r+t} h1v1H${s+t}z`):n.push(`M${a+t},${r+t} h${s+1-a}v1H${a+t}z`);return}o&&a===null&&(a=s)})}),n.join(``)}function rK(e,t){return e.slice().map((e,n)=>n<t.y||n>=t.y+t.h?e:e.map((e,n)=>n<t.x||n>=t.x+t.w?e:!1))}function iK(e,t,n,r){if(r==null)return null;let a=e.length+n*2,o=Math.floor(t*tK),s=a/t,c=(r.width||o)*s,l=(r.height||o)*s,u=r.x==null?e.length/2-c/2:r.x*s,d=r.y==null?e.length/2-l/2:r.y*s,f=r.opacity==null?1:r.opacity,p=null;if(r.excavate){let e=Math.floor(u),t=Math.floor(d);p={x:e,y:t,w:Math.ceil(c+u-e),h:Math.ceil(l+d-t)}}let m=r.crossOrigin;return{x:u,y:d,h:l,w:c,excavation:p,opacity:f,crossOrigin:m}}function aK(e,t){return t==null?e?$G:eK:Math.max(Math.floor(t),0)}function oK({value:e,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:o,size:s,boostLevel:c}){let l=S.useMemo(()=>{let r=(Array.isArray(e)?e:[e]).reduce((e,t)=>(e.push(...GG.QrSegment.makeSegments(t)),e),[]);return GG.QrCode.encodeSegments(r,KG[t],n,void 0,void 0,c)},[e,t,n,c]),{cells:u,margin:d,numCells:f,calculatedImageSettings:p}=S.useMemo(()=>{let e=l.getModules(),t=aK(r,a);return{cells:e,margin:t,numCells:e.length+t*2,calculatedImageSettings:iK(e,s,t,o)}},[l,s,o,r,a]);return{qrcode:l,margin:d,cells:u,numCells:f,calculatedImageSettings:p}}var sK=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),cK=S.forwardRef(function(e,t){let n=e,{value:r,size:a=qG,level:o=JG,bgColor:s=YG,fgColor:c=XG,includeMargin:l=ZG,minVersion:u=QG,boostLevel:d,marginSize:f,imageSettings:p}=n,m=UG(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`marginSize`,`imageSettings`]),{style:h}=m,g=UG(m,[`style`]),_=p?.src,v=S.useRef(null),y=S.useRef(null),b=S.useCallback(e=>{v.current=e,typeof t==`function`?t(e):t&&(t.current=e)},[t]),[x,C]=S.useState(!1),{margin:w,cells:T,numCells:E,calculatedImageSettings:D}=oK({value:r,level:o,minVersion:u,boostLevel:d,includeMargin:l,marginSize:f,imageSettings:p,size:a});S.useEffect(()=>{if(v.current!=null){let e=v.current,t=e.getContext(`2d`);if(!t)return;let n=T,r=y.current,o=D!=null&&r!==null&&r.complete&&r.naturalHeight!==0&&r.naturalWidth!==0;o&&D.excavation!=null&&(n=rK(T,D.excavation));let l=window.devicePixelRatio||1;e.height=e.width=a*l;let u=a/E*l;t.scale(u,u),t.fillStyle=s,t.fillRect(0,0,E,E),t.fillStyle=c,sK?t.fill(new Path2D(nK(n,w))):T.forEach(function(e,n){e.forEach(function(e,r){e&&t.fillRect(r+w,n+w,1,1)})}),D&&(t.globalAlpha=D.opacity),o&&t.drawImage(r,D.x+w,D.y+w,D.w,D.h)}}),S.useEffect(()=>{C(!1)},[_]);let ee=HG({height:a,width:a},h),te=null;return _!=null&&(te=S.createElement(`img`,{src:_,key:_,style:{display:`none`},onLoad:()=>{C(!0)},ref:y,crossOrigin:D?.crossOrigin})),S.createElement(S.Fragment,null,S.createElement(`canvas`,HG({style:ee,height:a,width:a,ref:b,role:`img`},g)),te)});cK.displayName=`QRCodeCanvas`;var lK=S.forwardRef(function(e,t){let n=e,{value:r,size:a=qG,level:o=JG,bgColor:s=YG,fgColor:c=XG,includeMargin:l=ZG,minVersion:u=QG,boostLevel:d,title:f,marginSize:p,imageSettings:m}=n,h=UG(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`title`,`marginSize`,`imageSettings`]),{margin:g,cells:_,numCells:v,calculatedImageSettings:y}=oK({value:r,level:o,minVersion:u,boostLevel:d,includeMargin:l,marginSize:p,imageSettings:m,size:a}),b=_,x=null;m!=null&&y!=null&&(y.excavation!=null&&(b=rK(_,y.excavation)),x=S.createElement(`image`,{href:m.src,height:y.h,width:y.w,x:y.x+g,y:y.y+g,preserveAspectRatio:`none`,opacity:y.opacity,crossOrigin:y.crossOrigin}));let C=nK(b,g);return S.createElement(`svg`,HG({height:a,width:a,viewBox:`0 0 ${v} ${v}`,ref:t,role:`img`},h),!!f&&S.createElement(`title`,null,f),S.createElement(`path`,{fill:s,d:`M0,0 h${v}v${v}H0z`,shapeRendering:`crispEdges`}),S.createElement(`path`,{fill:c,d:C,shapeRendering:`crispEdges`}),x)});lK.displayName=`QRCodeSVG`;function uK(){return typeof window>`u`?!1:window.matchMedia(`(hover: none) and (pointer: coarse)`).matches||typeof navigator<`u`&&navigator.maxTouchPoints>0||`ontouchstart`in window}function dK(e,t,n){let r=0;for(let a=0;a<8;a++)for(let o=0;o<8;o++){let s=Math.min(t-1,Math.floor((o+.5)/8*t)),c=Math.min(n-1,Math.floor((a+.5)/8*n)),{data:l}=e.getImageData(s,c,1,1);.2126*(l[0]??0)+.7152*(l[1]??0)+.0722*(l[2]??0)>12&&r++}return r<=1}function fK(e){let t={};if(typeof window<`u`){if(e){let n=e.getBoundingClientRect();n.width>0&&n.height>0&&(t.viewportWidth=Math.round(n.width),t.viewportHeight=Math.round(n.height))}t.viewportWidth===void 0&&(t.viewportWidth=window.innerWidth,t.viewportHeight=window.innerHeight),t.devicePixelRatio=window.devicePixelRatio||1;let n=navigator.connection;n?.downlink&&n.downlink>0&&(t.downlinkMbps=n.downlink)}return t}var pK=1500,mK=15e3,hK=40,gK=8e3;function _K({serverUrl:e,streamKey:t,label:n,autoPlay:r=!0,muted:a=!0,showControls:o=!0,showStats:s=!1,onPlaybackStats:c,onClientNetworkSample:l,onConnectTiming:u,className:d=``,onStateChange:f,onError:p,overlay:m,createSession:h,sendAnswer:g,handleOffer:_,getIceServers:v,addIceCandidate:y,getIceCandidates:b,closeSession:x,getSessionState:w,reoffer:T,posterUrl:E,hintsOverride:D,reconnectSignal:ee,onControlChannel:te}){let O=(0,S.useRef)(null),ne=(0,S.useRef)(null),re=(0,S.useRef)(null),ie=(0,S.useRef)(new Set),ae=(0,S.useRef)(null),oe=(0,S.useRef)(null),se=(0,S.useRef)(0),k=(0,S.useRef)(!0),A=(0,S.useRef)(te);A.current=te;let ce=(0,S.useRef)(null),le=(0,S.useRef)(null),ue=(0,S.useRef)(0),de=(0,S.useRef)(!1),j=(0,S.useRef)(async()=>{}),[M,fe]=(0,S.useState)(`idle`),[pe,me]=(0,S.useState)(``),[he,ge]=(0,S.useState)(a),[_e,N]=(0,S.useState)(!1),[ve,ye]=(0,S.useState)(!1),be=uK(),[xe,Se]=(0,S.useState)(!0),Ce=(0,S.useRef)(null),we=(0,S.useRef)(!1);(g||h)&&(we.current=!0);let Te=we.current,Ee=(0,S.useRef)(!1);_&&(Ee.current=!0);let De=Ee.current,[Oe,ke]=(0,S.useState)(!1),Ae=(0,S.useRef)(null),[je,Me]=(0,S.useState)(null),[Ne,Pe]=(0,S.useState)(!1),Fe=(0,S.useCallback)(()=>{let e=O.current;if(!(!e||e.readyState<2||!e.videoWidth||!e.videoHeight))try{let t=document.createElement(`canvas`);t.width=e.videoWidth,t.height=e.videoHeight;let n=t.getContext(`2d`);if(!n||(n.drawImage(e,0,0),dK(n,t.width,t.height)))return;Ae.current=t.toDataURL(`image/jpeg`,.6)}catch{}},[]),Ie=(0,S.useCallback)(e=>{fe(e),e===`playing`&&ke(!0),f?.(e)},[f]),Le=(0,S.useCallback)(()=>{if(ae.current?.abort(),ae.current=null,oe.current&&=(clearTimeout(oe.current),null),le.current&&=(clearTimeout(le.current),null),ce.current=null,de.current=!1,ue.current=0,re.current&&=(re.current.close(),null),x&&ie.current.size>0){for(let e of ie.current)x(e).catch(()=>{});ie.current.clear()}},[x]),Re=(0,S.useCallback)(()=>{ae.current?.abort(),ae.current=null,oe.current&&=(clearTimeout(oe.current),null),le.current&&=(clearTimeout(le.current),null),ce.current=null,de.current=!1,ue.current=0},[]),ze=1e3,Be=(0,S.useCallback)(e=>{if(!w||!T)return;le.current&&=(clearTimeout(le.current),null);let t=async()=>{if(k.current&&ce.current===e){if(!de.current)try{let{pendingRenegotiation:t}=await w(e);if(k.current&&ce.current===e&&t&&t.epoch>ue.current&&!de.current){ue.current=t.epoch,await j.current(e,t.target);return}}catch{}!k.current||ce.current!==e||(le.current=setTimeout(()=>{t()},ze))}};le.current=setTimeout(()=>{t()},ze)},[w,T]),Ve=(0,S.useCallback)(async(e=!1)=>{if(!k.current||!h||!g)return;let t=e?re.current:null,n=e?new Set(ie.current):null;e?Re():Le(),Ie(`connecting`);let r=new AbortController;ae.current=r;try{let{sessionId:a,sdpOffer:o,iceServers:s}=await h({...fK(ne.current),...D});if(ie.current.add(a),!k.current||r.signal.aborted){x?.(a).catch(()=>{}),ie.current.delete(a);return}let c=new RTCPeerConnection({iceServers:[...s??[],{urls:`stun:stun.l.google.com:19302`}]});e||(re.current=c);let l=new MediaStream,u=!1,d=()=>{if(!(u||!k.current)){if(u=!0,re.current=c,O.current&&(O.current.srcObject=l,O.current.play().catch(()=>{})),t&&t!==c)try{t.close()}catch{}if(n)for(let e of n)ie.current.delete(e),x?.(e).catch(()=>{})}};c.ontrack=t=>{if(console.debug(`[WebRTC] ontrack`,t.track.kind,t.track.readyState),l.addTrack(t.track),e){d();return}O.current&&(O.current.srcObject=l,O.current.play().catch(()=>{}))},c.oniceconnectionstatechange=()=>{if(!k.current)return;let t=c.iceConnectionState;if(console.debug(`[WebRTC] ICE state:`,t),t===`connected`||t===`completed`)se.current=0,e&&d(),Ie(`playing`),O.current?.paused&&(console.debug(`[WebRTC] video was paused at ICE connected — calling play()`),O.current.play().catch(()=>{}));else if(t===`failed`||t===`disconnected`||t===`closed`){if(e&&!u)try{c.close()}catch{}Ie(`disconnected`),Ke()}},c.onicecandidateerror=e=>{console.debug(`[WebRTC] ICE candidate error:`,e)},console.debug(`[WebRTC] Setting remote description (server offer)...`),await c.setRemoteDescription({type:`offer`,sdp:o});let f=await c.createAnswer();if(await c.setLocalDescription(f),console.debug(`[WebRTC] Local description set, waiting for ICE gathering...`),await yK(c),!k.current)return;let p=(c.localDescription?.sdp??``).split(`
|
|
111
|
+
`).filter(e=>e.startsWith(`a=candidate:`)).length;console.debug(`[WebRTC] Sending answer to server`,{localCandidates:p,sessionId:a.slice(0,8)}),await g(a,c.localDescription?.sdp??``),console.debug(`[WebRTC] Answer sent successfully`);let m=c,_=()=>{let e=m.connectionState;if(e===`closed`||e===`failed`)return;let t=O.current;t&&t.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${m.iceConnectionState})`)};setTimeout(_,3e3),setTimeout(_,8e3)}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}},[e,t,h,g,Le,Re,x,Ie,p,D]),He=(0,S.useCallback)(async()=>{if(k.current){Le(),Ie(`connecting`);try{let n=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});re.current=n,n.addTransceiver(`video`,{direction:`recvonly`}),n.addTransceiver(`audio`,{direction:`recvonly`});let r=new MediaStream;n.ontrack=e=>{r.addTrack(e.track),O.current&&(O.current.srcObject=r,O.current.play().catch(()=>{}))},n.oniceconnectionstatechange=()=>{if(!k.current)return;let e=n.iceConnectionState;e===`connected`||e===`completed`?(se.current=0,Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})):(e===`failed`||e===`disconnected`||e===`closed`)&&(Ie(`disconnected`),Ke())};let a=await n.createOffer();if(await n.setLocalDescription(a),await yK(n),!k.current)return;let o=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,s=await fetch(o,{method:`POST`,headers:{"Content-Type":`application/sdp`},body:n.localDescription?.sdp??``});if(!s.ok)throw Error(`WHEP ${s.status}: ${s.statusText}`);let c=await s.text();await n.setRemoteDescription({type:`answer`,sdp:c})}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}}},[e,t,Le,Ie,p]),Ue=(0,S.useCallback)(async(e=!1)=>{if(!k.current||!_)return;let n=e?re.current:null,r=e?new Set(ie.current):null;e?Re():Le(),Ie(`connecting`);let a=new AbortController;ae.current=a;let o=performance.now(),s=()=>Math.round(performance.now()-o),c={};try{let o=await v?.();if(c.iceServersMs=s(),!k.current||a.signal.aborted)return;let l=new RTCPeerConnection({iceServers:[...o??[],{urls:`stun:stun.l.google.com:19302`}]});e||(re.current=l);let d=new MediaStream,f=!1,p=()=>{if(!(f||!k.current)){if(f=!0,re.current=l,O.current&&(O.current.srcObject=d,O.current.play().catch(()=>{})),n&&n!==l)try{n.close()}catch{}if(r)for(let e of r)ie.current.delete(e),x?.(e).catch(()=>{})}};l.ontrack=t=>{if(c.firstTrackMs===void 0&&(c.firstTrackMs=s()),console.debug(`[WebRTC] ontrack (client-offer)`,t.track.kind,t.track.readyState),d.addTrack(t.track),e){p();return}O.current&&(O.current.srcObject=d,O.current.play().catch(()=>{}))};let m=!1;l.oniceconnectionstatechange=()=>{if(!k.current)return;let n=l.iceConnectionState;if(console.debug(`[WebRTC] ICE state (client-offer):`,n),n===`connected`||n===`completed`){if(!m){m=!0,c.iceConnectedMs=s(),console.info(`[WebRTC timing] client-offer connected`,{streamKey:t,...c}),u?.({...c});let e=O.current;e&&`requestVideoFrameCallback`in e&&(e.requestVideoFrameCallback(()=>{c.firstFrameMs=s(),console.info(`[WebRTC timing] first decoded frame`,{streamKey:t,firstFrameMs:c.firstFrameMs}),u?.({...c})}),setTimeout(()=>{k.current&&c.firstFrameMs===void 0&&console.warn(`[WebRTC timing] NO decoded frame (stalled)`,{streamKey:t,sinceIceConnectedMs:s()-(c.iceConnectedMs??0),iceConnectedMs:c.iceConnectedMs,firstTrackMs:c.firstTrackMs})},gK))}se.current=0,e&&p(),Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})}else if(n===`failed`||n===`disconnected`||n===`closed`){if(e&&!f)try{l.close()}catch{}Ie(`disconnected`),Ke()}};let h=null,g=[];if(l.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();h&&y?y(h,t).catch(()=>{}):g.push(t)},l.addTransceiver(`video`,{direction:`recvonly`}),l.addTransceiver(`audio`,{direction:`recvonly`}),A.current){let e=l.createDataChannel(`camstack-control`);A.current(e)}let S=await l.createOffer();if(c.offerCreatedMs=s(),await l.setLocalDescription(S),c.localSetMs=s(),!k.current||a.signal.aborted)return;let C={...fK(ne.current),...D},w=s(),{sessionId:T,sdpAnswer:E}=await _(l.localDescription?.sdp??S.sdp??``,void 0,C);if(c.signalingRttMs=s()-w,h=T,ie.current.add(T),ce.current=T,!k.current||a.signal.aborted){x?.(T).catch(()=>{}),ie.current.delete(T);return}if(y)for(let e of g)y(T,e).catch(()=>{});if(g.length=0,await l.setRemoteDescription({type:`answer`,sdp:E}),c.answerSetMs=s(),console.debug(`[WebRTC] Client-offer answer set (trickle)`,{sessionId:T.slice(0,8)}),b){let e=new Set,t=Date.now(),n=async()=>{if(!(!k.current||a.signal.aborted)&&!(l.connectionState===`closed`||l.signalingState===`closed`)){try{let{candidates:n,done:r}=await b(T);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),l.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let a=l.iceConnectionState;if(r||Date.now()-t>1e4||a===`connected`||a===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Be(T)}catch(e){if(!k.current)return;let t=e instanceof Error?e.message:String(e);me(t),Ie(`error`),p?.(t),Ke()}},[_,v,y,b,x,Le,Re,Ie,p,Be,D]);j.current=(0,S.useCallback)(async(e,t)=>{let n=T;if(!k.current||!n)return;let r=re.current;de.current=!0;try{let a=await v?.();if(!k.current)return;let o=new RTCPeerConnection({iceServers:[...a??[],{urls:`stun:stun.l.google.com:19302`}]}),s=new MediaStream,c=!1,l=!1,u=null,d,f,p=()=>{f!==void 0&&(clearTimeout(f),f=void 0);let e=u;if(u=null,e){d!==void 0&&typeof e.cancelVideoFrameCallback==`function`&&e.cancelVideoFrameCallback(d),e.removeEventListener(`loadeddata`,m);try{e.srcObject=null}catch{}e.remove()}};function m(){if(c||!k.current){p();return}c=!0,re.current=o,O.current&&(O.current.srcObject=s,O.current.play().catch(()=>{})),r&&r!==o&&r.close(),p()}let h=()=>{if(l||c||!k.current)return;if(l=!0,typeof document>`u`){m();return}let e=document.createElement(`video`);e.muted=!0,e.playsInline=!0,e.autoplay=!0,e.style.cssText=`position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none;`,e.srcObject=s,u=e,(ne.current??document.body).appendChild(e),e.play().catch(()=>{}),typeof e.requestVideoFrameCallback==`function`&&(d=e.requestVideoFrameCallback(()=>m())),e.addEventListener(`loadeddata`,m,{once:!0}),f=setTimeout(()=>m(),1800)};o.ontrack=e=>{console.debug(`[WebRTC] ontrack (reoffer)`,e.track.kind,e.track.readyState),s.addTrack(e.track),h()},o.oniceconnectionstatechange=()=>{if(!k.current)return;let e=o.iceConnectionState;console.debug(`[WebRTC] ICE state (reoffer):`,e),e===`connected`||e===`completed`?(se.current=0,h(),Ie(`playing`),O.current?.paused&&O.current.play().catch(()=>{})):(e===`failed`||e===`closed`)&&(p(),!c&&e===`failed`&&o.close(),Ie(`disconnected`),Ke())};let g=null,_=[];if(o.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();g&&y?y(g,t).catch(()=>{}):_.push(t)},o.addTransceiver(`video`,{direction:`recvonly`}),o.addTransceiver(`audio`,{direction:`recvonly`}),A.current){let e=o.createDataChannel(`camstack-control`);A.current(e)}let x=await o.createOffer();if(await o.setLocalDescription(x),!k.current){o.close();return}let S={...fK(ne.current),...D},{sessionId:C,sdpAnswer:w}=await n(e,o.localDescription?.sdp??x.sdp??``,t,S);if(!k.current){o.close();return}if(g=C,ie.current.add(C),ce.current=C,y)for(let e of _)y(C,e).catch(()=>{});if(_.length=0,await o.setRemoteDescription({type:`answer`,sdp:w}),b){let e=new Set,t=Date.now(),n=async()=>{if(k.current&&!(o.connectionState===`closed`||o.signalingState===`closed`)){try{let{candidates:n,done:r}=await b(C);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),o.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let a=o.iceConnectionState;if(r||Date.now()-t>1e4||a===`connected`||a===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Be(C)}catch(t){console.debug(`[WebRTC] reoffer failed; keeping last frame, re-arming poll`,t instanceof Error?t.message:String(t)),Be(e)}finally{de.current=!1}},[T,v,y,b,Ie,Be,D]);let We=De?Ue:Te?Ve:He,Ge=(0,S.useRef)(()=>{});Ge.current=We;let Ke=(0,S.useCallback)(()=>{if(!k.current||se.current>=hK)return;let e=se.current;se.current+=1;let t=Math.min(mK,pK*2**e),n=Math.round(t*(.8+Math.random()*.4));oe.current=setTimeout(()=>{k.current&&Ge.current()},n)},[]);(0,S.useEffect)(()=>(k.current=!0,se.current=0,r&&We(),()=>{k.current=!1,Le()}),[e,t]);let qe=(0,S.useRef)(!1);(0,S.useEffect)(()=>{if(r){if(De){if(!_)return}else if(Te){if(!h||!g)return}else return;qe.current||re.current||(qe.current=!0,We())}},[r,De,Te,_,h,g,We]);let Je=()=>{se.current=0,We()},Ye=()=>{if(se.current=0,re.current&&De){Ue(!0);return}if(re.current&&Te){Ve(!0);return}We()},Xe=(0,S.useRef)(ee);(0,S.useEffect)(()=>{Xe.current!==ee&&(Xe.current=ee,k.current&&Ye())},[ee]);let Ze=()=>{O.current&&(O.current.muted=!O.current.muted,ge(O.current.muted))},Qe=async()=>{if(ne.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(ne.current.requestFullscreen){await ne.current.requestFullscreen();return}let e=O.current;e?.webkitEnterFullscreen&&e.webkitEnterFullscreen()}catch(e){console.warn(`Fullscreen toggle failed: ${e instanceof Error?e.message:e}`)}},$e=async()=>{let e=O.current;if(e)try{if(typeof e.webkitSetPresentationMode==`function`){e.webkitSetPresentationMode(e.webkitPresentationMode===`picture-in-picture`?`inline`:`picture-in-picture`);return}document.pictureInPictureElement?await document.exitPictureInPicture():await e.requestPictureInPicture()}catch(e){console.warn(`PiP toggle failed: ${e instanceof Error?e.message:String(e)}`)}},et=()=>{if(!O.current)return;let e=document.createElement(`canvas`);e.width=O.current.videoWidth||1280,e.height=O.current.videoHeight||720;let n=e.getContext(`2d`);if(!n)return;n.drawImage(O.current,0,0);let r=document.createElement(`a`);r.download=`${t.replace(/[/:]/g,`-`)}-${Date.now()}.jpg`,r.href=e.toDataURL(`image/jpeg`,.92),r.click()};(0,S.useEffect)(()=>{let e=()=>N(!!document.fullscreenElement);document.addEventListener(`fullscreenchange`,e);let t=O.current;return t?.addEventListener(`webkitbeginfullscreen`,e),t?.addEventListener(`webkitendfullscreen`,e),()=>{document.removeEventListener(`fullscreenchange`,e),t?.removeEventListener(`webkitbeginfullscreen`,e),t?.removeEventListener(`webkitendfullscreen`,e)}},[]),(0,S.useEffect)(()=>{let e=O.current,t=typeof document<`u`&&document.pictureInPictureEnabled===!0,n=e!==null&&typeof e.webkitSetPresentationMode==`function`;ye(t||n)},[]);let[tt,nt]=(0,S.useState)(``),rt=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!s){nt(``),rt.current=null;return}let e=async()=>{let e=re.current;if(e)try{let t=await e.getStats(),n=0,r=0,a=0,o=0,s=0,c=0;t.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`?(n=t.bytesReceived??0,r=t.timestamp,a=t.framesPerSecond??0,o=t.frameWidth??0,s=t.frameHeight??0):t.type===`candidate-pair`&&t.nominated&&typeof t.currentRoundTripTime==`number`&&(c=t.currentRoundTripTime)});let l=0;rt.current&&r>rt.current.ts&&(l=Math.round((n-rt.current.bytes)*8/(r-rt.current.ts))),rt.current={bytes:n,ts:r};let u=[];o&&s&&u.push(`${o}×${s}`),a&&u.push(`${Math.round(a)}fps`),l>0&&u.push(`${l} kbps`),c&&u.push(`${Math.round(c*1e3)}ms`),nt(u.join(` · `))}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[s]);let it=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!l){it.current=null;return}let e=async()=>{let e=re.current;if(e)try{let t=await e.getStats(),n=0,r=0,a=0,o=0,s=0,c=0;t.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`?(n=t.packetsLost??0,r=t.packetsReceived??0,a=t.bytesReceived??0,o=t.timestamp,s=t.jitter??0):t.type===`candidate-pair`&&t.nominated&&typeof t.currentRoundTripTime==`number`&&(c=t.currentRoundTripTime)});let u=it.current;if(it.current={lost:n,recv:r,bytes:a,ts:o},!u||o<=u.ts)return;let d=Math.max(0,n-u.lost),f=d+Math.max(0,r-u.recv),p=f>0?Math.min(100,d/f*100):0,m=Math.max(0,Math.round((a-u.bytes)*8/(o-u.ts)));l({rttMs:Math.round(c*1e3),jitterMs:Math.round(s*1e3),estimatedBandwidthKbps:m,packetLossPercent:p})}catch{}},t=setInterval(()=>{e()},2e3);return()=>clearInterval(t)},[l]);let at=(0,S.useRef)(null);(0,S.useEffect)(()=>{if(!c){at.current=null;return}let e=async()=>{let e=re.current,t=O.current;if(e)try{let n=await e.getStats(),r=0,a=0,o=0,s=0,l=0,u=0,d=0,f=0;n.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`&&(r=t.framesReceived??0,a=t.framesDecoded??0,o=t.framesDropped??0,s=t.framesPerSecond??0,l=t.freezeCount??0,u=t.totalFreezesDuration??0,d=t.jitterBufferDelay??0,f=t.jitterBufferEmittedCount??0)});let p=t?.currentTime??0,m=Date.now(),h=at.current,g=f>0?Math.round(d/f*1e3):0;h&&c({dRecv:r-h.recv,dDec:a-h.dec,dDrop:o-h.drop,fps:Math.round(s),dFreeze:l-h.freeze,freezeTotalMs:Math.round(u*1e3),avgJitterMs:g,dCtMs:Math.round((p-h.ct)*1e3),dtMs:m-h.ts,readyState:t?.readyState??-1}),at.current={recv:r,dec:a,drop:o,freeze:l,ct:p,ts:m}}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[c]),(0,S.useEffect)(()=>{ge(a);let e=O.current;e&&(e.muted=a,a||e.play().catch(()=>{}))},[a]);let ot=()=>{be||(Se(!0),Ce.current&&clearTimeout(Ce.current),Ce.current=setTimeout(()=>Se(!1),3e3))},st=()=>{Se(e=>!e),Ce.current&&clearTimeout(Ce.current)};(0,S.useEffect)(()=>{if(M===`playing`){Fe();let e=setInterval(Fe,2e3);return()=>clearInterval(e)}Oe&&Ae.current&&Me(Ae.current)},[M,Oe,Fe]),(0,S.useEffect)(()=>{if(M!==`playing`){Pe(!1);return}let e=O.current;if(!e)return;let t=!1,n=()=>{t||Pe(!0)},r;typeof e.requestVideoFrameCallback==`function`&&(r=e.requestVideoFrameCallback(()=>n())),e.addEventListener(`loadeddata`,n,{once:!0});let a=setTimeout(n,12e3);return()=>{t=!0,clearTimeout(a),r!==void 0&&typeof e.cancelVideoFrameCallback==`function`&&e.cancelVideoFrameCallback(r),e.removeEventListener(`loadeddata`,n)}},[M]);let ct=Oe&&je?je:E??null,lt=!Ne&&ct!==null;return(0,C.jsxs)(`div`,{ref:ne,className:`relative isolate bg-black overflow-hidden group ${d}`,onMouseMove:ot,onMouseEnter:ot,onTouchStart:st,children:[(0,C.jsx)(`video`,{ref:O,autoPlay:r,muted:he,playsInline:!0,className:`w-full h-full object-contain relative z-0`}),lt&&ct&&(0,C.jsx)(`img`,{src:ct,alt:``,className:`absolute inset-0 w-full h-full object-contain z-[5] transform-gpu pointer-events-none`}),n&&M===`playing`&&(0,C.jsx)(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium`,children:n}),s&&tt&&(0,C.jsx)(`div`,{className:`absolute top-2 right-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-mono`,children:tt}),m,!ct&&M===`connecting`&&(0,C.jsxs)(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[(0,C.jsx)(`svg`,{className:`h-6 w-6 text-white/60 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:(0,C.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})}),(0,C.jsx)(`span`,{className:`text-xs text-white/60`,children:`Connecting…`})]}),!ct&&(M===`error`||M===`disconnected`)&&(0,C.jsxs)(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[(0,C.jsx)(`svg`,{className:`h-6 w-6 text-red-400`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:(0,C.jsx)(`path`,{d:`M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36`,strokeLinecap:`round`})}),(0,C.jsx)(`span`,{className:`text-xs text-red-400 text-center px-4`,children:M===`error`?pe||`Connection failed`:`Disconnected`}),(0,C.jsx)(`button`,{onClick:Je,className:`mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors`,children:`Reconnect`})]}),ct&&(M===`connecting`||M===`disconnected`)&&(0,C.jsx)(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55`,children:(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5 text-white/90 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:(0,C.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})})}),ct&&M===`error`&&(0,C.jsx)(`button`,{onClick:Je,title:pe||`Reconnect`,className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white/90 hover:bg-black/75 transition-colors`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,C.jsx)(`path`,{d:`M23 4v6h-6M1 20v-6h6`}),(0,C.jsx)(`path`,{d:`M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15`})]})}),o&&M!==`idle`&&M!==`error`&&(0,C.jsxs)(`div`,{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${be||xe?`opacity-100 pointer-events-auto`:`opacity-0 pointer-events-none`}`,children:[(0,C.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,C.jsx)(vK,{onClick:Ze,title:he?`Unmute`:`Mute`,children:he?(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`line`,{x1:`23`,y1:`9`,x2:`17`,y2:`15`}),(0,C.jsx)(`line`,{x1:`17`,y1:`9`,x2:`23`,y2:`15`})]}):(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`path`,{d:`M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07`})]})})}),(0,C.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,C.jsx)(vK,{onClick:et,title:`Take snapshot`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,C.jsx)(`path`,{d:`M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z`}),(0,C.jsx)(`circle`,{cx:`12`,cy:`13`,r:`4`})]})}),ve&&(0,C.jsx)(vK,{onClick:$e,title:`Picture-in-Picture`,children:(0,C.jsxs)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,C.jsx)(`path`,{d:`M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4`}),(0,C.jsx)(`rect`,{width:`10`,height:`7`,x:`12`,y:`13`,rx:`2`})]})}),(0,C.jsx)(vK,{onClick:Qe,title:_e?`Exit fullscreen`:`Fullscreen`,children:_e?(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:(0,C.jsx)(`path`,{d:`M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3`})}):(0,C.jsx)(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:(0,C.jsx)(`path`,{d:`M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3`})})})]})]})]})}function vK({onClick:e,title:t,children:n}){return(0,C.jsx)(`button`,{onClick:e,title:t,className:`rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors`,children:n})}async function yK(e){if(e.iceGatheringState!==`complete`)return new Promise(t=>{let n=!1,r,a=()=>{n||(n=!0,r&&clearInterval(r),e.removeEventListener(`icegatheringstatechange`,o),t())},o=()=>{e.iceGatheringState===`complete`&&a()};e.addEventListener(`icegatheringstatechange`,o);let s=Date.now();r=setInterval(()=>{let t=e.localDescription?.sdp??``;/ typ host/.test(t)&&Date.now()-s>=600&&a()},100),setTimeout(a,2500)})}ZM(`camstack:player-overlays-state`,null);var bK=ZM(`camstack:player-overlays-actions`,null);function xK(e){let t=(0,S.useContext)(bK);(0,S.useEffect)(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}B({id:F(),stableId:P(),addonId:P(),type:P(),name:P(),online:I(),disabled:I(),parentDeviceId:F().nullable(),role:P().nullable().optional(),features:z(P()).optional(),isCamera:I().optional(),sourceInfo:Cd.optional()}),w.AddonStarted,w.AddonInstalled,w.AddonRestarted,w.AddonUpdated,w.AddonStopped,w.AddonUninstalled,w.AddonCrashed,w.AddonError,w.DetectionPhaseTransition,w.DetectionResult,w.DetectionEvent,w.DetectionCameraNative,w.ProviderMotion,w.MotionOnMotionChanged,w.MotionAnalysis,w.MotionZonesRaw,w.ProviderDetection,w.PipelineAudioInferenceResult,w.AgentOnline,w.AgentOffline,w.DeviceRegistered,w.DeviceUnregistered,w.DeviceStateChanged,w.EventEmitted;var SK=Object.freeze([...new Set(Object.values(w))].toSorted()),CK=Object.freeze([w.PipelineCameraMetricsSnapshot,w.PipelineRunnerLoadSnapshot,w.PipelineEngineMetricsSnapshot,w.PipelineInferenceResult,w.PipelineTrace,w.PipelineProgress,w.StreamBrokerMetricsSnapshot,w.MetricsNodeResourcesSnapshot,w.MetricsNodeProcessesSnapshot,w.ClusterTopologySnapshot,w.MotionAnalysis,w.MotionZonesRaw,w.DetectionResult,w.PipelineAudioInferenceResult,w.PlatformProbePhase,w.BenchmarkProgress,w.ModelDownloadProgress]),wK=new Set(CK);Object.freeze(SK.filter(e=>!wK.has(e))),Object.freeze([...new Set(eT.filter(e=>e.scope===`device`).map(e=>e.name))].toSorted()),ZM(`camstack:zone-editing`,null);var TK=500,EK=800;function DK(e,t,n){try{let r=e.live;if(!r)return null;let a=r.onEvent;return!a||typeof a.subscribe!=`function`?null:a.subscribe({category:t},{onData:n})}catch{return null}}function OK(e,t){return e?.id===t}function kK(e,t){let[n,r]=(0,S.useState)(null),[a,o]=(0,S.useState)(null),[s,c]=(0,S.useState)(null),[l,u]=(0,S.useState)(`watching`),d=(0,S.useRef)(void 0),f=(0,S.useRef)(void 0),p=(0,S.useRef)(void 0),m=(0,S.useRef)(0);return(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.motion-analysis`,e=>{let n=e;if(!OK(n?.source,t))return;let a=n.data;!a?.regions||a.regions.length===0||(r({zones:a.regions.map(e=>({...e.bbox,intensity:e.intensity})),frameWidth:a.frameWidth,frameHeight:a.frameHeight}),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>r(null),TK))});return()=>{n?.unsubscribe(),d.current&&clearTimeout(d.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.motion-zones-raw`,e=>{let n=e;if(!OK(n?.source,t))return;let r=n.data;r?.zones&&(o({boxes:r.zones.map(e=>({bbox:e.bbox,changeScore:e.changeScore})),frameWidth:r.frameSize?.width??0,frameHeight:r.frameSize?.height??0,motionScore:r.zones.length>0?r.zones.reduce((e,t)=>e+t.changeScore,0)/r.zones.length:0}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>o(null),TK))});return()=>{n?.unsubscribe(),f.current&&clearTimeout(f.current)}},[e,t]),(0,S.useEffect)(()=>{if(m.current=0,t===null)return;let n=DK(e,`pipeline-analytics.frame-tracked`,e=>{let n=e?.data;!n||n.deviceId!==t||n.detections?.length&&typeof n.detections[0]?.kind==`string`&&(m.current=Date.now(),c({detections:n.detections,frameWidth:n.frameWidth,frameHeight:n.frameHeight}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>c(null),EK))});return()=>{n?.unsubscribe(),p.current&&clearTimeout(p.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.result`,e=>{let n=e;if(!OK(n?.source,t)||Date.now()-m.current<EK)return;let r=n.data?.frame;r?.detections?.length&&(c({detections:r.detections,frameWidth:r.width,frameHeight:r.height}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>c(null),EK))});return()=>{n?.unsubscribe(),p.current&&clearTimeout(p.current)}},[e,t]),(0,S.useEffect)(()=>{if(t===null)return;let n=DK(e,`detection.phase-transition`,e=>{let n=e;OK(n?.source,t)&&n.data?.to&&u(n.data.to)});return()=>{n?.unsubscribe()}},[e,t]),{motion:n,motionRaw:a,detection:s,phase:l}}function AK(e,t,n=5e3){let[r,a]=(0,S.useState)([]);(0,S.useEffect)(()=>{if(t===null)return;let r=!1,o=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(e=>{r||a(e)}).catch(()=>{})};o();let s=setInterval(o,n);return()=>{r=!0,clearInterval(s)}},[e,t,n]);let[o,s]=(0,S.useState)(null);(0,S.useEffect)(()=>{if(t===null)return;let n=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(e=>{n||!e||s({phase:e.phase,detectionFps:e.actualFps,avgInferenceMs:e.avgInferenceTimeMs,droppedFrames:e.droppedFrames})}).catch(()=>{}),()=>{n=!0}},[e,t]),Mz(`pipeline.camera-metrics-snapshot`,e=>{if(t===null)return;let n=e.data;n.deviceId!==t||!n.metrics||s({phase:n.metrics.phase,detectionFps:n.metrics.actualFps,avgInferenceMs:n.metrics.avgInferenceTimeMs,droppedFrames:n.metrics.droppedFrames})});let{streams:c,hasWebrtc:l}=(0,S.useMemo)(()=>t===null||r.length===0?{streams:[],hasWebrtc:!1}:{streams:r.map(e=>({id:e.id,label:e.label,target:e.target,status:e.status,inputFps:e.inputFps,decodeFps:e.decodeFps,bitrateKbps:e.bitrateKbps})),hasWebrtc:!0},[t,r]),u=(0,S.useCallback)(async()=>{if(e.turnProvider)try{return(await e.turnProvider.getTurnServers.query()).map(e=>({urls:typeof e.urls==`string`?e.urls:[...e.urls],...e.username===void 0?{}:{username:e.username},...e.credential===void 0?{}:{credential:e.credential}}))}catch{return}},[e]),d=(0,S.useCallback)(async(n,r)=>{if(t===null)throw Error(`No device selected`);let a=await e.webrtcSession.createSession.mutate({deviceId:t,target:n,hints:r}),o=await u();return{sessionId:a.sessionId,sdpOffer:a.sdpOffer,...o?{iceServers:o}:{}}},[e,t,u]),f=(0,S.useCallback)(async(n,r,a,o)=>{if(t===null)throw Error(`No device selected`);return e.webrtcSession.handleOffer.mutate({deviceId:t,target:n,sdpOffer:r,...a===void 0?{}:{sessionId:a},...o===void 0?{}:{hints:o}})},[e,t]),p=(0,S.useCallback)(async(n,r)=>{if(t===null)throw Error(`No device selected`);await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:n,sdpAnswer:r})},[e,t]);return{streams:c,hasWebrtc:l,pipelineMetrics:o,createSession:d,handleOffer:f,getIceServers:u,addIceCandidate:(0,S.useCallback)(async(n,r)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:n,candidate:r.candidate??``,sdpMid:r.sdpMid??null,sdpMLineIndex:r.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:(0,S.useCallback)(async n=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:n}),[e,t]),sendAnswer:p,closeSession:(0,S.useCallback)(async n=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:n}).catch(()=>{})},[e,t]),getSessionState:(0,S.useCallback)(async n=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:n})}catch{return{pendingRenegotiation:null}}},[e,t])}}(0,S.lazy)(()=>fs(()=>import(`./MaskShapeCanvas-DI4BY7W2-Hg_mGtXA.js`).then(e=>({default:e.MaskShapeCanvas})),[],import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./MotionZonesSettings-NcxxQN8r-C0-pVeBX.js`).then(e=>({default:e.MotionZonesSettings})),__vite__mapDeps([0,1]),import.meta.url)),(0,S.lazy)(()=>fs(()=>import(`./PrivacyMaskSettings-APgPLF7p-QVePTd0g.js`).then(e=>({default:e.PrivacyMaskSettings})),__vite__mapDeps([2,1]),import.meta.url));var jK=H([`auto`,`high`,`medium`,`low`]),MK=Co([U(`auto`),F().int().min(1)]),NK=B({enabled:I(),motion:I(),motionHoldSec:F().optional(),audio:H([`off`,`sensor`,`level`]),audioDb:F(),audioHoldSec:F(),detection:I(),detectionHoldSec:F(),detectionClasses:z(P()).optional(),appearance:B({motionColor:P(),audioColor:P(),detectionColor:P(),thickness:F()}).optional()}),PK=B({serverUrl:P().min(1),token:P().min(1),devices:z(F().int().nonnegative()).min(1),layout:MK,quality:jK,showName:I(),showBadges:I(),muted:I(),paused:I(),highlight:NK.optional(),activeOnly:I().optional(),showBoxes:I().optional(),audioOnIds:z(F().int().nonnegative()).optional(),pausedIds:z(F().int().nonnegative()).optional(),snapshots:V(P(),P()).optional(),ptzIds:z(F().int().nonnegative()).optional()});function FK(e){if(e==null)return{ok:!1,error:`config is required`};let t=PK.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}var IK=1e4;function LK(){try{return window.parent!==window}catch{return!0}}function RK(e){let t=window.ReactNativeWebView;if(t){t.postMessage(JSON.stringify(e));return}LK()&&window.parent.postMessage(e,`*`)}function zK(e){let t=t=>{let n=t.data;if(typeof n!=`object`||!n)return;let r=n;r.type!==`embed-command`||typeof r.command!=`object`||r.command===null||e(r.command)};return window.addEventListener(`message`,t),()=>window.removeEventListener(`message`,t)}function BK(e,t,n,r){let a=t();if(a!=null)return Promise.resolve(n(a));if(!LK()){let t=r===void 0?null:r();return t===null?Promise.resolve({ok:!1,error:`config global for mode "${e}" is not set`}):Promise.resolve(t)}return new Promise(t=>{let r,a=e=>{let o=e.data;if(typeof o!=`object`||!o)return;let s=o;s.type===`embed-config`&&(clearTimeout(r),window.removeEventListener(`message`,a),t(n(s.config)))};window.addEventListener(`message`,a),r=setTimeout(()=>{window.removeEventListener(`message`,a),t({ok:!1,error:`config handshake timed out`})},IK),window.parent.postMessage({type:`embed-ready`,mode:e},`*`)})}function VK(e,t,n,r){let[a,o]=(0,S.useState)(null),s=(0,S.useRef)(t);s.current=t;let c=(0,S.useRef)(n);c.current=n;let l=(0,S.useRef)(r);return l.current=r,(0,S.useEffect)(()=>{let t=!0;return BK(e,()=>s.current(),e=>c.current(e),()=>l.current===void 0?null:l.current()).then(e=>{t&&o(e)}),()=>{t=!1}},[e]),a}var HK=H([`auto`,`high`,`medium`,`low`]),UK=Co([U(`auto`),F().int().min(1)]),WK=B({enabled:I(),motion:I(),audio:H([`off`,`sensor`,`level`]),audioDb:F(),audioHoldSec:F(),detection:I(),detectionHoldSec:F(),detectionClasses:z(P()).optional(),appearance:B({motionColor:P(),audioColor:P(),detectionColor:P(),thickness:F()}).optional()}),GK=B({devices:z(F().int().nonnegative()).min(1),layout:UK,quality:HK,showName:I(),audioOnIds:z(F().int().nonnegative()).optional(),activeOnly:I().optional(),boxes:I().optional(),highlight:WK.optional()}),KK=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function qK(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===void 0)return null;let a,o;if(r<128)a=r,o=0;else if((r&224)==192)a=r&31,o=1;else if((r&240)==224)a=r&15,o=2;else if((r&248)==240)a=r&7,o=3;else return null;for(let t=1;t<=o;t++){let r=e[n+t];if(r===void 0||(r&192)!=128)return null;a=a<<6|r&63}n+=o+1,t+=String.fromCodePoint(a)}return t}function JK(e){if(e.length%4==1)return null;let t=[];for(let n of e){let e=KK.indexOf(n);if(e<0)return null;t.push(e)}let n=[];for(let e=0;e<t.length;e+=4){let r=t[e],a=t[e+1];if(r===void 0||a===void 0)return null;let o=t[e+2],s=t[e+3];n.push(r<<2|a>>4),o!==void 0&&n.push((a&15)<<4|o>>2),s!==void 0&&o!==void 0&&n.push((o&3)<<6|s)}let r=qK(n);if(r===null)return null;try{return JSON.parse(r)}catch{return null}}function YK(e,t){return e.startsWith(t)?e.slice(t.length):e}function XK(e){let t=new URLSearchParams(YK(e,`#`)).get(`t`);return t!==null&&t.length>0?t:null}function ZK(e,t){return new URLSearchParams(YK(e,`?`)).has(`v`)||XK(t)!==null}function QK(e){if(e.length===0)return null;let t=[];for(let n of e.split(`,`)){if(!/^\d+$/.test(n))return null;t.push(Number(n))}return t}function $K(e){return{ok:!1,error:e}}function eq(e,t){let n=new URLSearchParams(YK(e,`?`)),r=n.get(`mode`);if(r!==null&&r!==`grid`)return $K(`unsupported mode "${r}"`);let a=n.get(`v`);if(a===null)return $K(`missing share-link version (v)`);if(a!==`1`)return $K(`unsupported share-link version "${a}"`);let o=n.get(`devices`),s=o===null?null:QK(o);if(s===null||s.length===0)return $K(`invalid or missing devices list`);let c=n.get(`layout`),l;if(c===null||c===`auto`)l=`auto`;else if(/^\d+$/.test(c)&&Number(c)>=1)l=Number(c);else return $K(`invalid layout "${c}"`);let u=n.get(`q`)??`auto`,d=HK.safeParse(u);if(!d.success)return $K(`invalid quality "${u}"`);let f=n.get(`names`)??`0`;if(f!==`0`&&f!==`1`)return $K(`invalid names flag "${f}"`);let p=n.get(`audio`),m;if(p!==null){let e=QK(p);if(e===null)return $K(`invalid audio list "${p}"`);m=e}let h=n.get(`activeOnly`);if(h!==null&&h!==`0`&&h!==`1`)return $K(`invalid activeOnly flag "${h}"`);let g=h===`1`,_=n.get(`boxes`);if(_!==null&&_!==`0`&&_!==`1`)return $K(`invalid boxes flag "${_}"`);let v=_===`1`,y=n.get(`hl`),b;if(y!==null){let e=JK(y),t=WK.safeParse(e);if(e===null||!t.success)return $K(`invalid highlight config (hl)`);b=t.data}let x={devices:[...s],layout:l,quality:d.data,showName:f===`1`,...m!==void 0&&m.length>0?{audioOnIds:[...m]}:{},...g?{activeOnly:!0}:{},...v?{boxes:!0}:{},...b===void 0?{}:{highlight:b}},S=GK.safeParse(x);return S.success?{ok:!0,params:S.data,token:XK(t)}:$K(S.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `))}function tq(e,t,n){if(!ZK(e,t))return null;let r=eq(e,t);if(!r.ok)return{ok:!1,error:r.error};if(r.token===null)return{ok:!1,error:`share token missing — the link must end with #t=<token>`};let a=r.params;return FK({serverUrl:n,token:r.token,devices:[...a.devices],layout:a.layout,quality:a.quality,showName:a.showName,showBadges:!0,muted:!0,paused:!1,...a.highlight===void 0?{}:{highlight:a.highlight},...a.activeOnly===!0?{activeOnly:!0}:{},...a.boxes===!0?{showBoxes:!0}:{},...a.audioOnIds!==void 0&&a.audioOnIds.length>0?{audioOnIds:[...a.audioOnIds]}:{}})}function nq(){let e=tq(location.search,location.hash,location.origin);return e!==null&&location.hash!==``&&history.replaceState(null,``,location.pathname+location.search),e}var rq=16/9;function iq(e,t,n,r){if(e<=0||t<=0||n<=0)return{cols:0,rows:0,cellW:0,cellH:0};if(typeof r==`number`&&r>=1){let a=Math.floor(r),o=Math.ceil(e/a),s=Math.min(t/a,n/o*rq);return{cols:a,rows:o,cellW:s,cellH:s/rq}}let a={cols:1,rows:e,cellW:0,cellH:0},o=-1;for(let r=1;r<=e;r++){let s=Math.ceil(e/r),c=Math.min(t/r,n/s*rq),l=c/rq,u=c*l;u>o&&(o=u,a={cols:r,rows:s,cellW:c,cellH:l})}return a}function aq(){let[e,t]=(0,S.useState)(null),[n,r]=(0,S.useState)(`idle`),a=(0,S.useRef)(null),o=(0,S.useRef)(null),s=(0,S.useRef)(null),c=(0,S.useRef)(0),l=(0,S.useRef)(null),u=lB(),d=uB(),f=dB(),p=(0,S.useRef)({start:u.mutateAsync,answer:d.mutateAsync,stop:f.mutateAsync});p.current={start:u.mutateAsync,answer:d.mutateAsync,stop:f.mutateAsync};let m=(0,S.useCallback)(()=>{if(a.current){try{a.current.close()}catch{}a.current=null}if(o.current){for(let e of o.current.getTracks())try{e.stop()}catch{}o.current=null}},[]),h=(0,S.useCallback)(async()=>{let e=s.current;if(s.current=null,m(),e)try{await p.current.stop({deviceId:e.deviceId,sessionId:e.sessionId})}catch{}},[m]),g=(0,S.useCallback)(async e=>{if(l.current===e){c.current+=1,l.current=null,t(null),r(`idle`),await h();return}c.current+=1;let n=c.current;l.current=e,t(e),r(`starting`);let u;try{u=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch{n===c.current&&(l.current=null,t(null),r(`error`));return}if(n!==c.current){for(let e of u.getTracks())e.stop();return}if(await h(),n!==c.current){for(let e of u.getTracks())e.stop();return}let d=null;try{o.current=u;let f=await p.current.start({deviceId:e});if(n!==c.current){try{await p.current.stop({deviceId:e,sessionId:f.sessionId})}catch{}m();return}s.current={deviceId:e,sessionId:f.sessionId},d=new RTCPeerConnection,a.current=d,d.oniceconnectionstatechange=()=>{if(n!==c.current||!d)return;let e=d.iceConnectionState;e===`connected`||e===`completed`?r(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&(l.current=null,t(null),r(`idle`),h())};for(let e of u.getAudioTracks())d.addTrack(e,u);await d.setRemoteDescription({type:`offer`,sdp:f.sdpOffer});let g=await d.createAnswer();if(await d.setLocalDescription(g),n!==c.current)return;await p.current.answer({deviceId:e,sessionId:f.sessionId,sdpAnswer:d.localDescription?.sdp??g.sdp??``})}catch{if(d)try{d.close()}catch{}m();let e=s.current;if(s.current=null,e)try{await p.current.stop({deviceId:e.deviceId,sessionId:e.sessionId})}catch{}n===c.current&&(l.current=null,t(null),r(`error`))}},[h,m]),_=(0,S.useCallback)(e=>{if(e===null){c.current+=1,l.current=null,t(null),r(`idle`),h();return}l.current!==e&&g(e)},[h,g]);return(0,S.useEffect)(()=>()=>{c.current+=1,h()},[h]),{activeMicId:e,micState:n,toggleMic:e=>{g(e)},setActiveMic:_}}var oq=6e3,sq=500;function cq(e,t){let n=(0,S.useRef)(new Map),[,r]=(0,S.useState)(0),a=t?.motion??!1,o=t?.audio??`off`,s=t?.audioDb??-30,c=t?.audioHoldSec??3,l=t?.detection??!1,u=t?.detectionHoldSec??3,d=t?.detectionClasses??[],f=(e,t)=>{n.current.set(e,Date.now()+t),r(e=>e+1)};Mz(w.MotionOnMotionChanged,e=>{if(!a)return;let t=e.data;t&&t.detected&&f(t.deviceId,oq)}),Mz(w.PipelineAudioInferenceResult,e=>{if(o===`off`)return;let t=e.data;t&&(o===`sensor`?t.frame.detections.length>0:(t.frame.level?.dbfs??-1/0)>=s)&&f(t.deviceId,c*1e3)}),Mz(w.DetectionResult,e=>{if(!l)return;let t=e.data;t&&t.frame.detections.some(e=>d.length===0||d.includes(e.macroClass))&&f(t.frame.deviceId,u*1e3)}),(0,S.useEffect)(()=>{let e=setInterval(()=>r(e=>e+1),sq);return()=>clearInterval(e)},[]);let p=Date.now(),m=new Set;for(let t of e){let e=n.current.get(t);e!==void 0&&p<e&&m.add(t)}return m}function lq(e){return{type:`tileOpen`,deviceId:e}}function uq(e){return{type:`audioToggle`,deviceId:e}}function dq(e){return{type:`pauseToggle`,deviceId:e}}function fq(e){return{type:`ptzOpen`,deviceId:e}}function pq(e,t){return t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t}}function mq(e){return{type:`layout`,tiles:e}}function hq(e){RK(e)}function gq(e,t,n,r){let a=Number.isFinite(e)&&e>0?e:0,o=Number.isFinite(t)&&t>0?t:0;if(!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0)return{width:a,height:o};let s=Math.min(a/n,o/r);return{width:n*s,height:r*s}}function _q(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)?0:Math.max(0,(n*t-e)/2)}function vq(e,t,n,r){if(!Number.isFinite(e))return 0;let a=_q(t,n,r);return Math.max(-a,Math.min(a,e))}var yq=4,bq=8,xq=300;function Sq(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Cq({children:e,onTap:t}){let n=(0,S.useRef)(null),r=(0,S.useRef)(null),a=(0,S.useRef)(new Map),o=(0,S.useRef)(1),s=(0,S.useRef)(0),c=(0,S.useRef)(0),l=(0,S.useRef)(null),u=(0,S.useRef)(null),d=(0,S.useRef)(0),f=()=>{let e=r.current;e&&(e.style.transform=`translate(${s.current}px, ${c.current}px) scale(${o.current})`)},p=()=>{let e=n.current?.getBoundingClientRect();if(!e||e.width<=0||e.height<=0)return;let t=r.current?.querySelector(`video`)??null,a=t?null:r.current?.querySelector(`img`)??null,l=t?.videoWidth??a?.naturalWidth??0,u=t?.videoHeight??a?.naturalHeight??0,d=gq(e.width,e.height,l,u);s.current=vq(s.current,e.width,d.width,o.current),c.current=vq(c.current,e.height,d.height,o.current)},m=()=>{o.current=1,s.current=0,c.current=0,f()},h=e=>{try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}if(a.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),a.current.size===2){let e=[...a.current.values()],t=e[0],n=e[1];t&&n&&(l.current={dist:Sq(t,n),scale:o.current,cx:(t.x+n.x)/2,cy:(t.y+n.y)/2,tx:s.current,ty:c.current}),u.current=null}else a.current.size===1&&(u.current={x:e.clientX,y:e.clientY,tx:s.current,ty:c.current,moved:!1})},g=e=>{if(!a.current.has(e.pointerId))return;if(a.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),a.current.size>=2&&l.current){let e=[...a.current.values()],t=e[0],n=e[1];if(!t||!n)return;let r=Sq(t,n);l.current.dist>0&&(o.current=Math.max(1,Math.min(yq,l.current.scale*(r/l.current.dist))));let u=(t.x+n.x)/2,d=(t.y+n.y)/2;s.current=l.current.tx+(u-l.current.cx),c.current=l.current.ty+(d-l.current.cy),p(),f();return}let t=u.current;if(a.current.size===1&&t){let n=e.clientX-t.x,r=e.clientY-t.y;(Math.abs(n)>bq||Math.abs(r)>bq)&&(t.moved=!0),o.current>1&&(s.current=t.tx+n,c.current=t.ty+r,p(),f())}},_=e=>{let n=a.current.size===1,r=u.current;if(a.current.delete(e.pointerId),a.current.size<2&&(l.current=null),a.current.size===0&&(u.current=null,n&&r&&!r.moved)){let e=Date.now();e-d.current<xq?(d.current=0,m()):(d.current=e,t())}};return(0,C.jsx)(`div`,{ref:n,style:{position:`absolute`,inset:0,overflow:`hidden`,touchAction:`none`},onPointerDown:h,onPointerMove:g,onPointerUp:_,onPointerCancel:_,children:(0,C.jsx)(`div`,{ref:r,style:{width:`100%`,height:`100%`,transformOrigin:`center center`,willChange:`transform`},children:e})})}var wq=2500,Tq={person:`#f59e0b`,vehicle:`#3b82f6`,animal:`#22c55e`,face:`#a855f7`,plate:`#ec4899`},Eq=`#ef4444`;function Dq(e){return Tq[e]??Eq}function Oq(e){return e<0?0:e>1?1:e}function kq(e){if(e.width<=0||e.height<=0)return[];let t=[];for(let n of e.detections){let{bbox:r}=n,a=Oq(r.x/e.width),o=Oq(r.y/e.height),s=Oq((r.x+r.width)/e.width),c=Oq((r.y+r.height)/e.height);s<=a||c<=o||t.push({label:n.macroClass,score:n.score,x1:a,y1:o,x2:s,y2:c})}return t}function Aq({deviceId:e}){let[t,n]=(0,S.useState)([]),r=(0,S.useRef)(void 0);return Mz(w.DetectionResult,t=>{let a=t.data;!a||a.frame.deviceId!==e||(n(kq(a.frame)),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>n([]),wq))}),(0,S.useEffect)(()=>()=>{r.current&&clearTimeout(r.current),n([])},[e]),t.length===0?null:(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,overflow:`hidden`,pointerEvents:`none`},children:t.map((e,t)=>{let n=Dq(e.label),r=Math.round(e.score*100);return(0,C.jsx)(`div`,{style:{position:`absolute`,left:`${e.x1*100}%`,top:`${e.y1*100}%`,width:`${(e.x2-e.x1)*100}%`,height:`${(e.y2-e.y1)*100}%`,border:`2px solid ${n}`,borderRadius:3},children:(0,C.jsx)(`span`,{style:{position:`absolute`,left:-2,bottom:`100%`,background:n,color:`#fff`,fontSize:10,fontWeight:700,fontFamily:`system-ui, sans-serif`,lineHeight:`14px`,padding:`0 4px`,borderRadius:3,whiteSpace:`nowrap`},children:`${e.label} ${r}%`})},`${e.label}-${t}`)})})}var jq=500;function Mq(e,t,n){let{motion:r,detection:a}=kK(e.trpcClient,t),o=(0,S.useRef)(0),s=(0,S.useRef)(0),c=(0,S.useRef)(0),l=(0,S.useRef)(!1),[,u]=(0,S.useState)(0),d=n?.audio??`off`,f=n?.audioDb??-30,p=n?.audioHoldSec??3,m=n?.motionHoldSec??0,h=n?.detectionHoldSec??3,g=n?.detectionClasses??[],_=g.join(`,`);if(Mz(w.MotionOnMotionChanged,e=>{let r=e.data;!r||r.deviceId!==t||!n?.motion||(r.detected===!0?(c.current=Date.now()+Math.max(1,m)*1e3,l.current=!0,u(e=>e+1)):r.detected===!1&&l.current&&(c.current=Date.now()+m*1e3,l.current=!1,u(e=>e+1)))}),Mz(w.PipelineAudioInferenceResult,e=>{let n=e.data;!n||n.deviceId!==t||d===`off`||(d===`sensor`?n.frame.detections.length>0:(n.frame.level?.dbfs??-1/0)>=f)&&(o.current=Date.now()+p*1e3,u(e=>e+1))}),(0,S.useEffect)(()=>{a&&a.detections.some(e=>g.length===0||g.includes(e.macroClass))&&(s.current=Date.now()+h*1e3,u(e=>e+1))},[a,h,_]),(0,S.useEffect)(()=>{let e=r!==null;(e||l.current)&&(c.current=Date.now()+m*1e3,e||u(e=>e+1)),l.current=e},[r,m]),(0,S.useEffect)(()=>{let e=setInterval(()=>u(e=>e+1),jq);return()=>clearInterval(e)},[]),!n?.enabled)return null;let v=Date.now();return n.detection&&v<s.current?`detection`:d!==`off`&&v<o.current?`audio`:n.motion&&(r!==null||v<c.current)?`motion`:null}var Nq={motion:`#DC2626`,audio:`#3B82F6`,detection:`#22C55E`},Pq=3500;function Fq(e){return e===`auto`?{kind:`adaptive`}:{kind:`profile`,profile:e===`medium`?`mid`:e}}function Iq({system:e,deviceId:t,name:n,online:r,quality:a,muted:o,paused:s,showName:c,audioActive:l,micActive:u,onTogglePause:d,onToggleAudio:f,onToggleMic:p,onOpen:m,ptzSupported:h,onPtz:g,highlight:_,showBoxes:v,reconnectSignal:y,posterUrl:b}){let{handleOffer:x,getIceServers:w,addIceCandidate:T,getIceCandidates:E,closeSession:D,getSessionState:ee}=AK(e.trpcClient,t),te=Mq(e,t,_),[O,ne]=(0,S.useState)(void 0);(0,S.useEffect)(()=>{if(b||s)return;let n=!1;return e.trpcClient.snapshot.getSnapshot.query({deviceId:t}).then(e=>{!n&&e?.base64&&ne(`data:${e.contentType??`image/jpeg`};base64,${e.base64}`)}).catch(()=>{}),()=>{n=!0}},[b,s,e,t]);let re=b??O,ie=(0,S.useMemo)(()=>Fq(a),[a]),ae=`grid:${t}:${a}`,oe=(0,S.useMemo)(()=>(e,t)=>x(ie,e,t),[x,ie]),se=(0,S.useMemo)(()=>(e,t,n)=>x(n,t,e),[x]),[k,A]=(0,S.useState)(!1),ce=(0,S.useRef)(null),le=()=>{ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>A(!1),Pq)},ue=()=>{A(!0),le()},de=()=>{A(e=>{let t=!e;return t&&le(),t})},j=e=>{e.stopPropagation(),ue()};return(0,S.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current)},[]),(0,C.jsxs)(`div`,{style:{position:`relative`,width:`100%`,height:`100%`,background:`#000`},children:[(0,C.jsx)(Cq,{onTap:de,children:s?(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fafaf9`},children:(0,C.jsx)(zq,{size:28})}):(0,C.jsx)(_K,{serverUrl:e.serverUrl,streamKey:ae,autoPlay:!0,muted:o,showControls:!1,className:`w-full h-full`,handleOffer:oe,reoffer:se,getSessionState:ee,getIceServers:w,addIceCandidate:T,getIceCandidates:E,closeSession:D,reconnectSignal:y,posterUrl:re,onClientNetworkSample:a===`auto`?n=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...n}).catch(()=>{})}:void 0},ae)}),v&&!s?(0,C.jsx)(Aq,{deviceId:t}):null,te&&(()=>{let e=_?.appearance,t=te===`motion`?e?.motionColor??Nq.motion:te===`audio`?e?.audioColor??Nq.audio:e?.detectionColor??Nq.detection;return(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,border:`${e?.thickness??3}px solid ${t}`,boxShadow:`inset 0 0 12px ${t}`,pointerEvents:`none`}})})(),(c||k)&&(0,C.jsxs)(`div`,{style:{position:`absolute`,left:0,right:0,top:0,display:`flex`,alignItems:`center`,gap:6,padding:`4px 8px`,background:`rgba(0,0,0,0.6)`,color:`#fafaf9`,fontSize:12,fontWeight:600,fontFamily:`system-ui, sans-serif`,pointerEvents:`none`,opacity:c||k?1:0,transition:`opacity 150ms ease`},children:[(0,C.jsx)(`span`,{style:{width:8,height:8,borderRadius:4,background:r?`#34d399`:`#71717a`}}),(0,C.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:n})]}),(0,C.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!k,transition:`opacity 150ms ease`,pointerEvents:`none`},children:[(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,pointerEvents:`none`},children:(0,C.jsx)(Lq,{label:s?`Play`:`Pause`,big:!0,enabled:k,onClick:e=>{j(e),d(t)},children:s?(0,C.jsx)(zq,{size:22}):(0,C.jsx)(Bq,{size:22})})}),(0,C.jsxs)(`div`,{style:{position:`absolute`,left:8,bottom:8,display:`flex`,gap:8,pointerEvents:`none`},children:[(0,C.jsx)(Lq,{label:l?`Mute`:`Listen`,active:l,enabled:k,onClick:e=>{j(e),f(t)},children:l?(0,C.jsx)(Vq,{size:18}):(0,C.jsx)(Hq,{size:18})}),(0,C.jsx)(Lq,{label:u?`Stop talk`:`Talk`,active:u,enabled:k,onClick:e=>{j(e),p(t)},children:(0,C.jsx)(Uq,{size:18,muted:!u})}),h&&g?(0,C.jsx)(Lq,{label:`PTZ`,enabled:k,onClick:e=>{j(e),g(t)},children:(0,C.jsx)(Gq,{size:18})}):null]}),(0,C.jsx)(`div`,{style:{position:`absolute`,right:8,bottom:8,pointerEvents:`none`},children:(0,C.jsx)(Lq,{label:`Open`,enabled:k,onClick:e=>{j(e),m(t)},children:(0,C.jsx)(Wq,{size:18})})})]})]})}function Lq({children:e,label:t,onClick:n,big:r=!1,active:a=!1,enabled:o=!0}){let s=r?52:40;return(0,C.jsx)(`button`,{type:`button`,"aria-label":t,onClick:n,style:{width:s,height:s,borderRadius:s/2,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:a?`rgba(59,130,246,0.85)`:`rgba(0,0,0,0.55)`,color:`#fafaf9`,cursor:`pointer`,padding:0,WebkitTapHighlightColor:`transparent`,pointerEvents:o?`auto`:`none`},children:e})}var Rq={fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`};function zq({size:e}){return(0,C.jsx)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,children:(0,C.jsx)(`polygon`,{points:`6 4 20 12 6 20 6 4`,fill:`currentColor`})})}function Bq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,children:[(0,C.jsx)(`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,fill:`currentColor`}),(0,C.jsx)(`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,fill:`currentColor`})]})}function Vq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`path`,{d:`M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07`})]})}function Hq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),(0,C.jsx)(`line`,{x1:`23`,y1:`9`,x2:`17`,y2:`15`}),(0,C.jsx)(`line`,{x1:`17`,y1:`9`,x2:`23`,y2:`15`})]})}function Uq({size:e,muted:t}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`path`,{d:`M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z`}),(0,C.jsx)(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2M12 19v4`}),t&&(0,C.jsx)(`line`,{x1:`3`,y1:`3`,x2:`21`,y2:`21`})]})}function Wq({size:e}){return(0,C.jsx)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:(0,C.jsx)(`path`,{d:`M15 3h6v6M21 3l-9 9M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5`})})}function Gq({size:e}){return(0,C.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,...Rq,children:[(0,C.jsx)(`path`,{d:`M12 2v20M2 12h20`}),(0,C.jsx)(`path`,{d:`M12 2l-3 3M12 2l3 3M12 22l-3-3M12 22l3-3M2 12l3-3M2 12l3 3M22 12l-3-3M22 12l-3 3`})]})}function Kq({message:e}){return(0,S.useEffect)(()=>hq(pq(`error`,e)),[e]),(0,C.jsxs)(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Grid embed config error: `,e]})}function qq({system:e,config:t}){let[n,r]=(0,S.useState)(()=>new Set(t.audioOnIds??[])),a=aq(),o=(0,S.useRef)(a.setActiveMic);o.current=a.setActiveMic;let[s,c]=(0,S.useState)(()=>new Set(t.pausedIds??[])),[l,u]=(0,S.useState)(t.highlight),[d,f]=(0,S.useState)(t.activeOnly??!1),[p,m]=(0,S.useState)(t.showBoxes??!1),h=cq(t.devices,l),g=(0,S.useMemo)(()=>d?t.devices.filter(e=>h.has(e)):t.devices,[d,t.devices,h]),[_,v]=(0,S.useState)(t.quality),[y,b]=(0,S.useState)(t.layout),[x,w]=(0,S.useState)(t.showName),[T,E]=(0,S.useState)(0),[D,ee]=(0,S.useState)(()=>t.snapshots??{}),te=(0,S.useMemo)(()=>new Set(t.ptzIds??[]),[t.ptzIds]),[O,ne]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),[re,ie]=(0,S.useState)({});(0,S.useEffect)(()=>{let t=!1;return e.trpcClient.deviceManager.listAll.query({}).then(e=>{if(t)return;let n={};for(let t of e)n[t.id]={name:t.name??`Camera ${t.id}`,online:t.online??!1};ie(n)}).catch(()=>{}),()=>{t=!0}},[e]),(0,S.useEffect)(()=>(window.__camstackGrid={setAudioOn:e=>r(new Set(e)),setMutedAll:e=>{e&&r(new Set)},setActiveMic:e=>o.current(e),setHighlight:e=>u(e),setActiveOnly:e=>f(e),setShowBoxes:e=>m(e),setPaused:e=>c(new Set(e)),setQuality:e=>v(e),setLayout:e=>b(e),setShowName:w,setShowBadges:()=>{},setSnapshots:e=>ee(e),fit:(e,t)=>ne({w:e,h:t}),reconnect:()=>E(e=>e+1)},hq(pq(`ready`)),()=>{window.__camstackGrid&&delete window.__camstackGrid}),[]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackGrid;if(t)switch(e.kind){case`setAudioOn`:t.setAudioOn(e.value);break;case`setMutedAll`:t.setMutedAll(e.value);break;case`setActiveMic`:t.setActiveMic(e.value);break;case`setHighlight`:t.setHighlight(e.value);break;case`setActiveOnly`:t.setActiveOnly(e.value);break;case`setShowBoxes`:t.setShowBoxes(e.value===!0);break;case`setPaused`:t.setPaused(e.value);break;case`setQuality`:t.setQuality(e.value);break;case`setLayout`:t.setLayout(e.value);break;case`setShowName`:t.setShowName(e.value);break;case`setShowBadges`:t.setShowBadges(e.value);break;case`setSnapshots`:t.setSnapshots(e.value);break;case`fit`:t.fit(e.w,e.h);break;case`reconnect`:t.reconnect();break;default:break}}),[]);let ae=(0,S.useMemo)(()=>iq(g.length,O.w,O.h,y),[g.length,O.w,O.h,y]),oe=(0,S.useRef)(null);return(0,S.useEffect)(()=>{let e=oe.current;if(!e)return;let t=[];e.querySelectorAll(`[data-device-id]`).forEach(e=>{let n=Number(e.dataset.deviceId),r=e.getBoundingClientRect();t.push({deviceId:n,rect:{x:r.x,y:r.y,w:r.width,h:r.height}})}),t.length&&hq(mq(t))},[ae,g]),(0,C.jsxs)(`div`,{ref:oe,style:{position:`fixed`,inset:0,background:`#000`,display:`flex`,flexWrap:`wrap`,alignItems:`center`,justifyContent:`center`},children:[d&&g.length===0&&(0,C.jsx)(`div`,{style:{color:`#a1a1aa`,fontFamily:`system-ui, sans-serif`,fontSize:14,padding:24,textAlign:`center`},children:`No active cameras`}),g.map(t=>(0,C.jsx)(`div`,{"data-device-id":t,style:{width:ae.cellW,height:ae.cellH},children:(0,C.jsx)(Iq,{system:e,deviceId:t,name:re[t]?.name??`Camera ${t}`,online:re[t]?.online??!1,quality:_,muted:!n.has(t),paused:s.has(t),showName:x,audioActive:n.has(t),micActive:a.activeMicId===t,onTogglePause:e=>hq(dq(e)),onToggleAudio:e=>hq(uq(e)),onToggleMic:a.toggleMic,onOpen:e=>hq(lq(e)),ptzSupported:te.has(t),onPtz:e=>hq(fq(e)),highlight:l,showBoxes:p,reconnectSignal:T,posterUrl:D[String(t)]})},t))]})}function Jq(){let e=VK(`grid`,()=>window.__CAMSTACK_GRID__,FK,nq),t=(0,S.useMemo)(()=>e===null||!e.ok?null:{system:XA({serverUrl:e.config.serverUrl,token:e.config.token}),queryClient:new hE({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}})},[e]);return(0,S.useEffect)(()=>{if(t)return()=>t.system.close()},[t]),e===null?null:e.ok?t?(0,C.jsx)(Az,{system:t.system,children:(0,C.jsx)(vE,{client:t.queryClient,children:(0,C.jsx)($.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:(0,C.jsx)(qq,{system:t.system,config:e.config})})})}):(0,C.jsx)(Kq,{message:`Failed to initialise the grid embed`}):(0,C.jsx)(Kq,{message:e.error})}var Yq=class{capacity;dispose;map=new Map;constructor(e,t){this.capacity=e,this.dispose=t}has(e){return this.map.has(e)}get(e){if(!this.map.has(e))return;let t=this.map.get(e);return this.map.delete(e),t!==void 0&&this.map.set(e,t),t}set(e,t){if(this.map.has(e)){let t=this.map.get(e);this.map.delete(e),t!==void 0&&this.dispose?.(t)}for(this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;let t=this.map.get(e);this.map.delete(e),t!==void 0&&this.dispose?.(t)}}clear(){this.map.forEach(e=>this.dispose?.(e)),this.map.clear()}};function Xq(e){try{return new URL(e).toString()}catch{let t=typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost`;return new URL(e,t).toString()}}function Zq(e,t){return new URL(t,e).toString()}function Qq(e){let t=(e.split(`/`).pop()??``).match(/^(\d+)-(\d+)(?:-\d+)?\.m4s$/);return t?{startMs:Number(t[1]),durMs:Number(t[2])}:null}function $q(e,t){let n=e.split(`
|
|
112
112
|
`).map(e=>e.trim());for(let e of n)if(/low\.m3u8/i.test(e))return Zq(t,e);let r=null;for(let e=0;e<n.length;e++){let a=n[e],o=n[e+1];a&&a.startsWith(`#EXT-X-STREAM-INF`)&&o&&!o.startsWith(`#`)&&(r=Zq(t,o))}return r}async function eJ(e,t){let n=await fetch(e,t?{headers:t}:void 0);if(!n.ok)throw Error(`playlist fetch ${n.status} for ${e}`);return n.text()}async function tJ(e,t){let n=Xq(e),r=$q(await eJ(n,t),n);if(!r)return[];let a=await eJ(r,t),o=[];for(let e of a.split(`
|
|
113
113
|
`).map(e=>e.trim())){if(!e||e.startsWith(`#`))continue;let t=Zq(r,e),n=Qq(t);n&&o.push({uri:t,startMs:n.startMs,durMs:n.durMs})}return o.sort((e,t)=>e.startMs-t.startMs),o}function nJ(e,t){let n=e.length;if(n===0)return 0;let r=0,a=n-1,o=-1;for(;r<=a;){let n=r+a>>1,s=e[n];if(!s)break;s.startMs<=t?(o=n,r=n+1):a=n-1}if(o===-1)return 0;let s=e[o];if(s&&t<s.startMs+s.durMs)return o;let c=e[o+1];return s&&c?Math.abs(s.startMs-t)<=Math.abs(c.startMs-t)?o:o+1:o}function rJ(e,t){return e.length===0?null:e[nJ(e,t)]??null}function iJ(e,t,n,r){if(e.length===0||r<=0)return[];let a=nJ(e,t),o=[];if(n===`forward`)for(let t=a+1;t<=a+r&&t<e.length;t++){let n=e[t];n&&o.push(n)}else for(let t=a-1;t>=a-r&&t>=0;t--){let n=e[t];n&&o.push(n)}return o}function aJ(e){return e instanceof Error&&e.unsupported===!0}var oJ=class{deps;generation=0;inflight=null;lastEpoch=0;lastSegStart=null;unsupported=!1;bytes;frames;prefetchCount;subSegmentGranularityMs;prefetching=new Map;constructor(e){this.deps=e,this.bytes=new Yq(e.byteCacheSize??24),this.frames=new Yq(e.frameCacheSize??16,e=>e.close()),this.prefetchCount=e.prefetchCount??3,this.subSegmentGranularityMs=e.subSegmentGranularityMs??1e3}get codecUnsupported(){return this.unsupported}clearFrames(){this.frames.clear()}dispose(){this.inflight?.abort();for(let e of this.prefetching.values())e.abort();this.prefetching.clear(),this.frames.clear(),this.bytes.clear()}async scrubTo(e){if(this.unsupported)return;let t=e>=this.lastEpoch?`forward`:`backward`;this.lastEpoch=e;let n=++this.generation;this.inflight?.abort();let r=new AbortController;this.inflight=r;let a=performance.now(),o=await this.deps.ensureIndex(e),s=rJ(o,e);if(!s)return;let c=this.deps.decodeAt!==void 0&&this.lastSegStart===s.startMs,l=Math.min(Math.max(e-s.startMs,0),Math.max(s.durMs-1,0)),u=c?Math.floor(l/this.subSegmentGranularityMs)*this.subSegmentGranularityMs:0,d=s.startMs+u,f=this.frames.get(d);if(f){n===this.generation&&(this.deps.draw(f),this.deps.onTiming?.({epochMs:e,cached:!0,fetchMs:0,decodeMs:0,totalMs:performance.now()-a}),this.maybePrefetch(o,e,t,s.startMs));return}try{let l=performance.now(),f=await this.getBytes(s.uri,r.signal),p=performance.now()-l,m=performance.now(),h=c&&this.deps.decodeAt?await this.deps.decodeAt(f,u):await this.deps.decode(f),g=performance.now()-m;if(n!==this.generation){h.close();return}this.frames.set(d,h),this.deps.draw(h),this.deps.onTiming?.({epochMs:e,cached:!1,fetchMs:p,decodeMs:g,totalMs:performance.now()-a}),this.maybePrefetch(o,e,t,s.startMs)}catch(e){if(r.signal.aborted)return;throw aJ(e)&&(this.unsupported=!0),e}}async getBytes(e,t){let n=this.bytes.get(e);if(n)return n;let r=await this.deps.fetchBytes(e,t);return this.bytes.set(e,r),r}maybePrefetch(e,t,n,r){let a=this.lastSegStart;this.lastSegStart=r,!(a===null||r===a)&&this.schedulePrefetch(e,t,n)}schedulePrefetch(e,t,n){let r=iJ(e,t,n,this.prefetchCount);for(let e of r){if(this.bytes.has(e.uri)||this.prefetching.has(e.uri))continue;let t=new AbortController;this.prefetching.set(e.uri,t),this.deps.fetchBytes(e.uri,t.signal).then(t=>{this.bytes.set(e.uri,t),this.prefetching.delete(e.uri)}).catch(()=>{this.prefetching.delete(e.uri)})}}},sJ=u(s((e=>{var t=(function(){var e=new Date,n=4,r=3,a=2,o=1,s=n;return{setLogLevel:function(e){s=e==this.debug?o:e==this.info?a:e==this.warn?r:(this.error,n)},debug:function(n,r){console.debug===void 0&&(console.debug=console.log),o>=s&&console.debug(`[`+t.getDurationString(new Date-e,1e3)+`]`,`[`+n+`]`,r)},log:function(e,t){this.debug(e.msg)},info:function(n,r){a>=s&&console.info(`[`+t.getDurationString(new Date-e,1e3)+`]`,`[`+n+`]`,r)},warn:function(n,a){r>=s&&console.warn(`[`+t.getDurationString(new Date-e,1e3)+`]`,`[`+n+`]`,a)},error:function(r,a){n>=s&&console.error(`[`+t.getDurationString(new Date-e,1e3)+`]`,`[`+r+`]`,a)}}})();t.getDurationString=function(e,t){var n;function r(e,t){for(var n=(``+e).split(`.`);n[0].length<t;)n[0]=`0`+n[0];return n.join(`.`)}e<0?(n=!0,e=-e):n=!1;var a=e/(t||1),o=Math.floor(a/3600);a-=o*3600;var s=Math.floor(a/60);a-=s*60;var c=a*1e3;return a=Math.floor(a),c-=a*1e3,c=Math.floor(c),(n?`-`:``)+o+`:`+r(s,2)+`:`+r(a,2)+`.`+r(c,3)},t.printRanges=function(e){var n=e.length;if(n>0){for(var r=``,a=0;a<n;a++)a>0&&(r+=`,`),r+=`[`+t.getDurationString(e.start(a))+`,`+t.getDurationString(e.end(a))+`]`;return r}else return`(empty)`},e!==void 0&&(e.Log=t);var n=function(e){if(e instanceof ArrayBuffer)this.buffer=e,this.dataview=new DataView(e);else throw`Needs an array buffer`;this.position=0};n.prototype.getPosition=function(){return this.position},n.prototype.getEndPosition=function(){return this.buffer.byteLength},n.prototype.getLength=function(){return this.buffer.byteLength},n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.buffer.byteLength,e));return this.position=isNaN(t)||!isFinite(t)?0:t,!0},n.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},n.prototype.readAnyInt=function(e,t){var n=0;if(this.position+e<=this.buffer.byteLength){switch(e){case 1:n=t?this.dataview.getInt8(this.position):this.dataview.getUint8(this.position);break;case 2:n=t?this.dataview.getInt16(this.position):this.dataview.getUint16(this.position);break;case 3:if(t)throw`No method for reading signed 24 bits values`;n=this.dataview.getUint8(this.position)<<16,n|=this.dataview.getUint8(this.position+1)<<8,n|=this.dataview.getUint8(this.position+2);break;case 4:n=t?this.dataview.getInt32(this.position):this.dataview.getUint32(this.position);break;case 8:if(t)throw`No method for reading signed 64 bits values`;n=this.dataview.getUint32(this.position)<<32,n|=this.dataview.getUint32(this.position+4);break;default:throw`readInt method not implemented for size: `+e}return this.position+=e,n}else throw`Not enough bytes in buffer`},n.prototype.readUint8=function(){return this.readAnyInt(1,!1)},n.prototype.readUint16=function(){return this.readAnyInt(2,!1)},n.prototype.readUint24=function(){return this.readAnyInt(3,!1)},n.prototype.readUint32=function(){return this.readAnyInt(4,!1)},n.prototype.readUint64=function(){return this.readAnyInt(8,!1)},n.prototype.readString=function(e){if(this.position+e<=this.buffer.byteLength){for(var t=``,n=0;n<e;n++)t+=String.fromCharCode(this.readUint8());return t}else throw`Not enough bytes in buffer`},n.prototype.readCString=function(){for(var e=[];;){var t=this.readUint8();if(t!==0)e.push(t);else break}return String.fromCharCode.apply(null,e)},n.prototype.readInt8=function(){return this.readAnyInt(1,!0)},n.prototype.readInt16=function(){return this.readAnyInt(2,!0)},n.prototype.readInt32=function(){return this.readAnyInt(4,!0)},n.prototype.readInt64=function(){return this.readAnyInt(8,!1)},n.prototype.readUint8Array=function(e){for(var t=new Uint8Array(e),n=0;n<e;n++)t[n]=this.readUint8();return t},n.prototype.readInt16Array=function(e){for(var t=new Int16Array(e),n=0;n<e;n++)t[n]=this.readInt16();return t},n.prototype.readUint16Array=function(e){for(var t=new Int16Array(e),n=0;n<e;n++)t[n]=this.readUint16();return t},n.prototype.readUint32Array=function(e){for(var t=new Uint32Array(e),n=0;n<e;n++)t[n]=this.readUint32();return t},n.prototype.readInt32Array=function(e){for(var t=new Int32Array(e),n=0;n<e;n++)t[n]=this.readInt32();return t},e!==void 0&&(e.MP4BoxStream=n);var r=function(e,t,n){this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:typeof e==`object`?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0),this.position=0,this.endianness=n??r.LITTLE_ENDIAN};r.prototype={},r.prototype.getPosition=function(){return this.position},r.prototype._realloc=function(e){if(this._dynamicSize){var t=this._byteOffset+this.position+e,n=this._buffer.byteLength;if(t<=n){t>this._byteLength&&(this._byteLength=t);return}for(n<1&&(n=1);t>n;)n*=2;var r=new ArrayBuffer(n),a=new Uint8Array(this._buffer);new Uint8Array(r,0,a.length).set(a),this.buffer=r,this._byteLength=t}},r.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength),t=new Uint8Array(e),n=new Uint8Array(this._buffer,0,t.length);t.set(n),this.buffer=e}},r.BIG_ENDIAN=!1,r.LITTLE_ENDIAN=!0,r.prototype._byteLength=0,Object.defineProperty(r.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(r.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}}),r.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t},r.prototype.isEof=function(){return this.position>=this._byteLength},r.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},r.prototype.readInt32Array=function(e,t){e??=this.byteLength-this.position/4;var n=new Int32Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readInt16Array=function(e,t){e??=this.byteLength-this.position/2;var n=new Int16Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readInt8Array=function(e){e??=this.byteLength-this.position;var t=new Int8Array(e);return r.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},r.prototype.readUint32Array=function(e,t){e??=this.byteLength-this.position/4;var n=new Uint32Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readUint16Array=function(e,t){e??=this.byteLength-this.position/2;var n=new Uint16Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readUint8Array=function(e){e??=this.byteLength-this.position;var t=new Uint8Array(e);return r.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},r.prototype.readFloat64Array=function(e,t){e??=this.byteLength-this.position/8;var n=new Float64Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readFloat32Array=function(e,t){e??=this.byteLength-this.position/4;var n=new Float32Array(e);return r.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),r.arrayToNative(n,t??this.endianness),this.position+=n.byteLength,n},r.prototype.readInt32=function(e){var t=this._dataView.getInt32(this.position,e??this.endianness);return this.position+=4,t},r.prototype.readInt16=function(e){var t=this._dataView.getInt16(this.position,e??this.endianness);return this.position+=2,t},r.prototype.readInt8=function(){var e=this._dataView.getInt8(this.position);return this.position+=1,e},r.prototype.readUint32=function(e){var t=this._dataView.getUint32(this.position,e??this.endianness);return this.position+=4,t},r.prototype.readUint16=function(e){var t=this._dataView.getUint16(this.position,e??this.endianness);return this.position+=2,t},r.prototype.readUint8=function(){var e=this._dataView.getUint8(this.position);return this.position+=1,e},r.prototype.readFloat32=function(e){var t=this._dataView.getFloat32(this.position,e??this.endianness);return this.position+=4,t},r.prototype.readFloat64=function(e){var t=this._dataView.getFloat64(this.position,e??this.endianness);return this.position+=8,t},r.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,r.memcpy=function(e,t,n,r,a){var o=new Uint8Array(e,t,a),s=new Uint8Array(n,r,a);o.set(s)},r.arrayToNative=function(e,t){return t==this.endianness?e:this.flipArrayEndianness(e)},r.nativeToEndian=function(e,t){return this.endianness==t?e:this.flipArrayEndianness(e)},r.flipArrayEndianness=function(e){for(var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=0;n<e.byteLength;n+=e.BYTES_PER_ELEMENT)for(var r=n+e.BYTES_PER_ELEMENT-1,a=n;r>a;r--,a++){var o=t[a];t[a]=t[r],t[r]=o}return e},r.prototype.failurePosition=0,String.fromCharCodeUint8=function(e){for(var t=[],n=0;n<e.length;n++)t[n]=e[n];return String.fromCharCode.apply(null,t)},r.prototype.readString=function(e,t){return t==null||t==`ASCII`?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(e??this.byteLength-this.position)]):new TextDecoder(t).decode(this.mapUint8Array(e))},r.prototype.readCString=function(e){var t=this.byteLength-this.position,n=new Uint8Array(this._buffer,this._byteOffset+this.position),r=t;e!=null&&(r=Math.min(e,t));for(var a=0;a<r&&n[a]!==0;a++);var o=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(a)]);return e==null?a!=t&&(this.position+=1):this.position+=r-a,o};var a=2**32;r.prototype.readInt64=function(){return this.readInt32()*a+this.readUint32()},r.prototype.readUint64=function(){return this.readUint32()*a+this.readUint32()},r.prototype.readInt64=function(){return this.readUint32()*a+this.readUint32()},r.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},e!==void 0&&(e.DataStream=r),r.prototype.save=function(e){var t=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var n=window.URL.createObjectURL(t),r=document.createElement(`a`);document.body.appendChild(r),r.setAttribute(`href`,n),r.setAttribute(`download`,e),r.setAttribute(`target`,`_self`),r.click(),window.URL.revokeObjectURL(n)}else throw`DataStream.save: Can't create object URL.`},r.prototype._dynamicSize=!0,Object.defineProperty(r.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){e||this._trimAlloc(),this._dynamicSize=e}}),r.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e),n=new Uint8Array(t),r=new Uint8Array(this._buffer,e,n.length);n.set(r),this.buffer=t,this.position-=e},r.prototype.writeInt32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt32Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeInt32(e[n],t)},r.prototype.writeInt16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Int16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt16Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeInt16(e[n],t)},r.prototype.writeInt8Array=function(e){if(this._realloc(e.length*1),e instanceof Int8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt8Array(e.length);else for(var t=0;t<e.length;t++)this.writeInt8(e[t])},r.prototype.writeUint32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Uint32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint32Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeUint32(e[n],t)},r.prototype.writeUint16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Uint16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint16Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeUint16(e[n],t)},r.prototype.writeUint8Array=function(e){if(this._realloc(e.length*1),e instanceof Uint8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint8Array(e.length);else for(var t=0;t<e.length;t++)this.writeUint8(e[t])},r.prototype.writeFloat64Array=function(e,t){if(this._realloc(e.length*8),e instanceof Float64Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat64Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeFloat64(e[n],t)},r.prototype.writeFloat32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Float32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat32Array(e.length,t);else for(var n=0;n<e.length;n++)this.writeFloat32(e[n],t)},r.prototype.writeInt32=function(e,t){this._realloc(4),this._dataView.setInt32(this.position,e,t??this.endianness),this.position+=4},r.prototype.writeInt16=function(e,t){this._realloc(2),this._dataView.setInt16(this.position,e,t??this.endianness),this.position+=2},r.prototype.writeInt8=function(e){this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1},r.prototype.writeUint32=function(e,t){this._realloc(4),this._dataView.setUint32(this.position,e,t??this.endianness),this.position+=4},r.prototype.writeUint16=function(e,t){this._realloc(2),this._dataView.setUint16(this.position,e,t??this.endianness),this.position+=2},r.prototype.writeUint8=function(e){this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1},r.prototype.writeFloat32=function(e,t){this._realloc(4),this._dataView.setFloat32(this.position,e,t??this.endianness),this.position+=4},r.prototype.writeFloat64=function(e,t){this._realloc(8),this._dataView.setFloat64(this.position,e,t??this.endianness),this.position+=8},r.prototype.writeUCS2String=function(e,t,n){n??=e.length;for(var r=0;r<e.length&&r<n;r++)this.writeUint16(e.charCodeAt(r),t);for(;r<n;r++)this.writeUint16(0)},r.prototype.writeString=function(e,t,n){var r=0;if(t==null||t==`ASCII`)if(n!=null){var a=Math.min(e.length,n);for(r=0;r<a;r++)this.writeUint8(e.charCodeAt(r));for(;r<n;r++)this.writeUint8(0)}else for(r=0;r<e.length;r++)this.writeUint8(e.charCodeAt(r));else this.writeUint8Array(new TextEncoder(t).encode(e.substring(0,n)))},r.prototype.writeCString=function(e,t){var n=0;if(t!=null){var r=Math.min(e.length,t);for(n=0;n<r;n++)this.writeUint8(e.charCodeAt(n));for(;n<t;n++)this.writeUint8(0)}else{for(n=0;n<e.length;n++)this.writeUint8(e.charCodeAt(n));this.writeUint8(0)}},r.prototype.writeStruct=function(e,t){for(var n=0;n<e.length;n+=2){var r=e[n+1];this.writeType(r,t[e[n]],t)}},r.prototype.writeType=function(e,t,n){var a;if(typeof e==`function`)return e(this,t);if(typeof e==`object`&&!(e instanceof Array))return e.set(this,t,n);var o=null,s=`ASCII`,c=this.position;switch(typeof e==`string`&&/:/.test(e)&&(a=e.split(`:`),e=a[0],o=parseInt(a[1])),typeof e==`string`&&/,/.test(e)&&(a=e.split(`,`),e=a[0],s=parseInt(a[1])),e){case`uint8`:this.writeUint8(t);break;case`int8`:this.writeInt8(t);break;case`uint16`:this.writeUint16(t,this.endianness);break;case`int16`:this.writeInt16(t,this.endianness);break;case`uint32`:this.writeUint32(t,this.endianness);break;case`int32`:this.writeInt32(t,this.endianness);break;case`float32`:this.writeFloat32(t,this.endianness);break;case`float64`:this.writeFloat64(t,this.endianness);break;case`uint16be`:this.writeUint16(t,r.BIG_ENDIAN);break;case`int16be`:this.writeInt16(t,r.BIG_ENDIAN);break;case`uint32be`:this.writeUint32(t,r.BIG_ENDIAN);break;case`int32be`:this.writeInt32(t,r.BIG_ENDIAN);break;case`float32be`:this.writeFloat32(t,r.BIG_ENDIAN);break;case`float64be`:this.writeFloat64(t,r.BIG_ENDIAN);break;case`uint16le`:this.writeUint16(t,r.LITTLE_ENDIAN);break;case`int16le`:this.writeInt16(t,r.LITTLE_ENDIAN);break;case`uint32le`:this.writeUint32(t,r.LITTLE_ENDIAN);break;case`int32le`:this.writeInt32(t,r.LITTLE_ENDIAN);break;case`float32le`:this.writeFloat32(t,r.LITTLE_ENDIAN);break;case`float64le`:this.writeFloat64(t,r.LITTLE_ENDIAN);break;case`cstring`:this.writeCString(t,o);break;case`string`:this.writeString(t,s,o);break;case`u16string`:this.writeUCS2String(t,this.endianness,o);break;case`u16stringle`:this.writeUCS2String(t,r.LITTLE_ENDIAN,o);break;case`u16stringbe`:this.writeUCS2String(t,r.BIG_ENDIAN,o);break;default:if(e.length==3){for(var l=e[1],u=0;u<t.length;u++)this.writeType(l,t[u]);break}else{this.writeStruct(e,t);break}}o!=null&&(this.position=c,this._realloc(o),this.position=c+o)},r.prototype.writeUint64=function(e){var t=Math.floor(e/a);this.writeUint32(t),this.writeUint32(e&4294967295)},r.prototype.writeUint24=function(e){this.writeUint8((e&16711680)>>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)},r.prototype.adjustUint32=function(e,t){var n=this.position;this.seek(e),this.writeUint32(t),this.seek(n)},r.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var n=new Int32Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*4,n},r.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var n=new Int16Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*2,n},r.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},r.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var n=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*4,n},r.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var n=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*2,n},r.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var n=new Float64Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*8,n},r.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var n=new Float32Array(this._buffer,this.byteOffset+this.position,e);return r.arrayToNative(n,t??this.endianness),this.position+=e*4,n};var o=function(e){this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)};o.prototype=new r(new ArrayBuffer,0,r.BIG_ENDIAN),o.prototype.initialized=function(){var e;return this.bufferIndex>-1?!0:this.buffers.length>0?(e=this.buffers[0],e.fileStart===0?(this.buffer=e,this.bufferIndex=0,t.debug(`MultiBufferStream`,`Stream ready for parsing`),!0):(t.warn(`MultiBufferStream`,`The first buffer should have a fileStart of 0`),this.logBufferLevel(),!1)):(t.warn(`MultiBufferStream`,`No buffer to start parsing from`),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(e,n){t.debug(`ArrayBuffer`,`Trying to create a new buffer of size: `+(e.byteLength+n.byteLength));var r=new Uint8Array(e.byteLength+n.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(n),e.byteLength),r.buffer},o.prototype.reduceBuffer=function(e,t,n){var r=new Uint8Array(n);return r.set(new Uint8Array(e,t,n)),r.buffer.fileStart=e.fileStart+t,r.buffer.usedBytes=0,r.buffer},o.prototype.insertBuffer=function(e){for(var n=!0,r=0;r<this.buffers.length;r++){var a=this.buffers[r];if(e.fileStart<=a.fileStart){if(e.fileStart===a.fileStart)if(e.byteLength>a.byteLength){this.buffers.splice(r,1),r--;continue}else t.warn(`MultiBufferStream`,`Buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`) already appended, ignoring`);else e.fileStart+e.byteLength<=a.fileStart||(e=this.reduceBuffer(e,0,a.fileStart-e.fileStart)),t.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.splice(r,0,e),r===0&&(this.buffer=e);n=!1;break}else if(e.fileStart<a.fileStart+a.byteLength){var o=a.fileStart+a.byteLength-e.fileStart,s=e.byteLength-o;if(s>0)e=this.reduceBuffer(e,o,s);else{n=!1;break}}}n&&(t.debug(`MultiBufferStream`,`Appending new buffer (fileStart: `+e.fileStart+` - Length: `+e.byteLength+`)`),this.buffers.push(e),r===0&&(this.buffer=e))},o.prototype.logBufferLevel=function(e){var n,r,a,o,s=[],c,l=``;for(a=0,o=0,n=0;n<this.buffers.length;n++)r=this.buffers[n],n===0?(c={},s.push(c),c.start=r.fileStart,c.end=r.fileStart+r.byteLength,l+=`[`+c.start+`-`):c.end===r.fileStart?c.end=r.fileStart+r.byteLength:(c={},c.start=r.fileStart,l+=s[s.length-1].end-1+`], [`+c.start+`-`,c.end=r.fileStart+r.byteLength,s.push(c)),a+=r.usedBytes,o+=r.byteLength;s.length>0&&(l+=c.end-1+`]`);var u=e?t.info:t.debug;this.buffers.length===0?u(`MultiBufferStream`,`No more buffer in memory`):u(`MultiBufferStream`,``+this.buffers.length+` stored buffer(s) (`+a+`/`+o+` bytes), continuous ranges: `+l)},o.prototype.cleanBuffers=function(){var e,n;for(e=0;e<this.buffers.length;e++)n=this.buffers[e],n.usedBytes===n.byteLength&&(t.debug(`MultiBufferStream`,`Removing buffer #`+e),this.buffers.splice(e,1),e--)},o.prototype.mergeNextBuffer=function(){var e;if(this.bufferIndex+1<this.buffers.length)if(e=this.buffers[this.bufferIndex+1],e.fileStart===this.buffer.fileStart+this.buffer.byteLength){var n=this.buffer.byteLength,r=this.buffer.usedBytes,a=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,e),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=r,this.buffer.fileStart=a,t.debug(`ISOFile`,`Concatenating buffer for box parsing (length: `+n+`->`+this.buffer.byteLength+`)`),!0}else return!1;else return!1},o.prototype.findPosition=function(e,n,r){var a,o=null,s=-1;for(a=e===!0?0:this.bufferIndex;a<this.buffers.length&&(o=this.buffers[a],o.fileStart<=n);)s=a,r&&(o.fileStart+o.byteLength<=n?o.usedBytes=o.byteLength:o.usedBytes=n-o.fileStart,this.logBufferLevel()),a++;return s===-1?-1:(o=this.buffers[s],o.fileStart+o.byteLength>=n?(t.debug(`MultiBufferStream`,`Found position in existing buffer #`+s),s):-1)},o.prototype.findEndContiguousBuf=function(e){var t,n,r,a=e===void 0?this.bufferIndex:e;if(n=this.buffers[a],this.buffers.length>a+1)for(t=a+1;t<this.buffers.length&&(r=this.buffers[t],r.fileStart===n.fileStart+n.byteLength);t++)n=r;return n.fileStart+n.byteLength},o.prototype.getEndFilePositionAfter=function(e){var t=this.findPosition(!0,e,!1);return t===-1?e:this.findEndContiguousBuf(t)},o.prototype.addUsedBytes=function(e){this.buffer.usedBytes+=e,this.logBufferLevel()},o.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},o.prototype.seek=function(e,n,r){var a=this.findPosition(n,e,r);return a===-1?(t.debug(`MultiBufferStream`,`Position `+e+` not found in buffered data`),!1):(this.buffer=this.buffers[a],this.bufferIndex=a,this.position=e-this.buffer.fileStart,t.debug(`MultiBufferStream`,`Repositioning parser at buffer position: `+this.position),!0)},o.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw`Error accessing position in the MultiBufferStream`;return this.buffers[this.bufferIndex].fileStart+this.position},o.prototype.getLength=function(){return this.byteLength},o.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw`Error accessing position in the MultiBufferStream`;return this.buffers[this.bufferIndex].fileStart+this.byteLength},e!==void 0&&(e.MultiBufferStream=o);var s=function(){var e=3,n=4,r=5,a=6,o=[];o[e]=`ES_Descriptor`,o[n]=`DecoderConfigDescriptor`,o[r]=`DecoderSpecificInfo`,o[a]=`SLConfigDescriptor`,this.getDescriptorName=function(e){return o[e]};var s=this,c={};return this.parseOneDescriptor=function(e){var n=0,r=0,a=e.readUint8(),s,l;for(n++,l=e.readUint8(),n++;l&128;)r=(r<<7)+(l&127),l=e.readUint8(),n++;return r=(r<<7)+(l&127),t.debug(`MPEG4DescriptorParser`,`Found `+(o[a]||`Descriptor `+a)+`, size `+r+` at position `+e.getPosition()),s=o[a]?new c[o[a]](r):new c.Descriptor(r),s.parse(e),s},c.Descriptor=function(e,t){this.tag=e,this.size=t,this.descs=[]},c.Descriptor.prototype.parse=function(e){this.data=e.readUint8Array(this.size)},c.Descriptor.prototype.findDescriptor=function(e){for(var t=0;t<this.descs.length;t++)if(this.descs[t].tag==e)return this.descs[t];return null},c.Descriptor.prototype.parseRemainingDescriptors=function(e){for(var t=e.position;e.position<t+this.size;){var n=s.parseOneDescriptor(e);this.descs.push(n)}},c.ES_Descriptor=function(t){c.Descriptor.call(this,e,t)},c.ES_Descriptor.prototype=new c.Descriptor,c.ES_Descriptor.prototype.parse=function(e){if(this.ES_ID=e.readUint16(),this.flags=e.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=e.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var t=e.readUint8();this.URL=e.readString(t),this.size-=t+1}else this.URL=``;this.flags&32?(this.OCR_ES_ID=e.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(e)},c.ES_Descriptor.prototype.getOTI=function(e){var t=this.findDescriptor(n);return t?t.oti:0},c.ES_Descriptor.prototype.getAudioConfig=function(e){var t=this.findDescriptor(n);if(!t)return null;var a=t.findDescriptor(r);if(a&&a.data){var o=(a.data[0]&248)>>3;return o===31&&a.data.length>=2&&(o=32+((a.data[0]&7)<<3)+((a.data[1]&224)>>5)),o}else return null},c.DecoderConfigDescriptor=function(e){c.Descriptor.call(this,n,e)},c.DecoderConfigDescriptor.prototype=new c.Descriptor,c.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8(),this.streamType=e.readUint8(),this.upStream=(this.streamType>>1&1)!=0,this.streamType>>>=2,this.bufferSize=e.readUint24(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32(),this.size-=13,this.parseRemainingDescriptors(e)},c.DecoderSpecificInfo=function(e){c.Descriptor.call(this,r,e)},c.DecoderSpecificInfo.prototype=new c.Descriptor,c.SLConfigDescriptor=function(e){c.Descriptor.call(this,a,e)},c.SLConfigDescriptor.prototype=new c.Descriptor,this};e!==void 0&&(e.MPEG4DescriptorParser=s);var c={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:[{type:`mdat`,name:`MediaDataBox`},{type:`idat`,name:`ItemDataBox`},{type:`free`,name:`FreeSpaceBox`},{type:`skip`,name:`FreeSpaceBox`},{type:`meco`,name:`AdditionalMetadataContainerBox`},{type:`strk`,name:`SubTrackBox`}],FULL_BOXES:[{type:`hmhd`,name:`HintMediaHeaderBox`},{type:`nmhd`,name:`NullMediaHeaderBox`},{type:`iods`,name:`ObjectDescriptorBox`},{type:`xml `,name:`XMLBox`},{type:`bxml`,name:`BinaryXMLBox`},{type:`ipro`,name:`ItemProtectionBox`},{type:`mere`,name:`MetaboxRelationBox`}],CONTAINER_BOXES:[[{type:`moov`,name:`CompressedMovieBox`},[`trak`,`pssh`]],[{type:`trak`,name:`TrackBox`}],[{type:`edts`,name:`EditBox`}],[{type:`mdia`,name:`MediaBox`}],[{type:`minf`,name:`MediaInformationBox`}],[{type:`dinf`,name:`DataInformationBox`}],[{type:`stbl`,name:`SampleTableBox`},[`sgpd`,`sbgp`]],[{type:`mvex`,name:`MovieExtendsBox`},[`trex`]],[{type:`moof`,name:`CompressedMovieFragmentBox`},[`traf`]],[{type:`traf`,name:`TrackFragmentBox`},[`trun`,`sgpd`,`sbgp`]],[{type:`vttc`,name:`VTTCueBox`}],[{type:`tref`,name:`TrackReferenceBox`}],[{type:`iref`,name:`ItemReferenceBox`}],[{type:`mfra`,name:`MovieFragmentRandomAccessBox`},[`tfra`]],[{type:`meco`,name:`AdditionalMetadataContainerBox`}],[{type:`hnti`,name:`trackhintinformation`}],[{type:`hinf`,name:`hintstatisticsbox`}],[{type:`strk`,name:`SubTrackBox`}],[{type:`strd`,name:`SubTrackDefinitionBox`}],[{type:`sinf`,name:`ProtectionSchemeInfoBox`}],[{type:`rinf`,name:`RestrictedSchemeInfoBox`}],[{type:`schi`,name:`SchemeInformationBox`}],[{type:`trgr`,name:`TrackGroupBox`}],[{type:`udta`,name:`UserDataBox`},[`kind`]],[{type:`iprp`,name:`ItemPropertiesBox`},[`ipma`]],[{type:`ipco`,name:`ItemPropertyContainerBox`}],[{type:`grpl`,name:`GroupsListBox`}],[{type:`j2kH`,name:`J2KHeaderInfoBox`}],[{type:`etyp`,name:`ExtendedTypeBox`},[`tyco`]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){c.FullBox.prototype=new c.Box,c.ContainerBox.prototype=new c.Box,c.SampleEntry.prototype=new c.Box,c.TrackGroupTypeBox.prototype=new c.FullBox,c.BASIC_BOXES.forEach(function(e){c.createBoxCtor(e.type,e.name)}),c.FULL_BOXES.forEach(function(e){c.createFullBoxCtor(e.type,e.name)}),c.CONTAINER_BOXES.forEach(function(e){c.createContainerBoxCtor(e[0].type,e[0].name,null,e[1])})},Box:function(e,t,n,r){this.type=e,this.box_name=n,this.size=t,this.uuid=r},FullBox:function(e,t,n,r){c.Box.call(this,e,t,n,r),this.flags=0,this.version=0},ContainerBox:function(e,t,n,r){c.Box.call(this,e,t,n,r),this.boxes=[]},SampleEntry:function(e,t,n,r){c.ContainerBox.call(this,e,t),this.hdr_size=n,this.start=r},SampleGroupEntry:function(e){this.grouping_type=e},TrackGroupTypeBox:function(e,t){c.FullBox.call(this,e,t)},createBoxCtor:function(e,t,n){c.boxCodes.push(e),c[e+`Box`]=function(n){c.Box.call(this,e,n,t)},c[e+`Box`].prototype=new c.Box,n&&(c[e+`Box`].prototype.parse=n)},createFullBoxCtor:function(e,t,n){c[e+`Box`]=function(n){c.FullBox.call(this,e,n,t)},c[e+`Box`].prototype=new c.FullBox,c[e+`Box`].prototype.parse=function(e){this.parseFullHeader(e),n&&n.call(this,e)}},addSubBoxArrays:function(e){if(e){this.subBoxNames=e;for(var t=e.length,n=0;n<t;n++)this[e[n]+`s`]=[]}},createContainerBoxCtor:function(e,t,n,r){c[e+`Box`]=function(n){c.ContainerBox.call(this,e,n,t),c.addSubBoxArrays.call(this,r)},c[e+`Box`].prototype=new c.ContainerBox,n&&(c[e+`Box`].prototype.parse=n)},createMediaSampleEntryCtor:function(e,t,n){c.sampleEntryCodes[e]=[],c[e+`SampleEntry`]=function(e,t){c.SampleEntry.call(this,e,t),c.addSubBoxArrays.call(this,n)},c[e+`SampleEntry`].prototype=new c.SampleEntry,t&&(c[e+`SampleEntry`].prototype.parse=t)},createSampleEntryCtor:function(e,t,n,r){c.sampleEntryCodes[e].push(t),c[t+`SampleEntry`]=function(n){c[e+`SampleEntry`].call(this,t,n),c.addSubBoxArrays.call(this,r)},c[t+`SampleEntry`].prototype=new c[e+`SampleEntry`],n&&(c[t+`SampleEntry`].prototype.parse=n)},createEncryptedSampleEntryCtor:function(e,t,n){c.createSampleEntryCtor.call(this,e,t,n,[`sinf`])},createSampleGroupCtor:function(e,t){c[e+`SampleGroupEntry`]=function(t){c.SampleGroupEntry.call(this,e,t)},c[e+`SampleGroupEntry`].prototype=new c.SampleGroupEntry,t&&(c[e+`SampleGroupEntry`].prototype.parse=t)},createTrackGroupCtor:function(e,t){c[e+`TrackGroupTypeBox`]=function(t){c.TrackGroupTypeBox.call(this,e,t)},c[e+`TrackGroupTypeBox`].prototype=new c.TrackGroupTypeBox,t&&(c[e+`TrackGroupTypeBox`].prototype.parse=t)},createUUIDBox:function(e,t,n,r,a){c.UUIDs.push(e),c.UUIDBoxes[e]=function(a){n?c.FullBox.call(this,`uuid`,a,t,e):r?c.ContainerBox.call(this,`uuid`,a,t,e):c.Box.call(this,`uuid`,a,t,e)},c.UUIDBoxes[e].prototype=n?new c.FullBox:r?new c.ContainerBox:new c.Box,a&&(n?c.UUIDBoxes[e].prototype.parse=function(e){this.parseFullHeader(e),a&&a.call(this,e)}:c.UUIDBoxes[e].prototype.parse=a)}};c.initialize(),c.TKHD_FLAG_ENABLED=1,c.TKHD_FLAG_IN_MOVIE=2,c.TKHD_FLAG_IN_PREVIEW=4,c.TFHD_FLAG_BASE_DATA_OFFSET=1,c.TFHD_FLAG_SAMPLE_DESC=2,c.TFHD_FLAG_SAMPLE_DUR=8,c.TFHD_FLAG_SAMPLE_SIZE=16,c.TFHD_FLAG_SAMPLE_FLAGS=32,c.TFHD_FLAG_DUR_EMPTY=65536,c.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,c.TRUN_FLAGS_DATA_OFFSET=1,c.TRUN_FLAGS_FIRST_FLAG=4,c.TRUN_FLAGS_DURATION=256,c.TRUN_FLAGS_SIZE=512,c.TRUN_FLAGS_FLAGS=1024,c.TRUN_FLAGS_CTS_OFFSET=2048,c.Box.prototype.add=function(e){return this.addBox(new c[e+`Box`])},c.Box.prototype.addBox=function(e){return this.boxes.push(e),this[e.type+`s`]?this[e.type+`s`].push(e):this[e.type]=e,e},c.Box.prototype.set=function(e,t){return this[e]=t,this},c.Box.prototype.addEntry=function(e,t){var n=t||`entries`;return this[n]||(this[n]=[]),this[n].push(e),this},e!==void 0&&(e.BoxParser=c),c.parseUUID=function(e){return c.parseHex16(e)},c.parseHex16=function(e){for(var t=``,n=0;n<16;n++){var r=e.readUint8().toString(16);t+=r.length===1?`0`+r:r}return t},c.parseOneBox=function(e,n,r){var a,o=e.getPosition(),s=0,l,u;if(e.getEndPosition()-o<8)return t.debug(`BoxParser`,`Not enough data in stream to parse the type and size of the box`),{code:c.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return t.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a new box`),{code:c.ERR_NOT_ENOUGH_DATA};var d=e.readUint32(),f=e.readString(4),p=f;if(t.debug(`BoxParser`,`Found box of type '`+f+`' and size `+d+` at position `+o),s=8,f==`uuid`){if(e.getEndPosition()-e.getPosition()<16||r-s<16)return e.seek(o),t.debug(`BoxParser`,`Not enough bytes left in the parent box to parse a UUID box`),{code:c.ERR_NOT_ENOUGH_DATA};u=c.parseUUID(e),s+=16,p=u}if(d==1){if(e.getEndPosition()-e.getPosition()<8||r&&r-s<8)return e.seek(o),t.warn(`BoxParser`,`Not enough data in stream to parse the extended size of the "`+f+`" box`),{code:c.ERR_NOT_ENOUGH_DATA};d=e.readUint64(),s+=8}else if(d===0){if(r)d=r;else if(f!==`mdat`)return t.error(`BoxParser`,`Unlimited box size not supported for type: '`+f+`'`),a=new c.Box(f,d),{code:c.OK,box:a,size:a.size}}return d!==0&&d<s?(t.error(`BoxParser`,`Box of type `+f+` has an invalid size `+d+` (too small to be a box)`),{code:c.ERR_NOT_ENOUGH_DATA,type:f,size:d,hdr_size:s,start:o}):d!==0&&r&&d>r?(t.error(`BoxParser`,`Box of type '`+f+`' has a size `+d+` greater than its container size `+r),{code:c.ERR_NOT_ENOUGH_DATA,type:f,size:d,hdr_size:s,start:o}):d!==0&&o+d>e.getEndPosition()?(e.seek(o),t.info(`BoxParser`,`Not enough data in stream to parse the entire '`+f+`' box`),{code:c.ERR_NOT_ENOUGH_DATA,type:f,size:d,hdr_size:s,start:o}):n?{code:c.OK,type:f,size:d,hdr_size:s,start:o}:(c[f+`Box`]?a=new c[f+`Box`](d):f===`uuid`?c.UUIDBoxes[u]?a=new c.UUIDBoxes[u](d):(t.warn(`BoxParser`,`Unknown uuid type: '`+u+`'`),a=new c.Box(f,d),a.uuid=u,a.has_unparsed_data=!0):(t.warn(`BoxParser`,`Unknown box type: '`+f+`'`),a=new c.Box(f,d),a.has_unparsed_data=!0),a.hdr_size=s,a.start=o,a.write===c.Box.prototype.write&&a.type!==`mdat`&&(t.info(`BoxParser`,`'`+p+`' box writing not yet implemented, keeping unparsed data in memory for later write`),a.parseDataAndRewind(e)),a.parse(e),l=e.getPosition()-(a.start+a.size),l<0?(t.warn(`BoxParser`,`Parsing of box '`+p+`' did not read the entire indicated box data size (missing `+-l+` bytes), seeking forward`),e.seek(a.start+a.size)):l>0&&(t.error(`BoxParser`,`Parsing of box '`+p+`' read `+l+` more bytes than the indicated box data size, seeking backwards`),a.size!==0&&e.seek(a.start+a.size)),{code:c.OK,box:a,size:a.size})},c.Box.prototype.parse=function(e){this.type==`mdat`?this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size):this.data=e.readUint8Array(this.size-this.hdr_size)},c.Box.prototype.parseDataAndRewind=function(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.position-=this.size-this.hdr_size},c.FullBox.prototype.parseDataAndRewind=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.position-=this.size-this.hdr_size},c.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4},c.FullBox.prototype.parse=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},c.ContainerBox.prototype.parse=function(e){for(var n,r;e.getPosition()<this.start+this.size;)if(n=c.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),n.code===c.OK)if(r=n.box,this.boxes.push(r),this.subBoxNames&&this.subBoxNames.indexOf(r.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+`s`].push(r);else{var a=r.type===`uuid`?r.uuid:r.type;this[a]?t.warn(`Box of type `+a+` already stored in field of this type`):this[a]=r}else return},c.Box.prototype.parseLanguage=function(e){this.language=e.readUint16();var t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)},c.SAMPLE_ENTRY_TYPE_VISUAL=`Visual`,c.SAMPLE_ENTRY_TYPE_AUDIO=`Audio`,c.SAMPLE_ENTRY_TYPE_HINT=`Hint`,c.SAMPLE_ENTRY_TYPE_METADATA=`Metadata`,c.SAMPLE_ENTRY_TYPE_SUBTITLE=`Subtitle`,c.SAMPLE_ENTRY_TYPE_SYSTEM=`System`,c.SAMPLE_ENTRY_TYPE_TEXT=`Text`,c.SampleEntry.prototype.parseHeader=function(e){e.readUint8Array(6),this.data_reference_index=e.readUint16(),this.hdr_size+=8},c.SampleEntry.prototype.parse=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},c.SampleEntry.prototype.parseDataAndRewind=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,e.position-=this.size-this.hdr_size},c.SampleEntry.prototype.parseFooter=function(e){c.ContainerBox.prototype.parse.call(this,e)},c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_HINT),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_METADATA),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SYSTEM),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_TEXT),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,function(e){var t;this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16(),t=Math.min(31,e.readUint8()),this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}),c.createMediaSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,function(e){this.parseHeader(e),e.readUint32Array(2),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`avc1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`avc2`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`avc3`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`avc4`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`av01`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`dav1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`hvc1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`hev1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`hvt1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`lhe1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`dvh1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`dvhe`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vvc1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vvi1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vvs1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vvcN`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vp08`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`vp09`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`avs3`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`j2ki`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`mjp2`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`mjpg`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`uncv`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`mp4a`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`ac-3`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`ac-4`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`ec-3`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`Opus`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`mha1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`mha2`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`mhm1`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`mhm2`),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`fLaC`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_VISUAL,`encv`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_AUDIO,`enca`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE,`encu`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SYSTEM,`encs`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_TEXT,`enct`),c.createEncryptedSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_METADATA,`encm`),c.createBoxCtor(`a1lx`,`AV1LayeredImageIndexingProperty`,function(e){var t=((e.readUint8()&1)+1)*16;this.layer_size=[];for(var n=0;n<3;n++)t==16?this.layer_size[n]=e.readUint16():this.layer_size[n]=e.readUint32()}),c.createBoxCtor(`a1op`,`OperatingPointSelectorProperty`,function(e){this.op_index=e.readUint8()}),c.createFullBoxCtor(`auxC`,`AuxiliaryTypeProperty`,function(e){this.aux_type=e.readCString();var t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}),c.createBoxCtor(`av1C`,`AV1CodecConfigurationBox`,function(e){var n=e.readUint8();if((n>>7&1)!=1){t.error(`av1C marker problem`);return}if(this.version=n&127,this.version!==1){t.error(`av1C version `+this.version+` not supported`);return}if(n=e.readUint8(),this.seq_profile=n>>5&7,this.seq_level_idx_0=n&31,n=e.readUint8(),this.seq_tier_0=n>>7&1,this.high_bitdepth=n>>6&1,this.twelve_bit=n>>5&1,this.monochrome=n>>4&1,this.chroma_subsampling_x=n>>3&1,this.chroma_subsampling_y=n>>2&1,this.chroma_sample_position=n&3,n=e.readUint8(),this.reserved_1=n>>5&7,this.reserved_1!==0){t.error(`av1C reserved_1 parsing problem`);return}if(this.initial_presentation_delay_present=n>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=n&15;else if(this.reserved_2=n&15,this.reserved_2!==0){t.error(`av1C reserved_2 parsing problem`);return}var r=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(r)});function l(e){var t=`<table class='inner-table'>`;t+=`<thead><tr><th>length</th><th>nalu_data</th></tr></thead>`,t+=`<tbody>`;for(var n=0;n<e.length;n++){var r=e[n];t+=`<tr>`,t+=`<td>`+r.length+`</td>`,t+=`<td>`,t+=r.nalu.reduce(function(e,t){return e+t.toString(16).padStart(2,`0`)},`0x`),t+=`</td></tr>`}return t+=`</tbody></table>`,t}c.createBoxCtor(`avcC`,`AVCConfigurationBox`,function(e){var t,n;for(this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31,n=this.size-this.hdr_size-6,this.SPS=[],this.SPS.toString=function(){return l(this)},t=0;t<this.nb_SPS_nalus;t++)this.SPS[t]={},this.SPS[t].length=e.readUint16(),this.SPS[t].nalu=e.readUint8Array(this.SPS[t].length),n-=2+this.SPS[t].length;for(this.nb_PPS_nalus=e.readUint8(),n--,this.PPS=[],this.PPS.toString=function(){return l(this)},t=0;t<this.nb_PPS_nalus;t++)this.PPS[t]={},this.PPS[t].length=e.readUint16(),this.PPS[t].nalu=e.readUint8Array(this.PPS[t].length),n-=2+this.PPS[t].length;n>0&&(this.ext=e.readUint8Array(n))}),c.createBoxCtor(`btrt`,`BitRateBox`,function(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}),c.createFullBoxCtor(`ccst`,`CodingConstraintsBox`,function(e){var t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}),c.createBoxCtor(`cdef`,`ComponentDefinitionBox`,function(e){var t;for(this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],t=0;t<this.channel_count;t++)this.channel_indexes.push(e.readUint16()),this.channel_types.push(e.readUint16()),this.channel_associations.push(e.readUint16())}),c.createBoxCtor(`clap`,`CleanApertureBox`,function(e){this.cleanApertureWidthN=e.readUint32(),this.cleanApertureWidthD=e.readUint32(),this.cleanApertureHeightN=e.readUint32(),this.cleanApertureHeightD=e.readUint32(),this.horizOffN=e.readUint32(),this.horizOffD=e.readUint32(),this.vertOffN=e.readUint32(),this.vertOffD=e.readUint32()}),c.createBoxCtor(`clli`,`ContentLightLevelBox`,function(e){this.max_content_light_level=e.readUint16(),this.max_pic_average_light_level=e.readUint16()}),c.createFullBoxCtor(`cmex`,`CameraExtrinsicMatrixProperty`,function(e){this.flags&1&&(this.pos_x=e.readInt32()),this.flags&2&&(this.pos_y=e.readInt32()),this.flags&4&&(this.pos_z=e.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=e.readInt32(),this.quat_y=e.readInt32(),this.quat_z=e.readInt32()):(this.quat_x=e.readInt16(),this.quat_y=e.readInt16(),this.quat_z=e.readInt16()):this.version),this.flags&32&&(this.id=e.readUint32())}),c.createFullBoxCtor(`cmin`,`CameraIntrinsicMatrixProperty`,function(e){this.focal_length_x=e.readInt32(),this.principal_point_x=e.readInt32(),this.principal_point_y=e.readInt32(),this.flags&1&&(this.focal_length_y=e.readInt32(),this.skew_factor=e.readInt32())}),c.createBoxCtor(`cmpd`,`ComponentDefinitionBox`,function(e){for(this.component_count=e.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var t=e.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(e.readCString())}}),c.createFullBoxCtor(`co64`,`ChunkLargeOffsetBox`,function(e){var t=e.readUint32(),n;if(this.chunk_offsets=[],this.version===0)for(n=0;n<t;n++)this.chunk_offsets.push(e.readUint64())}),c.createFullBoxCtor(`CoLL`,`ContentLightLevelBox`,function(e){this.maxCLL=e.readUint16(),this.maxFALL=e.readUint16()}),c.createBoxCtor(`colr`,`ColourInformationBox`,function(e){if(this.colour_type=e.readString(4),this.colour_type===`nclx`){this.colour_primaries=e.readUint16(),this.transfer_characteristics=e.readUint16(),this.matrix_coefficients=e.readUint16();var t=e.readUint8();this.full_range_flag=t>>7}else (this.colour_type===`rICC`||this.colour_type===`prof`)&&(this.ICC_profile=e.readUint8Array(this.size-4))}),c.createFullBoxCtor(`cprt`,`CopyrightBox`,function(e){this.parseLanguage(e),this.notice=e.readCString()}),c.createFullBoxCtor(`cslg`,`CompositionToDecodeBox`,function(e){this.version===0&&(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32())}),c.createFullBoxCtor(`ctts`,`CompositionOffsetBox`,function(e){var n=e.readUint32(),r;if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(r=0;r<n;r++){this.sample_counts.push(e.readUint32());var a=e.readInt32();a<0&&t.warn(`BoxParser`,`ctts box uses negative values without using version 1`),this.sample_offsets.push(a)}else if(this.version==1)for(r=0;r<n;r++)this.sample_counts.push(e.readUint32()),this.sample_offsets.push(e.readInt32())}),c.createBoxCtor(`dac3`,`AC3SpecificBox`,function(e){var t=e.readUint8(),n=e.readUint8(),r=e.readUint8();this.fscod=t>>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}),c.createBoxCtor(`dec3`,`EC3SpecificBox`,function(e){var t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(var n=0;n<this.num_ind_sub+1;n++){var r={};this.ind_subs.push(r);var a=e.readUint8(),o=e.readUint8(),s=e.readUint8();r.fscod=a>>6,r.bsid=a>>1&31,r.bsmod=(a&1)<<4|o>>4&15,r.acmod=o>>1&7,r.lfeon=o&1,r.num_dep_sub=s>>1&15,r.num_dep_sub>0&&(r.chan_loc=(s&1)<<8|e.readUint8())}}),c.createFullBoxCtor(`dfLa`,`FLACSpecificBox`,function(e){var t=127,n=128,r=[],a=[`STREAMINFO`,`PADDING`,`APPLICATION`,`SEEKTABLE`,`VORBIS_COMMENT`,`CUESHEET`,`PICTURE`,`RESERVED`];do{var o=e.readUint8(),s=Math.min(o&t,a.length-1);if(s?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),r.push(a[s]),o&n)break}while(!0);this.numMetadataBlocks=r.length+` (`+r.join(`, `)+`)`}),c.createBoxCtor(`dimm`,`hintimmediateBytesSent`,function(e){this.bytessent=e.readUint64()}),c.createBoxCtor(`dmax`,`hintlongestpacket`,function(e){this.time=e.readUint32()}),c.createBoxCtor(`dmed`,`hintmediaBytesSent`,function(e){this.bytessent=e.readUint64()}),c.createBoxCtor(`dOps`,`OpusSpecificBox`,function(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(var t=0;t<this.OutputChannelCount;t++)this.ChannelMapping[t]=e.readUint8()}}),c.createFullBoxCtor(`dref`,`DataReferenceBox`,function(e){var t,n;this.entries=[];for(var r=e.readUint32(),a=0;a<r;a++)if(t=c.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===c.OK)n=t.box,this.entries.push(n);else return}),c.createBoxCtor(`drep`,`hintrepeatedBytesSent`,function(e){this.bytessent=e.readUint64()}),c.createFullBoxCtor(`elng`,`ExtendedLanguageBox`,function(e){this.extended_language=e.readString(this.size-this.hdr_size)}),c.createFullBoxCtor(`elst`,`EditListBox`,function(e){this.entries=[];for(var t=e.readUint32(),n=0;n<t;n++){var r={};this.entries.push(r),this.version===1?(r.segment_duration=e.readUint64(),r.media_time=e.readInt64()):(r.segment_duration=e.readUint32(),r.media_time=e.readInt32()),r.media_rate_integer=e.readInt16(),r.media_rate_fraction=e.readInt16()}}),c.createFullBoxCtor(`emsg`,`EventMessageBox`,function(e){this.version==1?(this.timescale=e.readUint32(),this.presentation_time=e.readUint64(),this.event_duration=e.readUint32(),this.id=e.readUint32(),this.scheme_id_uri=e.readCString(),this.value=e.readCString()):(this.scheme_id_uri=e.readCString(),this.value=e.readCString(),this.timescale=e.readUint32(),this.presentation_time_delta=e.readUint32(),this.event_duration=e.readUint32(),this.id=e.readUint32());var t=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(t-=4),this.message_data=e.readUint8Array(t)}),c.createEntityToGroupCtor=function(e,t){c[e+`Box`]=function(t){c.FullBox.call(this,e,t)},c[e+`Box`].prototype=new c.FullBox,c[e+`Box`].prototype.parse=function(e){if(this.parseFullHeader(e),t)t.call(this,e);else for(this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var n=e.readUint32();this.entity_ids.push(n)}}},c.createEntityToGroupCtor(`aebr`),c.createEntityToGroupCtor(`afbr`),c.createEntityToGroupCtor(`albc`),c.createEntityToGroupCtor(`altr`),c.createEntityToGroupCtor(`brst`),c.createEntityToGroupCtor(`dobr`),c.createEntityToGroupCtor(`eqiv`),c.createEntityToGroupCtor(`favc`),c.createEntityToGroupCtor(`fobr`),c.createEntityToGroupCtor(`iaug`),c.createEntityToGroupCtor(`pano`),c.createEntityToGroupCtor(`slid`),c.createEntityToGroupCtor(`ster`),c.createEntityToGroupCtor(`tsyn`),c.createEntityToGroupCtor(`wbbr`),c.createEntityToGroupCtor(`prgr`),c.createEntityToGroupCtor(`pymd`,function(e){this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(var t=0;t<this.num_entities_in_group;t++){var n=e.readUint32();this.entity_ids.push(n)}for(this.tile_size_x=e.readUint16(),this.tile_size_y=e.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],t=0;t<this.num_entities_in_group;t++)this.layer_binning[t]=e.readUint16(),this.tiles_in_layer_row_minus1[t]=e.readUint16(),this.tiles_in_layer_column_minus1[t]=e.readUint16()}),c.createFullBoxCtor(`esds`,`ElementaryStreamDescriptorBox`,function(e){var t=e.readUint8Array(this.size-this.hdr_size);if(s!==void 0){var n=new s;this.esd=n.parseOneDescriptor(new r(t.buffer,0,r.BIG_ENDIAN))}}),c.createBoxCtor(`fiel`,`FieldHandlingBox`,function(e){this.fieldCount=e.readUint8(),this.fieldOrdering=e.readUint8()}),c.createBoxCtor(`frma`,`OriginalFormatBox`,function(e){this.data_format=e.readString(4)}),c.createBoxCtor(`ftyp`,`FileTypeBox`,function(e){var t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];for(var n=0;t>=4;)this.compatible_brands[n]=e.readString(4),t-=4,n++}),c.createFullBoxCtor(`hdlr`,`HandlerBox`,function(e){this.version===0&&(e.readUint32(),this.handler=e.readString(4),e.readUint32Array(3),this.name=e.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]===`\0`&&(this.name=this.name.slice(0,-1)))}),c.createBoxCtor(`hvcC`,`HEVCConfigurationBox`,function(e){var t,n,r,a;this.configurationVersion=e.readUint8(),a=e.readUint8(),this.general_profile_space=a>>6,this.general_tier_flag=(a&32)>>5,this.general_profile_idc=a&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),a=e.readUint8(),this.constantFrameRate=a>>6,this.numTemporalLayers=(a&13)>>3,this.temporalIdNested=(a&4)>>2,this.lengthSizeMinusOne=a&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var e=`<table class='inner-table'>`;e+=`<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>`,e+=`<tbody>`;for(var t=0;t<this.length;t++){var n=this[t];e+=`<tr>`,e+=`<td rowspan='`+n.length+`'>`+n.completeness+`</td>`,e+=`<td rowspan='`+n.length+`'>`+n.nalu_type+`</td>`;for(var r=0;r<n.length;r++){var a=n[r];r!==0&&(e+=`<tr>`),e+=`<td>`,e+=a.data.reduce(function(e,t){return e+t.toString(16).padStart(2,`0`)},`0x`),e+=`</td></tr>`}}return e+=`</tbody></table>`,e};var o=e.readUint8();for(t=0;t<o;t++){var s=[];this.nalu_arrays.push(s),a=e.readUint8(),s.completeness=(a&128)>>7,s.nalu_type=a&63;var c=e.readUint16();for(n=0;n<c;n++){var l={};s.push(l),r=e.readUint16(),l.data=e.readUint8Array(r)}}}),c.createFullBoxCtor(`iinf`,`ItemInfoBox`,function(e){var n;this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++)if(n=c.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),n.code===c.OK)n.box.type!==`infe`&&t.error(`BoxParser`,`Expected 'infe' box, got `+n.box.type),this.item_infos[r]=n.box;else return}),c.createFullBoxCtor(`iloc`,`ItemLocationBox`,function(e){var t=e.readUint8();this.offset_size=t>>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.version===1||this.version===2?this.index_size=t&15:this.index_size=0,this.items=[];var n=0;if(this.version<2)n=e.readUint16();else if(this.version===2)n=e.readUint32();else throw`version of iloc box not supported`;for(var r=0;r<n;r++){var a={};if(this.items.push(a),this.version<2)a.item_ID=e.readUint16();else if(this.version===2)a.item_ID=e.readUint32();else throw`version of iloc box not supported`;switch(this.version===1||this.version===2?a.construction_method=e.readUint16()&15:a.construction_method=0,a.data_reference_index=e.readUint16(),this.base_offset_size){case 0:a.base_offset=0;break;case 4:a.base_offset=e.readUint32();break;case 8:a.base_offset=e.readUint64();break;default:throw`Error reading base offset size`}var o=e.readUint16();a.extents=[];for(var s=0;s<o;s++){var c={};if(a.extents.push(c),this.version===1||this.version===2)switch(this.index_size){case 0:c.extent_index=0;break;case 4:c.extent_index=e.readUint32();break;case 8:c.extent_index=e.readUint64();break;default:throw`Error reading extent index`}switch(this.offset_size){case 0:c.extent_offset=0;break;case 4:c.extent_offset=e.readUint32();break;case 8:c.extent_offset=e.readUint64();break;default:throw`Error reading extent index`}switch(this.length_size){case 0:c.extent_length=0;break;case 4:c.extent_length=e.readUint32();break;case 8:c.extent_length=e.readUint64();break;default:throw`Error reading extent index`}}}}),c.createBoxCtor(`imir`,`ImageMirror`,function(e){var t=e.readUint8();this.reserved=t>>7,this.axis=t&1}),c.createFullBoxCtor(`infe`,`ItemInfoEntry`,function(e){if((this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.content_encoding=e.readCString()),this.version===1){this.extension_type=e.readString(4),t.warn(`BoxParser`,`Cannot parse extension type`),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type===`mime`?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type===`uri `&&(this.item_uri_type=e.readCString()))}),c.createFullBoxCtor(`ipma`,`ItemPropertyAssociationBox`,function(e){var t,n;for(entry_count=e.readUint32(),this.associations=[],t=0;t<entry_count;t++){var r={};this.associations.push(r),this.version<1?r.id=e.readUint16():r.id=e.readUint32();var a=e.readUint8();for(r.props=[],n=0;n<a;n++){var o=e.readUint8(),s={};r.props.push(s),s.essential=(o&128)>>7==1,this.flags&1?s.property_index=(o&127)<<8|e.readUint8():s.property_index=o&127}}}),c.createFullBoxCtor(`iref`,`ItemReferenceBox`,function(e){var n,r;for(this.references=[];e.getPosition()<this.start+this.size;)if(n=c.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),n.code===c.OK)r=this.version===0?new c.SingleItemTypeReferenceBox(n.type,n.size,n.hdr_size,n.start):new c.SingleItemTypeReferenceBoxLarge(n.type,n.size,n.hdr_size,n.start),r.write===c.Box.prototype.write&&r.type!==`mdat`&&(t.warn(`BoxParser`,r.type+` box writing not yet implemented, keeping unparsed data in memory for later write`),r.parseDataAndRewind(e)),r.parse(e),this.references.push(r);else return}),c.createBoxCtor(`irot`,`ImageRotation`,function(e){this.angle=e.readUint8()&3}),c.createFullBoxCtor(`ispe`,`ImageSpatialExtentsProperty`,function(e){this.image_width=e.readUint32(),this.image_height=e.readUint32()}),c.createFullBoxCtor(`kind`,`KindBox`,function(e){this.schemeURI=e.readCString(),this.value=e.readCString()}),c.createFullBoxCtor(`leva`,`LevelAssignmentBox`,function(e){var n=e.readUint8();this.levels=[];for(var r=0;r<n;r++){var a={};this.levels[r]=a,a.track_ID=e.readUint32();var o=e.readUint8();switch(a.padding_flag=o>>7,a.assignment_type=o&127,a.assignment_type){case 0:a.grouping_type=e.readString(4);break;case 1:a.grouping_type=e.readString(4),a.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:a.sub_track_id=e.readUint32();break;default:t.warn(`BoxParser`,`Unknown leva assignement type`)}}}),c.createBoxCtor(`lhvC`,`LHEVCConfigurationBox`,function(e){var t,n,r;this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,r=e.readUint8(),this.numTemporalLayers=(r&13)>>3,this.temporalIdNested=(r&4)>>2,this.lengthSizeMinusOne=r&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var e=`<table class='inner-table'>`;e+=`<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>`,e+=`<tbody>`;for(var t=0;t<this.length;t++){var n=this[t];e+=`<tr>`,e+=`<td rowspan='`+n.length+`'>`+n.completeness+`</td>`,e+=`<td rowspan='`+n.length+`'>`+n.nalu_type+`</td>`;for(var r=0;r<n.length;r++){var a=n[r];r!==0&&(e+=`<tr>`),e+=`<td>`,e+=a.data.reduce(function(e,t){return e+t.toString(16).padStart(2,`0`)},`0x`),e+=`</td></tr>`}}return e+=`</tbody></table>`,e};var a=e.readUint8();for(t=0;t<a;t++){var o=[];this.nalu_arrays.push(o),r=e.readUint8(),o.completeness=(r&128)>>7,o.nalu_type=r&63;var s=e.readUint16();for(n=0;n<s;n++){var c={};o.push(c);var l=e.readUint16();c.data=e.readUint8Array(l)}}}),c.createBoxCtor(`lsel`,`LayerSelectorProperty`,function(e){this.layer_id=e.readUint16()}),c.createBoxCtor(`maxr`,`hintmaxrate`,function(e){this.period=e.readUint32(),this.bytes=e.readUint32()});function u(e,t){this.x=e,this.y=t}u.prototype.toString=function(){return`(`+this.x+`,`+this.y+`)`},c.createBoxCtor(`mdcv`,`MasteringDisplayColourVolumeBox`,function(e){this.display_primaries=[],this.display_primaries[0]=new u(e.readUint16(),e.readUint16()),this.display_primaries[1]=new u(e.readUint16(),e.readUint16()),this.display_primaries[2]=new u(e.readUint16(),e.readUint16()),this.white_point=new u(e.readUint16(),e.readUint16()),this.max_display_mastering_luminance=e.readUint32(),this.min_display_mastering_luminance=e.readUint32()}),c.createFullBoxCtor(`mdhd`,`MediaHeaderBox`,function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.parseLanguage(e),e.readUint16()}),c.createFullBoxCtor(`mehd`,`MovieExtendsHeaderBox`,function(e){this.flags&1&&(t.warn(`BoxParser`,`mehd box incorrectly uses flags set to 1, converting version to 1`),this.version=1),this.version==1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}),c.createFullBoxCtor(`meta`,`MetaBox`,function(e){this.boxes=[],c.ContainerBox.prototype.parse.call(this,e)}),c.createFullBoxCtor(`mfhd`,`MovieFragmentHeaderBox`,function(e){this.sequence_number=e.readUint32()}),c.createFullBoxCtor(`mfro`,`MovieFragmentRandomAccessOffsetBox`,function(e){this._size=e.readUint32()}),c.createFullBoxCtor(`mskC`,`MaskConfigurationProperty`,function(e){this.bits_per_pixel=e.readUint8()}),c.createFullBoxCtor(`mvhd`,`MovieHeaderBox`,function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readUint32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}),c.createBoxCtor(`npck`,`hintPacketsSent`,function(e){this.packetssent=e.readUint32()}),c.createBoxCtor(`nump`,`hintPacketsSent`,function(e){this.packetssent=e.readUint64()}),c.createFullBoxCtor(`padb`,`PaddingBitsBox`,function(e){var t=e.readUint32();this.padbits=[];for(var n=0;n<Math.floor((t+1)/2);n++)this.padbits=e.readUint8()}),c.createBoxCtor(`pasp`,`PixelAspectRatioBox`,function(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}),c.createBoxCtor(`payl`,`CuePayloadBox`,function(e){this.text=e.readString(this.size-this.hdr_size)}),c.createBoxCtor(`payt`,`hintpayloadID`,function(e){this.payloadID=e.readUint32();var t=e.readUint8();this.rtpmap_string=e.readString(t)}),c.createFullBoxCtor(`pdin`,`ProgressiveDownloadInfoBox`,function(e){var t=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var n=0;n<t;n++)this.rate[n]=e.readUint32(),this.initial_delay[n]=e.readUint32()}),c.createFullBoxCtor(`pitm`,`PrimaryItemBox`,function(e){this.version===0?this.item_id=e.readUint16():this.item_id=e.readUint32()}),c.createFullBoxCtor(`pixi`,`PixelInformationProperty`,function(e){var t;for(this.num_channels=e.readUint8(),this.bits_per_channels=[],t=0;t<this.num_channels;t++)this.bits_per_channels[t]=e.readUint8()}),c.createBoxCtor(`pmax`,`hintlargestpacket`,function(e){this.bytes=e.readUint32()}),c.createFullBoxCtor(`prdi`,`ProgressiveDerivedImageItemInformationProperty`,function(e){if(this.step_count=e.readUint16(),this.item_count=[],this.flags&2)for(var t=0;t<this.step_count;t++)this.item_count[t]=e.readUint16()}),c.createFullBoxCtor(`prft`,`ProducerReferenceTimeBox`,function(e){this.ref_track_id=e.readUint32(),this.ntp_timestamp=e.readUint64(),this.version===0?this.media_time=e.readUint32():this.media_time=e.readUint64()}),c.createFullBoxCtor(`pssh`,`ProtectionSystemSpecificHeaderBox`,function(e){if(this.system_id=c.parseHex16(e),this.version>0){var t=e.readUint32();this.kid=[];for(var n=0;n<t;n++)this.kid[n]=c.parseHex16(e)}var r=e.readUint32();r>0&&(this.data=e.readUint8Array(r))}),c.createFullBoxCtor(`clef`,`TrackCleanApertureDimensionsBox`,function(e){this.width=e.readUint32(),this.height=e.readUint32()}),c.createFullBoxCtor(`enof`,`TrackEncodedPixelsDimensionsBox`,function(e){this.width=e.readUint32(),this.height=e.readUint32()}),c.createFullBoxCtor(`prof`,`TrackProductionApertureDimensionsBox`,function(e){this.width=e.readUint32(),this.height=e.readUint32()}),c.createContainerBoxCtor(`tapt`,`TrackApertureModeDimensionsBox`,null,[`clef`,`prof`,`enof`]),c.createBoxCtor(`rtp `,`rtpmoviehintinformation`,function(e){this.descriptionformat=e.readString(4),this.sdptext=e.readString(this.size-this.hdr_size-4)}),c.createFullBoxCtor(`saio`,`SampleAuxiliaryInformationOffsetsBox`,function(e){this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32());var t=e.readUint32();this.offset=[];for(var n=0;n<t;n++)this.version===0?this.offset[n]=e.readUint32():this.offset[n]=e.readUint64()}),c.createFullBoxCtor(`saiz`,`SampleAuxiliaryInformationSizesBox`,function(e){if(this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32()),this.default_sample_info_size=e.readUint8(),this.sample_count=e.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var t=0;t<this.sample_count;t++)this.sample_info_size[t]=e.readUint8()}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_METADATA,`mett`,function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_METADATA,`metx`,function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE,`sbtt`,function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE,`stpp`,function(e){this.parseHeader(e),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.auxiliary_mime_types=e.readCString(),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE,`stxt`,function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_SUBTITLE,`tx3g`,function(e){this.parseHeader(e),this.displayFlags=e.readUint32(),this.horizontal_justification=e.readInt8(),this.vertical_justification=e.readInt8(),this.bg_color_rgba=e.readUint8Array(4),this.box_record=e.readInt16Array(4),this.style_record=e.readUint8Array(12),this.parseFooter(e)}),c.createSampleEntryCtor(c.SAMPLE_ENTRY_TYPE_METADATA,`wvtt`,function(e){this.parseHeader(e),this.parseFooter(e)}),c.createSampleGroupCtor(`alst`,function(e){var t,n=e.readUint16();for(this.first_output_sample=e.readUint16(),this.sample_offset=[],t=0;t<n;t++)this.sample_offset[t]=e.readUint32();var r=this.description_length-4-4*n;for(this.num_output_samples=[],this.num_total_samples=[],t=0;t<r/4;t++)this.num_output_samples[t]=e.readUint16(),this.num_total_samples[t]=e.readUint16()}),c.createSampleGroupCtor(`avll`,function(e){this.layerNumber=e.readUint8(),this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()}),c.createSampleGroupCtor(`avss`,function(e){this.subSequenceIdentifier=e.readUint16(),this.layerNumber=e.readUint8();var t=e.readUint8();this.durationFlag=t>>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];for(var n=e.readUint8(),r=0;r<n;r++){var a={};this.dependency.push(a),a.subSeqDirectionFlag=e.readUint8(),a.layerNumber=e.readUint8(),a.subSequenceIdentifier=e.readUint16()}}),c.createSampleGroupCtor(`dtrt`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`mvif`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`prol`,function(e){this.roll_distance=e.readInt16()}),c.createSampleGroupCtor(`rap `,function(e){var t=e.readUint8();this.num_leading_samples_known=t>>7,this.num_leading_samples=t&127}),c.createSampleGroupCtor(`rash`,function(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)t.warn(`BoxParser`,`Mismatch in `+this.grouping_type+` sample group length`),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var n=0;n<this.operation_point_count;n++)this.available_bitrate[n]=e.readUint32(),this.target_rate_share[n]=e.readUint16()}this.maximum_bitrate=e.readUint32(),this.minimum_bitrate=e.readUint32(),this.discard_priority=e.readUint8()}}),c.createSampleGroupCtor(`roll`,function(e){this.roll_distance=e.readInt16()}),c.SampleGroupEntry.prototype.parse=function(e){t.warn(`BoxParser`,`Unknown Sample Group type: `+this.grouping_type),this.data=e.readUint8Array(this.description_length)},c.createSampleGroupCtor(`scif`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`scnm`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`seig`,function(e){this.reserved=e.readUint8();var t=e.readUint8();this.crypt_byte_block=t>>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=c.parseHex16(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}),c.createSampleGroupCtor(`stsa`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`sync`,function(e){var t=e.readUint8();this.NAL_unit_type=t&63}),c.createSampleGroupCtor(`tele`,function(e){var t=e.readUint8();this.level_independently_decodable=t>>7}),c.createSampleGroupCtor(`tsas`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`tscl`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createSampleGroupCtor(`vipr`,function(e){t.warn(`BoxParser`,`Sample Group type: `+this.grouping_type+` not fully parsed`)}),c.createFullBoxCtor(`sbgp`,`SampleToGroupBox`,function(e){this.grouping_type=e.readString(4),this.version===1?this.grouping_type_parameter=e.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var t=e.readUint32(),n=0;n<t;n++){var r={};this.entries.push(r),r.sample_count=e.readInt32(),r.group_description_index=e.readInt32()}});function d(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}d.prototype.toString=function(){return`[row: `+this.bad_pixel_row+`, column: `+this.bad_pixel_column+`]`},c.createFullBoxCtor(`sbpm`,`SensorBadPixelsMapBox`,function(e){var t;for(this.component_count=e.readUint16(),this.component_index=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16());var n=e.readUint8();for(this.correction_applied=(n&128)==128,this.num_bad_rows=e.readUint32(),this.num_bad_cols=e.readUint32(),this.num_bad_pixels=e.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],t=0;t<this.num_bad_rows;t++)this.bad_rows.push(e.readUint32());for(t=0;t<this.num_bad_cols;t++)this.bad_columns.push(e.readUint32());for(t=0;t<this.num_bad_pixels;t++){var r=e.readUint32(),a=e.readUint32();this.bad_pixels.push(new d(r,a))}}),c.createFullBoxCtor(`schm`,`SchemeTypeBox`,function(e){this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readString(this.size-this.hdr_size-8))}),c.createBoxCtor(`sdp `,`rtptracksdphintinformation`,function(e){this.sdptext=e.readString(this.size-this.hdr_size)}),c.createFullBoxCtor(`sdtp`,`SampleDependencyTypeBox`,function(e){var t,n=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var r=0;r<n;r++)t=e.readUint8(),this.is_leading[r]=t>>6,this.sample_depends_on[r]=t>>4&3,this.sample_is_depended_on[r]=t>>2&3,this.sample_has_redundancy[r]=t&3}),c.createFullBoxCtor(`senc`,`SampleEncryptionBox`),c.createFullBoxCtor(`sgpd`,`SampleGroupDescriptionBox`,function(e){this.grouping_type=e.readString(4),t.debug(`BoxParser`,`Found Sample Groups of type `+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];for(var n=e.readUint32(),r=0;r<n;r++){var a=c[this.grouping_type+`SampleGroupEntry`]?new c[this.grouping_type+`SampleGroupEntry`](this.grouping_type):new c.SampleGroupEntry(this.grouping_type);this.entries.push(a),this.version===1&&this.default_length===0?a.description_length=e.readUint32():a.description_length=this.default_length,a.write===c.SampleGroupEntry.prototype.write&&(t.info(`BoxParser`,`SampleGroup for type `+this.grouping_type+` writing not yet implemented, keeping unparsed data in memory for later write`),a.data=e.readUint8Array(a.description_length),e.position-=a.description_length),a.parse(e)}}),c.createFullBoxCtor(`sidx`,`CompressedSegmentIndexBox`,function(e){this.reference_ID=e.readUint32(),this.timescale=e.readUint32(),this.version===0?(this.earliest_presentation_time=e.readUint32(),this.first_offset=e.readUint32()):(this.earliest_presentation_time=e.readUint64(),this.first_offset=e.readUint64()),e.readUint16(),this.references=[];for(var t=e.readUint16(),n=0;n<t;n++){var r={};this.references.push(r);var a=e.readUint32();r.reference_type=a>>31&1,r.referenced_size=a&2147483647,r.subsegment_duration=e.readUint32(),a=e.readUint32(),r.starts_with_SAP=a>>31&1,r.SAP_type=a>>28&7,r.SAP_delta_time=a&268435455}}),c.SingleItemTypeReferenceBox=function(e,t,n,r){c.Box.call(this,e,t),this.hdr_size=n,this.start=r},c.SingleItemTypeReferenceBox.prototype=new c.Box,c.SingleItemTypeReferenceBox.prototype.parse=function(e){this.from_item_ID=e.readUint16();var t=e.readUint16();this.references=[];for(var n=0;n<t;n++)this.references[n]={},this.references[n].to_item_ID=e.readUint16()},c.SingleItemTypeReferenceBoxLarge=function(e,t,n,r){c.Box.call(this,e,t),this.hdr_size=n,this.start=r},c.SingleItemTypeReferenceBoxLarge.prototype=new c.Box,c.SingleItemTypeReferenceBoxLarge.prototype.parse=function(e){this.from_item_ID=e.readUint32();var t=e.readUint16();this.references=[];for(var n=0;n<t;n++)this.references[n]={},this.references[n].to_item_ID=e.readUint32()},c.createFullBoxCtor(`SmDm`,`SMPTE2086MasteringDisplayMetadataBox`,function(e){this.primaryRChromaticity_x=e.readUint16(),this.primaryRChromaticity_y=e.readUint16(),this.primaryGChromaticity_x=e.readUint16(),this.primaryGChromaticity_y=e.readUint16(),this.primaryBChromaticity_x=e.readUint16(),this.primaryBChromaticity_y=e.readUint16(),this.whitePointChromaticity_x=e.readUint16(),this.whitePointChromaticity_y=e.readUint16(),this.luminanceMax=e.readUint32(),this.luminanceMin=e.readUint32()}),c.createFullBoxCtor(`smhd`,`SoundMediaHeaderBox`,function(e){this.balance=e.readUint16(),e.readUint16()}),c.createFullBoxCtor(`ssix`,`CompressedSubsegmentIndexBox`,function(e){this.subsegments=[];for(var t=e.readUint32(),n=0;n<t;n++){var r={};this.subsegments.push(r),r.ranges=[];for(var a=e.readUint32(),o=0;o<a;o++){var s={};r.ranges.push(s),s.level=e.readUint8(),s.range_size=e.readUint24()}}}),c.createFullBoxCtor(`stco`,`ChunkOffsetBox`,function(e){var t=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(var n=0;n<t;n++)this.chunk_offsets.push(e.readUint32())}),c.createFullBoxCtor(`stdp`,`DegradationPriorityBox`,function(e){var t=(this.size-this.hdr_size)/2;this.priority=[];for(var n=0;n<t;n++)this.priority[n]=e.readUint16()}),c.createFullBoxCtor(`sthd`,`SubtitleMediaHeaderBox`),c.createFullBoxCtor(`stri`,`SubTrackInformationBox`,function(e){this.switch_group=e.readUint16(),this.alternate_group=e.readUint16(),this.sub_track_id=e.readUint32();var t=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var n=0;n<t;n++)this.attribute_list[n]=e.readUint32()}),c.createFullBoxCtor(`stsc`,`SampleToChunkBox`,function(e){var t=e.readUint32(),n;if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(n=0;n<t;n++)this.first_chunk.push(e.readUint32()),this.samples_per_chunk.push(e.readUint32()),this.sample_description_index.push(e.readUint32())}),c.createFullBoxCtor(`stsd`,`SampleDescriptionBox`,function(e){var n,r,a,o;for(this.entries=[],a=e.readUint32(),n=1;n<=a;n++)if(r=c.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),r.code===c.OK)c[r.type+`SampleEntry`]?(o=new c[r.type+`SampleEntry`](r.size),o.hdr_size=r.hdr_size,o.start=r.start):(t.warn(`BoxParser`,`Unknown sample entry type: `+r.type),o=new c.SampleEntry(r.type,r.size,r.hdr_size,r.start)),o.write===c.SampleEntry.prototype.write&&(t.info(`BoxParser`,`SampleEntry `+o.type+` box writing not yet implemented, keeping unparsed data in memory for later write`),o.parseDataAndRewind(e)),o.parse(e),this.entries.push(o);else return}),c.createFullBoxCtor(`stsg`,`SubTrackSampleGroupBox`,function(e){this.grouping_type=e.readUint32();var t=e.readUint16();this.group_description_index=[];for(var n=0;n<t;n++)this.group_description_index[n]=e.readUint32()}),c.createFullBoxCtor(`stsh`,`ShadowSyncSampleBox`,function(e){var t=e.readUint32(),n;if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(n=0;n<t;n++)this.shadowed_sample_numbers.push(e.readUint32()),this.sync_sample_numbers.push(e.readUint32())}),c.createFullBoxCtor(`stss`,`SyncSampleBox`,function(e){var t,n=e.readUint32();if(this.version===0)for(this.sample_numbers=[],t=0;t<n;t++)this.sample_numbers.push(e.readUint32())}),c.createFullBoxCtor(`stsz`,`SampleSizeBox`,function(e){var t;if(this.sample_sizes=[],this.version===0)for(this.sample_size=e.readUint32(),this.sample_count=e.readUint32(),t=0;t<this.sample_count;t++)this.sample_size===0?this.sample_sizes.push(e.readUint32()):this.sample_sizes[t]=this.sample_size}),c.createFullBoxCtor(`stts`,`TimeToSampleBox`,function(e){var n=e.readUint32(),r,a;if(this.sample_counts=[],this.sample_deltas=[],this.version===0)for(r=0;r<n;r++)this.sample_counts.push(e.readUint32()),a=e.readInt32(),a<0&&(t.warn(`BoxParser`,`File uses negative stts sample delta, using value 1 instead, sync may be lost!`),a=1),this.sample_deltas.push(a)}),c.createFullBoxCtor(`stvi`,`StereoVideoBox`,function(e){var t=e.readUint32();this.single_view_allowed=t&3,this.stereo_scheme=e.readUint32();var n=e.readUint32();this.stereo_indication_type=e.readString(n);var r,a;for(this.boxes=[];e.getPosition()<this.start+this.size;)if(r=c.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),r.code===c.OK)a=r.box,this.boxes.push(a),this[a.type]=a;else return}),c.createBoxCtor(`styp`,`SegmentTypeBox`,function(e){c.ftypBox.prototype.parse.call(this,e)}),c.createFullBoxCtor(`stz2`,`CompactSampleSizeBox`,function(e){var n,r;if(this.sample_sizes=[],this.version===0)if(this.reserved=e.readUint24(),this.field_size=e.readUint8(),r=e.readUint32(),this.field_size===4)for(n=0;n<r;n+=2){var a=e.readUint8();this.sample_sizes[n]=a>>4&15,this.sample_sizes[n+1]=a&15}else if(this.field_size===8)for(n=0;n<r;n++)this.sample_sizes[n]=e.readUint8();else if(this.field_size===16)for(n=0;n<r;n++)this.sample_sizes[n]=e.readUint16();else t.error(`BoxParser`,`Error in length field in stz2 box`)}),c.createFullBoxCtor(`subs`,`SubSampleInformationBox`,function(e){var t,n,r=e.readUint32(),a;for(this.entries=[],t=0;t<r;t++){var o={};if(this.entries[t]=o,o.sample_delta=e.readUint32(),o.subsamples=[],a=e.readUint16(),a>0)for(n=0;n<a;n++){var s={};o.subsamples.push(s),this.version==1?s.size=e.readUint32():s.size=e.readUint16(),s.priority=e.readUint8(),s.discardable=e.readUint8(),s.codec_specific_parameters=e.readUint32()}}}),c.createFullBoxCtor(`tenc`,`TrackEncryptionBox`,function(e){if(e.readUint8(),this.version===0)e.readUint8();else{var t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=c.parseHex16(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}),c.createFullBoxCtor(`tfdt`,`TrackFragmentBaseMediaDecodeTimeBox`,function(e){this.version==1?this.baseMediaDecodeTime=e.readUint64():this.baseMediaDecodeTime=e.readUint32()}),c.createFullBoxCtor(`tfhd`,`TrackFragmentHeaderBox`,function(e){var t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&c.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&c.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&c.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&c.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&c.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}),c.createFullBoxCtor(`tfra`,`TrackFragmentRandomAccessBox`,function(e){this.track_ID=e.readUint32(),e.readUint24();var t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];for(var n=e.readUint32(),r=0;r<n;r++)this.version===1?(this.time=e.readUint64(),this.moof_offset=e.readUint64()):(this.time=e.readUint32(),this.moof_offset=e.readUint32()),this.traf_number=e[`readUint`+8*(this.length_size_of_traf_num+1)](),this.trun_number=e[`readUint`+8*(this.length_size_of_trun_num+1)](),this.sample_number=e[`readUint`+8*(this.length_size_of_sample_num+1)]()}),c.createFullBoxCtor(`tkhd`,`TrackHeaderBox`,function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}),c.createBoxCtor(`tmax`,`hintmaxrelativetime`,function(e){this.time=e.readUint32()}),c.createBoxCtor(`tmin`,`hintminrelativetime`,function(e){this.time=e.readUint32()}),c.createBoxCtor(`totl`,`hintBytesSent`,function(e){this.bytessent=e.readUint32()}),c.createBoxCtor(`tpay`,`hintBytesSent`,function(e){this.bytessent=e.readUint32()}),c.createBoxCtor(`tpyl`,`hintBytesSent`,function(e){this.bytessent=e.readUint64()}),c.TrackGroupTypeBox.prototype.parse=function(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()},c.createTrackGroupCtor(`msrc`),c.TrackReferenceTypeBox=function(e,t,n,r){c.Box.call(this,e,t),this.hdr_size=n,this.start=r},c.TrackReferenceTypeBox.prototype=new c.Box,c.TrackReferenceTypeBox.prototype.parse=function(e){this.track_ids=e.readUint32Array((this.size-this.hdr_size)/4)},c.trefBox.prototype.parse=function(e){for(var n,r;e.getPosition()<this.start+this.size;)if(n=c.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),n.code===c.OK)r=new c.TrackReferenceTypeBox(n.type,n.size,n.hdr_size,n.start),r.write===c.Box.prototype.write&&r.type!==`mdat`&&(t.info(`BoxParser`,`TrackReference `+r.type+` box writing not yet implemented, keeping unparsed data in memory for later write`),r.parseDataAndRewind(e)),r.parse(e),this.boxes.push(r);else return},c.createFullBoxCtor(`trep`,`TrackExtensionPropertiesBox`,function(e){for(this.track_ID=e.readUint32(),this.boxes=[];e.getPosition()<this.start+this.size;)if(ret=c.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),ret.code===c.OK)box=ret.box,this.boxes.push(box);else return}),c.createFullBoxCtor(`trex`,`TrackExtendsBox`,function(e){this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}),c.createBoxCtor(`trpy`,`hintBytesSent`,function(e){this.bytessent=e.readUint64()}),c.createFullBoxCtor(`trun`,`TrackRunBox`,function(e){var t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&c.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&c.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(var n=0;n<this.sample_count;n++)this.flags&c.TRUN_FLAGS_DURATION&&(this.sample_duration[n]=e.readUint32()),this.flags&c.TRUN_FLAGS_SIZE&&(this.sample_size[n]=e.readUint32()),this.flags&c.TRUN_FLAGS_FLAGS&&(this.sample_flags[n]=e.readUint32()),this.flags&c.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[n]=e.readUint32():this.sample_composition_time_offset[n]=e.readInt32())}),c.createFullBoxCtor(`tsel`,`TrackSelectionBox`,function(e){this.switch_group=e.readUint32();var t=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var n=0;n<t;n++)this.attribute_list[n]=e.readUint32()}),c.createFullBoxCtor(`txtC`,`TextConfigBox`,function(e){this.config=e.readCString()}),c.createBoxCtor(`tyco`,`TypeCombinationBox`,function(e){var t=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var n=0;n<t;n++)this.compatible_brands[n]=e.readString(4)}),c.createFullBoxCtor(`udes`,`UserDescriptionProperty`,function(e){this.lang=e.readCString(),this.name=e.readCString(),this.description=e.readCString(),this.tags=e.readCString()}),c.createFullBoxCtor(`uncC`,`UncompressedFrameConfigBox`,function(e){var t;if(this.profile=e.readString(4),this.version!=1&&this.version==0){for(this.component_count=e.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16()),this.component_bit_depth_minus_one.push(e.readUint8()),this.component_format.push(e.readUint8()),this.component_align_size.push(e.readUint8());this.sampling_type=e.readUint8(),this.interleave_type=e.readUint8(),this.block_size=e.readUint8();var n=e.readUint8();this.component_little_endian=n>>7&1,this.block_pad_lsb=n>>6&1,this.block_little_endian=n>>5&1,this.block_reversed=n>>4&1,this.pad_unknown=n>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}),c.createFullBoxCtor(`url `,`DataEntryUrlBox`,function(e){this.flags!==1&&(this.location=e.readCString())}),c.createFullBoxCtor(`urn `,`DataEntryUrnBox`,function(e){this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}),c.createUUIDBox(`a5d40b30e81411ddba2f0800200c9a66`,`LiveServerManifestBox`,!0,!1,function(e){this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}),c.createUUIDBox(`d08a4f1810f34a82b6c832d8aba183d3`,`PiffProtectionSystemSpecificHeaderBox`,!0,!1,function(e){this.system_id=c.parseHex16(e);var t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}),c.createUUIDBox(`a2394f525a9b4f14a2446c427c648df4`,`PiffSampleEncryptionBox`,!0,!1),c.createUUIDBox(`8974dbce7be74c5184f97148f9882554`,`PiffTrackEncryptionBox`,!0,!1,function(e){this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=c.parseHex16(e)}),c.createUUIDBox(`d4807ef2ca3946958e5426cb9e46a79f`,`TfrfBox`,!0,!1,function(e){this.fragment_count=e.readUint8(),this.entries=[];for(var t=0;t<this.fragment_count;t++){var n={},r=0,a=0;this.version===1?(r=e.readUint64(),a=e.readUint64()):(r=e.readUint32(),a=e.readUint32()),n.absolute_time=r,n.absolute_duration=a,this.entries.push(n)}}),c.createUUIDBox(`6d1d9b0542d544e680e2141daff757b2`,`TfxdBox`,!0,!1,function(e){this.version===1?(this.absolute_time=e.readUint64(),this.duration=e.readUint64()):(this.absolute_time=e.readUint32(),this.duration=e.readUint32())}),c.createFullBoxCtor(`vmhd`,`VideoMediaHeaderBox`,function(e){this.graphicsmode=e.readUint16(),this.opcolor=e.readUint16Array(3)}),c.createFullBoxCtor(`vpcC`,`VPCodecConfigurationRecord`,function(e){var t;this.version===1?(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)):(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize))}),c.createBoxCtor(`vttC`,`WebVTTConfigurationBox`,function(e){this.text=e.readString(this.size-this.hdr_size)}),c.createFullBoxCtor(`vvcC`,`VvcConfigurationBox`,function(e){var t,n,r={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(e){this.held_bits=e.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(e){this.held_bits=e.readUint16(),this.num_held_bits=16},extract_bits:function(e){var t=this.held_bits>>this.num_held_bits-e&(1<<e)-1;return this.num_held_bits-=e,t}};if(r.stream_read_1_bytes(e),r.extract_bits(5),this.lengthSizeMinusOne=r.extract_bits(2),this.ptl_present_flag=r.extract_bits(1),this.ptl_present_flag){if(r.stream_read_2_bytes(e),this.ols_idx=r.extract_bits(9),this.num_sublayers=r.extract_bits(3),this.constant_frame_rate=r.extract_bits(2),this.chroma_format_idc=r.extract_bits(2),r.stream_read_1_bytes(e),this.bit_depth_minus8=r.extract_bits(3),r.extract_bits(5),r.stream_read_2_bytes(e),r.extract_bits(2),this.num_bytes_constraint_info=r.extract_bits(6),this.general_profile_idc=r.extract_bits(7),this.general_tier_flag=r.extract_bits(1),this.general_level_idc=e.readUint8(),r.stream_read_1_bytes(e),this.ptl_frame_only_constraint_flag=r.extract_bits(1),this.ptl_multilayer_enabled_flag=r.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(t=0;t<this.num_bytes_constraint_info-1;t++){var a=r.extract_bits(6);r.stream_read_1_bytes(e);var o=r.extract_bits(2);this.general_constraint_info[t]=a<<2|o}this.general_constraint_info[this.num_bytes_constraint_info-1]=r.extract_bits(6)}else r.extract_bits(6);if(this.num_sublayers>1){for(r.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0,n=this.num_sublayers-2;n>=0;--n){var s=r.extract_bits(1);this.ptl_sublayer_present_mask|=s<<n}for(n=this.num_sublayers;n<=8&&this.num_sublayers>1;++n)r.extract_bits(1);for(this.sublayer_level_idc=[],n=this.num_sublayers-2;n>=0;--n)this.ptl_sublayer_present_mask&1<<n&&(this.sublayer_level_idc[n]=e.readUint8())}if(this.ptl_num_sub_profiles=e.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(t=0;t<this.ptl_num_sub_profiles;t++)this.general_sub_profile_idc.push(e.readUint32());this.max_picture_width=e.readUint16(),this.max_picture_height=e.readUint16(),this.avg_frame_rate=e.readUint16()}var c=12,l=13;this.nalu_arrays=[];var u=e.readUint8();for(t=0;t<u;t++){var d=[];this.nalu_arrays.push(d),r.stream_read_1_bytes(e),d.completeness=r.extract_bits(1),r.extract_bits(2),d.nalu_type=r.extract_bits(5);var f=1;for(d.nalu_type!=l&&d.nalu_type!=c&&(f=e.readUint16()),n=0;n<f;n++){var p=e.readUint16();d.push({data:e.readUint8Array(p),length:p})}}}),c.createFullBoxCtor(`vvnC`,`VvcNALUConfigBox`,function(e){var t=strm.readUint8();this.lengthSizeMinusOne=t&3}),c.SampleEntry.prototype.isVideo=function(){return!1},c.SampleEntry.prototype.isAudio=function(){return!1},c.SampleEntry.prototype.isSubtitle=function(){return!1},c.SampleEntry.prototype.isMetadata=function(){return!1},c.SampleEntry.prototype.isHint=function(){return!1},c.SampleEntry.prototype.getCodec=function(){return this.type.replace(`.`,``)},c.SampleEntry.prototype.getWidth=function(){return``},c.SampleEntry.prototype.getHeight=function(){return``},c.SampleEntry.prototype.getChannelCount=function(){return``},c.SampleEntry.prototype.getSampleRate=function(){return``},c.SampleEntry.prototype.getSampleSize=function(){return``},c.VisualSampleEntry.prototype.isVideo=function(){return!0},c.VisualSampleEntry.prototype.getWidth=function(){return this.width},c.VisualSampleEntry.prototype.getHeight=function(){return this.height},c.AudioSampleEntry.prototype.isAudio=function(){return!0},c.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},c.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},c.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},c.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},c.MetadataSampleEntry.prototype.isMetadata=function(){return!0},c.decimalToHex=function(e,t){var n=Number(e).toString(16);for(t??=t=2;n.length<t;)n=`0`+n;return n},c.avc1SampleEntry.prototype.getCodec=c.avc2SampleEntry.prototype.getCodec=c.avc3SampleEntry.prototype.getCodec=c.avc4SampleEntry.prototype.getCodec=function(){var e=c.SampleEntry.prototype.getCodec.call(this);return this.avcC?e+`.`+c.decimalToHex(this.avcC.AVCProfileIndication)+c.decimalToHex(this.avcC.profile_compatibility)+c.decimalToHex(this.avcC.AVCLevelIndication):e},c.hev1SampleEntry.prototype.getCodec=c.hvc1SampleEntry.prototype.getCodec=function(){var e,t=c.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(t+=`.`,this.hvcC.general_profile_space){case 0:t+=``;break;case 1:t+=`A`;break;case 2:t+=`B`;break;case 3:t+=`C`;break}t+=this.hvcC.general_profile_idc,t+=`.`;var n=this.hvcC.general_profile_compatibility,r=0;for(e=0;e<32&&(r|=n&1,e!=31);e++)r<<=1,n>>=1;t+=c.decimalToHex(r,0),t+=`.`,this.hvcC.general_tier_flag===0?t+=`L`:t+=`H`,t+=this.hvcC.general_level_idc;var a=!1,o=``;for(e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||a)&&(o=`.`+c.decimalToHex(this.hvcC.general_constraint_indicator[e],0)+o,a=!0);t+=o}return t},c.vvc1SampleEntry.prototype.getCodec=c.vvi1SampleEntry.prototype.getCodec=function(){var e,t=c.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){t+=`.`+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=`.H`:t+=`.L`,t+=this.vvcC.general_level_idc;var n=``;if(this.vvcC.general_constraint_info){var r=[],a=0;a|=this.vvcC.ptl_frame_only_constraint<<7,a|=this.vvcC.ptl_multilayer_enabled<<6;var o;for(e=0;e<this.vvcC.general_constraint_info.length;++e)a|=this.vvcC.general_constraint_info[e]>>2&63,r.push(a),a&&(o=e),a=this.vvcC.general_constraint_info[e]>>2&3;if(o===void 0)n=`.CA`;else{n=`.C`;var s=`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`,l=0,u=0;for(e=0;e<=o;++e)for(l=l<<8|r[e],u+=8;u>=5;){var d=l>>u-5&31;n+=s[d],u-=5,l&=(1<<u)-1}u&&(l<<=5-u,n+=s[l&31])}}t+=n}return t},c.mp4aSampleEntry.prototype.getCodec=function(){var e=c.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI(),n=this.esds.esd.getAudioConfig();return e+`.`+c.decimalToHex(t)+(n?`.`+n:``)}else return e},c.stxtSampleEntry.prototype.getCodec=function(){var e=c.SampleEntry.prototype.getCodec.call(this);return this.mime_format?e+`.`+this.mime_format:e},c.vp08SampleEntry.prototype.getCodec=c.vp09SampleEntry.prototype.getCodec=function(){var e=c.SampleEntry.prototype.getCodec.call(this),t=this.vpcC.level;t==0&&(t=`00`);var n=this.vpcC.bitDepth;return n==8&&(n=`08`),e+`.0`+this.vpcC.profile+`.`+t+`.`+n},c.av01SampleEntry.prototype.getCodec=function(){var e=c.SampleEntry.prototype.getCodec.call(this),t=this.av1C.seq_level_idx_0;t<10&&(t=`0`+t);var n;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?n=this.av1C.twelve_bit===1?`12`:`10`:this.av1C.seq_profile<=2&&(n=this.av1C.high_bitdepth===1?`10`:`08`),e+`.`+this.av1C.seq_profile+`.`+t+(this.av1C.seq_tier_0?`H`:`M`)+`.`+n},c.Box.prototype.writeHeader=function(e,n){this.size+=8,this.size>a&&(this.size+=8),this.type===`uuid`&&(this.size+=16),t.debug(`BoxWriter`,`Writing box `+this.type+` of size: `+this.size+` at position `+e.getPosition()+(n||``)),this.size>a?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,null,4),this.type===`uuid`&&e.writeUint8Array(this.uuid),this.size>a&&e.writeUint64(this.size)},c.FullBox.prototype.writeHeader=function(e){this.size+=4,c.Box.prototype.writeHeader.call(this,e,` v=`+this.version+` f=`+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)},c.Box.prototype.write=function(e){this.type===`mdat`?this.data&&(this.size=this.data.length,this.writeHeader(e),e.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data))},c.ContainerBox.prototype.write=function(e){this.size=0,this.writeHeader(e);for(var n=0;n<this.boxes.length;n++)this.boxes[n]&&(this.boxes[n].write(e),this.size+=this.boxes[n].size);t.debug(`BoxWriter`,`Adjusting box `+this.type+` with new size `+this.size),e.adjustUint32(this.sizePosition,this.size)},c.TrackReferenceTypeBox.prototype.write=function(e){this.size=this.track_ids.length*4,this.writeHeader(e),e.writeUint32Array(this.track_ids)},c.avcCBox.prototype.write=function(e){var t;for(this.size=7,t=0;t<this.SPS.length;t++)this.size+=2+this.SPS[t].length;for(t=0;t<this.PPS.length;t++)this.size+=2+this.PPS[t].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8(this.AVCProfileIndication),e.writeUint8(this.profile_compatibility),e.writeUint8(this.AVCLevelIndication),e.writeUint8(this.lengthSizeMinusOne+252),e.writeUint8(this.SPS.length+224),t=0;t<this.SPS.length;t++)e.writeUint16(this.SPS[t].length),e.writeUint8Array(this.SPS[t].nalu);for(e.writeUint8(this.PPS.length),t=0;t<this.PPS.length;t++)e.writeUint16(this.PPS[t].length),e.writeUint8Array(this.PPS[t].nalu);this.ext&&e.writeUint8Array(this.ext)},c.co64Box.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),t=0;t<this.chunk_offsets.length;t++)e.writeUint64(this.chunk_offsets[t])},c.cslgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=20,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)},c.cttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),this.version===1?e.writeInt32(this.sample_offsets[t]):e.writeUint32(this.sample_offsets[t])},c.drefBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.entries.length);for(var n=0;n<this.entries.length;n++)this.entries[n].write(e),this.size+=this.entries[n].size;t.debug(`BoxWriter`,`Adjusting box `+this.type+` with new size `+this.size),e.adjustUint32(this.sizePosition,this.size)},c.elngBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(e),e.writeString(this.extended_language)},c.elstBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var n=this.entries[t];e.writeUint32(n.segment_duration),e.writeInt32(n.media_time),e.writeInt16(n.media_rate_integer),e.writeInt16(n.media_rate_fraction)}},c.emsgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(e),e.writeCString(this.scheme_id_uri),e.writeCString(this.value),e.writeUint32(this.timescale),e.writeUint32(this.presentation_time_delta),e.writeUint32(this.event_duration),e.writeUint32(this.id),e.writeUint8Array(this.message_data)},c.ftypBox.prototype.write=function(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,null,4),e.writeUint32(this.minor_version);for(var t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],null,4)},c.hdlrBox.prototype.write=function(e){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,null,4),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeCString(this.name)},c.hvcCBox.prototype.write=function(e){var t,n;for(this.size=23,t=0;t<this.nalu_arrays.length;t++)for(this.size+=3,n=0;n<this.nalu_arrays[t].length;n++)this.size+=2+this.nalu_arrays[t][n].data.length;for(this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),e.writeUint32(this.general_profile_compatibility),e.writeUint8Array(this.general_constraint_indicator),e.writeUint8(this.general_level_idc),e.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),e.writeUint8(this.parallelismType+252),e.writeUint8(this.chroma_format_idc+252),e.writeUint8(this.bit_depth_luma_minus8+248),e.writeUint8(this.bit_depth_chroma_minus8+248),e.writeUint16(this.avgFrameRate),e.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),e.writeUint8(this.nalu_arrays.length),t=0;t<this.nalu_arrays.length;t++)for(e.writeUint8((this.nalu_arrays[t].completeness<<7)+this.nalu_arrays[t].nalu_type),e.writeUint16(this.nalu_arrays[t].length),n=0;n<this.nalu_arrays[t].length;n++)e.writeUint16(this.nalu_arrays[t][n].data.length),e.writeUint8Array(this.nalu_arrays[t][n].data)},c.kindBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(e),e.writeCString(this.schemeURI),e.writeCString(this.value)},c.mdhdBox.prototype.write=function(e){this.size=20,this.flags=0,this.version=0,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint16(this.language),e.writeUint16(0)},c.mehdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.fragment_duration)},c.mfhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)},c.mvhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=96,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)},c.SampleEntry.prototype.writeHeader=function(e){this.size=8,c.Box.prototype.writeHeader.call(this,e),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint16(this.data_reference_index)},c.SampleEntry.prototype.writeFooter=function(e){for(var n=0;n<this.boxes.length;n++)this.boxes[n].write(e),this.size+=this.boxes[n].size;t.debug(`BoxWriter`,`Adjusting box `+this.type+` with new size `+this.size),e.adjustUint32(this.sizePosition,this.size)},c.SampleEntry.prototype.write=function(e){this.writeHeader(e),e.writeUint8Array(this.data),this.size+=this.data.length,t.debug(`BoxWriter`,`Adjusting box `+this.type+` with new size `+this.size),e.adjustUint32(this.sizePosition,this.size)},c.VisualSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=70,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,null,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)},c.AudioSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=20,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)},c.stppSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,e.writeCString(this.namespace),e.writeCString(this.schema_location),e.writeCString(this.auxiliary_mime_types),this.writeFooter(e)},c.SampleGroupEntry.prototype.write=function(e){e.writeUint8Array(this.data)},c.sbgpBox.prototype.write=function(e){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(e),e.writeString(this.grouping_type,null,4),e.writeUint32(this.grouping_type_parameter),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var n=this.entries[t];e.writeInt32(n.sample_count),e.writeInt32(n.group_description_index)}},c.sgpdBox.prototype.write=function(e){var t,n;for(this.flags=0,this.size=12,t=0;t<this.entries.length;t++)n=this.entries[t],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=n.data.length);for(this.writeHeader(e),e.writeString(this.grouping_type,null,4),this.version===1&&e.writeUint32(this.default_length),this.version>=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length),t=0;t<this.entries.length;t++)n=this.entries[t],this.version===1&&this.default_length===0&&e.writeUint32(n.description_length),n.write(e)},c.sidxBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=20+12*this.references.length,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset),e.writeUint16(0),e.writeUint16(this.references.length);for(var t=0;t<this.references.length;t++){var n=this.references[t];e.writeUint32(n.reference_type<<31|n.referenced_size),e.writeUint32(n.subsegment_duration),e.writeUint32(n.starts_with_SAP<<31|n.SAP_type<<28|n.SAP_delta_time)}},c.smhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=4,this.writeHeader(e),e.writeUint16(this.balance),e.writeUint16(0)},c.stcoBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),e.writeUint32Array(this.chunk_offsets)},c.stscBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(e),e.writeUint32(this.first_chunk.length),t=0;t<this.first_chunk.length;t++)e.writeUint32(this.first_chunk[t]),e.writeUint32(this.samples_per_chunk[t]),e.writeUint32(this.sample_description_index[t])},c.stsdBox.prototype.write=function(e){var n;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(e),e.writeUint32(this.entries.length),this.size+=4,n=0;n<this.entries.length;n++)this.entries[n].write(e),this.size+=this.entries[n].size;t.debug(`BoxWriter`,`Adjusting box `+this.type+` with new size `+this.size),e.adjustUint32(this.sizePosition,this.size)},c.stshBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(e),e.writeUint32(this.shadowed_sample_numbers.length),t=0;t<this.shadowed_sample_numbers.length;t++)e.writeUint32(this.shadowed_sample_numbers[t]),e.writeUint32(this.sync_sample_numbers[t])},c.stssBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(e),e.writeUint32(this.sample_numbers.length),e.writeUint32Array(this.sample_numbers)},c.stszBox.prototype.write=function(e){var t,n=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(t=0;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){n=!1;break}else t++;else n=!1;this.size=8,n||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),n?e.writeUint32(this.sample_sizes[0]):e.writeUint32(0),e.writeUint32(this.sample_sizes.length),n||e.writeUint32Array(this.sample_sizes)},c.sttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),e.writeUint32(this.sample_deltas[t])},c.tfdtBox.prototype.write=function(e){var t=2**32-1;this.version=+(this.baseMediaDecodeTime>t),this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(e),this.version===1?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)},c.tfhdBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&c.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&c.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&c.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&c.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&c.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&c.TFHD_FLAG_BASE_DATA_OFFSET&&e.writeUint64(this.base_data_offset),this.flags&c.TFHD_FLAG_SAMPLE_DESC&&e.writeUint32(this.default_sample_description_index),this.flags&c.TFHD_FLAG_SAMPLE_DUR&&e.writeUint32(this.default_sample_duration),this.flags&c.TFHD_FLAG_SAMPLE_SIZE&&e.writeUint32(this.default_sample_size),this.flags&c.TFHD_FLAG_SAMPLE_FLAGS&&e.writeUint32(this.default_sample_flags)},c.tkhdBox.prototype.write=function(e){this.version=0,this.size=80,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration),e.writeUint32(0),e.writeUint32(0),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeUint16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)},c.trexBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=20,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)},c.trunBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&c.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&c.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&c.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&c.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&c.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&c.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(e),e.writeUint32(this.sample_count),this.flags&c.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=e.getPosition(),e.writeInt32(this.data_offset)),this.flags&c.TRUN_FLAGS_FIRST_FLAG&&e.writeUint32(this.first_sample_flags);for(var t=0;t<this.sample_count;t++)this.flags&c.TRUN_FLAGS_DURATION&&e.writeUint32(this.sample_duration[t]),this.flags&c.TRUN_FLAGS_SIZE&&e.writeUint32(this.sample_size[t]),this.flags&c.TRUN_FLAGS_FLAGS&&e.writeUint32(this.sample_flags[t]),this.flags&c.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?e.writeUint32(this.sample_composition_time_offset[t]):e.writeInt32(this.sample_composition_time_offset[t]))},c[`url Box`].prototype.write=function(e){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(e),this.location&&e.writeCString(this.location)},c[`urn Box`].prototype.write=function(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)},c.vmhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=8,this.writeHeader(e),e.writeUint16(this.graphicsmode),e.writeUint16Array(this.opcolor)},c.cttsBox.prototype.unpack=function(e){var t,n,r=0;for(t=0;t<this.sample_counts.length;t++)for(n=0;n<this.sample_counts[t];n++)e[r].pts=e[r].dts+this.sample_offsets[t],r++},c.sttsBox.prototype.unpack=function(e){var t,n,r=0;for(t=0;t<this.sample_counts.length;t++)for(n=0;n<this.sample_counts[t];n++)r===0?e[r].dts=0:e[r].dts=e[r-1].dts+this.sample_deltas[t],r++},c.stcoBox.prototype.unpack=function(e){var t;for(t=0;t<this.chunk_offsets.length;t++)e[t].offset=this.chunk_offsets[t]},c.stscBox.prototype.unpack=function(e){var t,n,r,a=0,o=0;for(t=0;t<this.first_chunk.length;t++)for(n=0;n<(t+1<this.first_chunk.length?this.first_chunk[t+1]:1/0);n++)for(o++,r=0;r<this.samples_per_chunk[t];r++){if(e[a])e[a].description_index=this.sample_description_index[t],e[a].chunk_index=o;else return;a++}},c.stszBox.prototype.unpack=function(e){var t;for(t=0;t<this.sample_sizes.length;t++)e[t].size=this.sample_sizes[t]},c.DIFF_BOXES_PROP_NAMES=[`boxes`,`entries`,`references`,`subsamples`,`items`,`item_infos`,`extents`,`associations`,`subsegments`,`ranges`,`seekLists`,`seekPoints`,`esd`,`levels`],c.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=[`compatible_brands`,`matrix`,`opcolor`,`sample_counts`,`sample_deltas`,`first_chunk`,`samples_per_chunk`,`sample_sizes`,`chunk_offsets`,`sample_offsets`,`sample_description_index`,`sample_duration`],c.boxEqualFields=function(e,t){if(e&&!t)return!1;for(var n in e)if(c.DIFF_BOXES_PROP_NAMES.indexOf(n)>-1)continue;else if(e[n]instanceof c.Box||t[n]instanceof c.Box)continue;else if(e[n]===void 0||t[n]===void 0)continue;else if(typeof e[n]==`function`||typeof t[n]==`function`)continue;else if(e.subBoxNames&&e.subBoxNames.indexOf(n.slice(0,4))>-1||t.subBoxNames&&t.subBoxNames.indexOf(n.slice(0,4))>-1)continue;else if(n===`data`||n===`start`||n===`size`||n===`creation_time`||n===`modification_time`)continue;else if(c.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(n)>-1)continue;else if(e[n]!==t[n])return!1;return!0},c.boxEqual=function(e,t){if(!c.boxEqualFields(e,t))return!1;for(var n=0;n<c.DIFF_BOXES_PROP_NAMES.length;n++){var r=c.DIFF_BOXES_PROP_NAMES[n];if(e[r]&&t[r]&&!c.boxEqual(e[r],t[r]))return!1}return!0};var f=function(){};f.prototype.parseSample=function(e){var t,r,a=new n(e.buffer);for(t=[];!a.isEos();)r=c.parseOneBox(a,!1),r.code===c.OK&&r.box.type===`vttc`&&t.push(r.box);return t},f.prototype.getText=function(e,t,n){function r(e,t,n){return n||=`0`,e+=``,e.length>=t?e:Array(t-e.length+1).join(n)+e}function a(e){var t=Math.floor(e/3600),n=Math.floor((e-t*3600)/60),a=Math.floor(e-t*3600-n*60),o=Math.floor((e-t*3600-n*60-a)*1e3);return``+r(t,2)+`:`+r(n,2)+`:`+r(a,2)+`.`+r(o,3)}for(var o=this.parseSample(n),s=``,c=0;c<o.length;c++){var l=o[c];s+=a(e)+` --> `+a(t)+`\r
|
|
114
|
-
`,s+=l.payl.text}return s};var p=function(){};p.prototype.parseSample=function(e){var t={},r;t.resources=[];var a=new n(e.data.buffer);if(!e.subsamples||e.subsamples.length===0)t.documentString=a.readString(e.data.length);else if(t.documentString=a.readString(e.subsamples[0].size),e.subsamples.length>1)for(r=1;r<e.subsamples.length;r++)t.resources[r]=a.readUint8Array(e.subsamples[r].size);return typeof DOMParser<`u`&&(t.document=new DOMParser().parseFromString(t.documentString,`application/xml`)),t};var m=function(){};m.prototype.parseSample=function(e){return new n(e.data.buffer).readString(e.data.length)},m.prototype.parseConfig=function(e){var t,r=new n(e.buffer);return r.readUint32(),t=r.readCString(),t},e!==void 0&&(e.VTTin4Parser=f,e.XMLSubtitlein4Parser=p,e.Textin4Parser=m);var h=function(e){this.stream=e||new o,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};h.prototype.setSegmentOptions=function(e,t,n){var r=this.getTrackById(e);if(r){var a={};this.fragmentedTracks.push(a),a.id=e,a.user=t,a.trak=r,r.nextSample=0,a.segmentStream=null,a.nb_samples=1e3,a.rapAlignement=!0,n&&(n.nbSamples&&(a.nb_samples=n.nbSamples),n.rapAlignement&&(a.rapAlignement=n.rapAlignement))}},h.prototype.unsetSegmentOptions=function(e){for(var t=-1,n=0;n<this.fragmentedTracks.length;n++)this.fragmentedTracks[n].id==e&&(t=n);t>-1&&this.fragmentedTracks.splice(t,1)},h.prototype.setExtractionOptions=function(e,t,n){var r=this.getTrackById(e);if(r){var a={};this.extractedTracks.push(a),a.id=e,a.user=t,a.trak=r,r.nextSample=0,a.nb_samples=1e3,a.samples=[],n&&n.nbSamples&&(a.nb_samples=n.nbSamples)}},h.prototype.unsetExtractionOptions=function(e){for(var t=-1,n=0;n<this.extractedTracks.length;n++)this.extractedTracks[n].id==e&&(t=n);t>-1&&this.extractedTracks.splice(t,1)},h.prototype.parse=function(){var e,n,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),e=c.parseOneBox(this.stream,r),e.code===c.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else{var a;switch(n=e.box,a=n.type===`uuid`?n.uuid:n.type,this.boxes.push(n),a){case`mdat`:this.mdats.push(n);break;case`moof`:this.moofs.push(n);break;case`moov`:this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[a]!==void 0&&t.warn(`ISOFile`,`Duplicate Box of type: `+a+`, overriding previous occurrence`),this[a]=n;break}this.updateUsedBytes&&this.updateUsedBytes(n,e)}},h.prototype.checkBuffer=function(e){if(e==null)throw`Buffer must be defined and non empty`;if(e.fileStart===void 0)throw`Buffer must have a fileStart property`;return e.byteLength===0?(t.warn(`ISOFile`,`Ignoring empty buffer (fileStart: `+e.fileStart+`)`),this.stream.logBufferLevel(),!1):(t.info(`ISOFile`,`Processing buffer (fileStart: `+e.fileStart+`)`),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(t.warn(`ISOFile`,`Not ready to start parsing`),!1))},h.prototype.appendBuffer=function(e,n){var r;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||=(this.buildSampleLists(),!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(n),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):r=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(t.info(`ISOFile`,`Done processing buffer (fileStart: `+e.fileStart+`) - next buffer to fetch should have a fileStart position of `+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),t.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize())),r},h.prototype.getInfo=function(){var e,t,n={},r,a,o,s,c=new Date(`1904-01-01T00:00:00Z`).getTime();if(this.moov)for(n.hasMoov=!0,n.duration=this.moov.mvhd.duration,n.timescale=this.moov.mvhd.timescale,n.isFragmented=this.moov.mvex!=null,n.isFragmented&&this.moov.mvex.mehd&&(n.fragment_duration=this.moov.mvex.mehd.fragment_duration),n.isProgressive=this.isProgressive,n.hasIOD=this.moov.iods!=null,n.brands=[],n.brands.push(this.ftyp.major_brand),n.brands=n.brands.concat(this.ftyp.compatible_brands),n.created=new Date(c+this.moov.mvhd.creation_time*1e3),n.modified=new Date(c+this.moov.mvhd.modification_time*1e3),n.tracks=[],n.audioTracks=[],n.videoTracks=[],n.subtitleTracks=[],n.metadataTracks=[],n.hintTracks=[],n.otherTracks=[],e=0;e<this.moov.traks.length;e++){if(r=this.moov.traks[e],s=r.mdia.minf.stbl.stsd.entries[0],a={},n.tracks.push(a),a.id=r.tkhd.track_id,a.name=r.mdia.hdlr.name,a.references=[],r.tref)for(t=0;t<r.tref.boxes.length;t++)o={},a.references.push(o),o.type=r.tref.boxes[t].type,o.track_ids=r.tref.boxes[t].track_ids;r.edts&&(a.edits=r.edts.elst.entries),a.created=new Date(c+r.tkhd.creation_time*1e3),a.modified=new Date(c+r.tkhd.modification_time*1e3),a.movie_duration=r.tkhd.duration,a.movie_timescale=n.timescale,a.layer=r.tkhd.layer,a.alternate_group=r.tkhd.alternate_group,a.volume=r.tkhd.volume,a.matrix=r.tkhd.matrix,a.track_width=r.tkhd.width/65536,a.track_height=r.tkhd.height/65536,a.timescale=r.mdia.mdhd.timescale,a.cts_shift=r.mdia.minf.stbl.cslg,a.duration=r.mdia.mdhd.duration,a.samples_duration=r.samples_duration,a.codec=s.getCodec(),a.kind=r.udta&&r.udta.kinds.length?r.udta.kinds[0]:{schemeURI:``,value:``},a.language=r.mdia.elng?r.mdia.elng.extended_language:r.mdia.mdhd.languageString,a.nb_samples=r.samples.length,a.size=r.samples_size,a.bitrate=a.size*8*a.timescale/a.samples_duration,s.isAudio()?(a.type=`audio`,n.audioTracks.push(a),a.audio={},a.audio.sample_rate=s.getSampleRate(),a.audio.channel_count=s.getChannelCount(),a.audio.sample_size=s.getSampleSize()):s.isVideo()?(a.type=`video`,n.videoTracks.push(a),a.video={},a.video.width=s.getWidth(),a.video.height=s.getHeight()):s.isSubtitle()?(a.type=`subtitles`,n.subtitleTracks.push(a)):s.isHint()?(a.type=`metadata`,n.hintTracks.push(a)):s.isMetadata()?(a.type=`metadata`,n.metadataTracks.push(a)):(a.type=`metadata`,n.otherTracks.push(a))}else n.hasMoov=!1;if(n.mime=``,n.hasMoov&&n.tracks){for(n.videoTracks&&n.videoTracks.length>0?n.mime+=`video/mp4; codecs="`:n.audioTracks&&n.audioTracks.length>0?n.mime+=`audio/mp4; codecs="`:n.mime+=`application/mp4; codecs="`,e=0;e<n.tracks.length;e++)e!==0&&(n.mime+=`,`),n.mime+=n.tracks[e].codec;n.mime+=`"; profiles="`,n.mime+=this.ftyp.compatible_brands.join(),n.mime+=`"`}return n},h.prototype.setNextSeekPositionFromSample=function(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)},h.prototype.processSamples=function(e){var n,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(n=0;n<this.fragmentedTracks.length;n++){var a=this.fragmentedTracks[n];for(r=a.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){t.debug(`ISOFile`,`Creating media fragment on track #`+a.id+` for sample `+r.nextSample);var o=this.createFragment(a.id,r.nextSample,a.segmentStream);if(o)a.segmentStream=o,r.nextSample++;else break;if((r.nextSample%a.nb_samples===0||e||r.nextSample>=r.samples.length)&&(t.info(`ISOFile`,`Sending fragmented data on track #`+a.id+` for samples [`+Math.max(0,r.nextSample-a.nb_samples)+`,`+(r.nextSample-1)+`]`),t.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(a.id,a.user,a.segmentStream.buffer,r.nextSample,e||r.nextSample>=r.samples.length),a.segmentStream=null,a!==this.fragmentedTracks[n]))break}}if(this.onSamples!==null)for(n=0;n<this.extractedTracks.length;n++){var s=this.extractedTracks[n];for(r=s.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){t.debug(`ISOFile`,`Exporting on track #`+s.id+` sample #`+r.nextSample);var c=this.getSample(r,r.nextSample);if(c)r.nextSample++,s.samples.push(c);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%s.nb_samples===0||r.nextSample>=r.samples.length)&&(t.debug(`ISOFile`,`Sending samples on track #`+s.id+` for sample `+r.nextSample),this.onSamples&&this.onSamples(s.id,s.user,s.samples),s.samples=[],s!==this.extractedTracks[n]))break}}}},h.prototype.getBox=function(e){var t=this.getBoxes(e,!0);return t.length?t[0]:null},h.prototype.getBoxes=function(e,t){var n=[];return h._sweep.call(this,e,n,t),n},h._sweep=function(e,t,n){for(var r in this.type&&this.type==e&&t.push(this),this.boxes){if(t.length&&n)return;h._sweep.call(this.boxes[r],e,t,n)}},h.prototype.getTrackSamplesInfo=function(e){var t=this.getTrackById(e);if(t)return t.samples},h.prototype.getTrackSample=function(e,t){var n=this.getTrackById(e);return this.getSample(n,t)},h.prototype.releaseUsedSamples=function(e,n){var r=0,a=this.getTrackById(e);a.lastValidSample||=0;for(var o=a.lastValidSample;o<n;o++)r+=this.releaseSample(a,o);t.info(`ISOFile`,`Track #`+e+` released samples up to `+n+` (released size: `+r+`, remaining: `+this.samplesDataSize+`)`),a.lastValidSample=n},h.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},h.prototype.stop=function(){this.sampleProcessingStarted=!1},h.prototype.flush=function(){t.info(`ISOFile`,`Flushing remaining samples`),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},h.prototype.seekTrack=function(e,n,r){var a,o,s=1/0,c=0,l=0,u;if(r.samples.length===0)return t.info(`ISOFile`,`No sample in track, cannot seek! Using time `+t.getDurationString(0,1)+` and offset: 0`),{offset:0,time:0};for(a=0;a<r.samples.length;a++){if(o=r.samples[a],a===0)l=0,u=o.timescale;else if(o.cts>e*o.timescale){l=a-1;break}n&&o.is_sync&&(c=a)}for(n&&(l=c),e=r.samples[l].cts,r.nextSample=l;r.samples[l].alreadyRead===r.samples[l].size&&r.samples[l+1];)l++;return s=r.samples[l].offset+r.samples[l].alreadyRead,t.info(`ISOFile`,`Seeking to `+(n?`RAP`:``)+` sample #`+r.nextSample+` on track `+r.tkhd.track_id+`, time `+t.getDurationString(e,u)+` and offset: `+s),{offset:s,time:e/u}},h.prototype.getTrackDuration=function(e){var t;return e.samples?(t=e.samples[e.samples.length-1],(t.cts+t.duration)/t.timescale):1/0},h.prototype.seek=function(e,n){var r=this.moov,a,o,s,c={offset:1/0,time:1/0};if(this.moov){for(s=0;s<r.traks.length;s++)a=r.traks[s],!(e>this.getTrackDuration(a))&&(o=this.seekTrack(e,n,a),o.offset<c.offset&&(c.offset=o.offset),o.time<c.time&&(c.time=o.time));return t.info(`ISOFile`,`Seeking at time `+t.getDurationString(c.time,1)+` needs a buffer with a fileStart position of `+c.offset),c.offset===1/0?c={offset:this.nextParsePosition,time:0}:c.offset=this.stream.getEndFilePositionAfter(c.offset),t.info(`ISOFile`,`Adjusted seek position (after checking data already in buffer): `+c.offset),c}else throw`Cannot seek: moov not received!`},h.prototype.equal=function(e){for(var t=0;t<this.boxes.length&&t<e.boxes.length;){var n=this.boxes[t],r=e.boxes[t];if(!c.boxEqual(n,r))return!1;t++}return!0},e!==void 0&&(e.ISOFile=h),h.prototype.lastBoxStartPosition=0,h.prototype.parsingMdat=null,h.prototype.nextParsePosition=0,h.prototype.discardMdatData=!1,h.prototype.processIncompleteBox=function(e){var t,n,r;return e.type===`mdat`?(t=new c[e.type+`Box`](e.size),this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,r=this.stream.seek(t.start+t.size,!1,this.discardMdatData),r?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)):(e.type===`moov`&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),n=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,n?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},h.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},h.prototype.processIncompleteMdat=function(){var e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(t.debug(`ISOFile`,`Found 'mdat' end in buffered data`),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},h.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},h.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},h.prototype.updateUsedBytes=function(e,t){this.stream.addUsedBytes&&(e.type===`mdat`?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))},h.prototype.add=c.Box.prototype.add,h.prototype.addBox=c.Box.prototype.addBox,h.prototype.init=function(e){var t=e||{};this.add(`ftyp`).set(`major_brand`,t.brands&&t.brands[0]||`iso4`).set(`minor_version`,0).set(`compatible_brands`,t.brands||[`iso4`]);var n=this.add(`moov`);return n.add(`mvhd`).set(`timescale`,t.timescale||600).set(`rate`,t.rate||65536).set(`creation_time`,0).set(`modification_time`,0).set(`duration`,t.duration||0).set(`volume`,t.width?0:256).set(`matrix`,[65536,0,0,0,65536,0,0,0,1073741824]).set(`next_track_id`,1),n.add(`mvex`),this},h.prototype.addTrack=function(e){this.moov||this.init(e);var t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||`avc1`;var r=this.moov.add(`trak`);this.moov.mvhd.next_track_id=t.id+1,r.add(`tkhd`).set(`flags`,c.TKHD_FLAG_ENABLED|c.TKHD_FLAG_IN_MOVIE|c.TKHD_FLAG_IN_PREVIEW).set(`creation_time`,0).set(`modification_time`,0).set(`track_id`,t.id).set(`duration`,t.duration||0).set(`layer`,t.layer||0).set(`alternate_group`,0).set(`volume`,1).set(`matrix`,[65536,0,0,0,65536,0,0,0,1073741824]).set(`width`,t.width<<16).set(`height`,t.height<<16);var a=r.add(`mdia`);a.add(`mdhd`).set(`creation_time`,0).set(`modification_time`,0).set(`timescale`,t.timescale||1).set(`duration`,t.media_duration||0).set(`language`,t.language||`und`),a.add(`hdlr`).set(`handler`,t.hdlr||`vide`).set(`name`,t.name||`Track created with MP4Box.js`),a.add(`elng`).set(`extended_language`,t.language||`fr-FR`);var o=a.add(`minf`);if(c[t.type+`SampleEntry`]!==void 0){var s=new c[t.type+`SampleEntry`];s.data_reference_index=1;var l=``;for(var u in c.sampleEntryCodes)for(var d=c.sampleEntryCodes[u],f=0;f<d.length;f++)if(d.indexOf(t.type)>-1){l=u;break}switch(l){case`Visual`:if(o.add(`vmhd`).set(`graphicsmode`,0).set(`opcolor`,[0,0,0]),s.set(`width`,t.width).set(`height`,t.height).set(`horizresolution`,72<<16).set(`vertresolution`,72<<16).set(`frame_count`,1).set(`compressorname`,t.type+` Compressor`).set(`depth`,24),t.avcDecoderConfigRecord){var p=new c.avcCBox;p.parse(new n(t.avcDecoderConfigRecord)),s.addBox(p)}else if(t.hevcDecoderConfigRecord){var m=new c.hvcCBox;m.parse(new n(t.hevcDecoderConfigRecord)),s.addBox(m)}break;case`Audio`:o.add(`smhd`).set(`balance`,t.balance||0),s.set(`channel_count`,t.channel_count||2).set(`samplesize`,t.samplesize||16).set(`samplerate`,t.samplerate||65536);break;case`Hint`:o.add(`hmhd`);break;case`Subtitle`:switch(o.add(`sthd`),t.type){case`stpp`:s.set(`namespace`,t.namespace||`nonamespace`).set(`schema_location`,t.schema_location||``).set(`auxiliary_mime_types`,t.auxiliary_mime_types||``);break}break;case`Metadata`:o.add(`nmhd`);break;case`System`:o.add(`nmhd`);break;default:o.add(`nmhd`);break}t.description&&s.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(e){s.addBox(e)}),o.add(`dinf`).add(`dref`).addEntry(new c[`url Box`]().set(`flags`,1));var h=o.add(`stbl`);return h.add(`stsd`).addEntry(s),h.add(`stts`).set(`sample_counts`,[]).set(`sample_deltas`,[]),h.add(`stsc`).set(`first_chunk`,[]).set(`samples_per_chunk`,[]).set(`sample_description_index`,[]),h.add(`stco`).set(`chunk_offsets`,[]),h.add(`stsz`).set(`sample_sizes`,[]),this.moov.mvex.add(`trex`).set(`track_id`,t.id).set(`default_sample_description_index`,t.default_sample_description_index||1).set(`default_sample_duration`,t.default_sample_duration||0).set(`default_sample_size`,t.default_sample_size||0).set(`default_sample_flags`,t.default_sample_flags||0),this.buildTrakSampleLists(r),t.id}},c.Box.prototype.computeSize=function(e){var t=e||new r;t.endianness=r.BIG_ENDIAN,this.write(t)},h.prototype.addSample=function(e,t,n){var r=n||{},a={},o=this.getTrackById(e);if(o!==null){a.number=o.samples.length,a.track_id=o.tkhd.track_id,a.timescale=o.mdia.mdhd.timescale,a.description_index=r.sample_description_index?r.sample_description_index-1:0,a.description=o.mdia.minf.stbl.stsd.entries[a.description_index],a.data=t,a.size=t.byteLength,a.alreadyRead=a.size,a.duration=r.duration||1,a.cts=r.cts||0,a.dts=r.dts||0,a.is_sync=r.is_sync||!1,a.is_leading=r.is_leading||0,a.depends_on=r.depends_on||0,a.is_depended_on=r.is_depended_on||0,a.has_redundancy=r.has_redundancy||0,a.degradation_priority=r.degradation_priority||0,a.offset=0,a.subsamples=r.subsamples,o.samples.push(a),o.samples_size+=a.size,o.samples_duration+=a.duration,o.first_dts===void 0&&(o.first_dts=r.dts),this.processSamples();var s=this.createSingleSampleMoof(a);return this.addBox(s),s.computeSize(),s.trafs[0].truns[0].data_offset=s.size+8,this.add(`mdat`).data=new Uint8Array(t),a}},h.prototype.createSingleSampleMoof=function(e){var t=0;t=e.is_sync?1<<25:65536;var n=new c.moofBox;n.add(`mfhd`).set(`sequence_number`,this.nextMoofNumber),this.nextMoofNumber++;var r=n.add(`traf`),a=this.getTrackById(e.track_id);return r.add(`tfhd`).set(`track_id`,e.track_id).set(`flags`,c.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),r.add(`tfdt`).set(`baseMediaDecodeTime`,e.dts-(a.first_dts||0)),r.add(`trun`).set(`flags`,c.TRUN_FLAGS_DATA_OFFSET|c.TRUN_FLAGS_DURATION|c.TRUN_FLAGS_SIZE|c.TRUN_FLAGS_FLAGS|c.TRUN_FLAGS_CTS_OFFSET).set(`data_offset`,0).set(`first_sample_flags`,0).set(`sample_count`,1).set(`sample_duration`,[e.duration]).set(`sample_size`,[e.size]).set(`sample_flags`,[t]).set(`sample_composition_time_offset`,[e.cts-e.dts]),n},h.prototype.lastMoofIndex=0,h.prototype.samplesDataSize=0,h.prototype.resetTables=function(){var e,t,n,r,a,o,s,c;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,e=0;e<this.moov.traks.length;e++){t=this.moov.traks[e],t.tkhd.duration=0,t.mdia.mdhd.duration=0,n=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,n.chunk_offsets=[],r=t.mdia.minf.stbl.stsc,r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[],a=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,a.sample_sizes=[],o=t.mdia.minf.stbl.stts,o.sample_counts=[],o.sample_deltas=[],s=t.mdia.minf.stbl.ctts,s&&(s.sample_counts=[],s.sample_offsets=[]),c=t.mdia.minf.stbl.stss;var l=t.mdia.minf.stbl.boxes.indexOf(c);l!=-1&&(t.mdia.minf.stbl.boxes[l]=null)}},h.initSampleGroups=function(e,t,n,r,a){var o,s,c,l;function u(e,t,n){this.grouping_type=e,this.grouping_type_parameter=t,this.sbgp=n,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||=[],s=0;s<n.length;s++){for(l=n[s].grouping_type+`/`+n[s].grouping_type_parameter,c=new u(n[s].grouping_type,n[s].grouping_type_parameter,n[s]),t&&(t.sample_groups_info[l]=c),e.sample_groups_info[l]||(e.sample_groups_info[l]=c),o=0;o<r.length;o++)r[o].grouping_type===n[s].grouping_type&&(c.description=r[o],c.description.used=!0);if(a)for(o=0;o<a.length;o++)a[o].grouping_type===n[s].grouping_type&&(c.fragment_description=a[o],c.fragment_description.used=!0,c.is_fragment=!0)}if(!t)for(s=0;s<r.length;s++)!r[s].used&&r[s].version>=2&&(l=r[s].grouping_type+`/0`,c=new u(r[s].grouping_type,0),e.sample_groups_info[l]||(e.sample_groups_info[l]=c));else if(a)for(s=0;s<a.length;s++)!a[s].used&&a[s].version>=2&&(l=a[s].grouping_type+`/0`,c=new u(a[s].grouping_type,0),c.is_fragment=!0,t.sample_groups_info[l]||(t.sample_groups_info[l]=c))},h.setSampleGroupProperties=function(e,t,n,r){var a,o;for(a in t.sample_groups=[],r)if(t.sample_groups[a]={},t.sample_groups[a].grouping_type=r[a].grouping_type,t.sample_groups[a].grouping_type_parameter=r[a].grouping_type_parameter,n>=r[a].last_sample_in_run&&(r[a].last_sample_in_run<0&&(r[a].last_sample_in_run=0),r[a].entry_index++,r[a].entry_index<=r[a].sbgp.entries.length-1&&(r[a].last_sample_in_run+=r[a].sbgp.entries[r[a].entry_index].sample_count)),r[a].entry_index<=r[a].sbgp.entries.length-1?t.sample_groups[a].group_description_index=r[a].sbgp.entries[r[a].entry_index].group_description_index:t.sample_groups[a].group_description_index=-1,t.sample_groups[a].group_description_index!==0){var s=r[a].fragment_description?r[a].fragment_description:r[a].description;t.sample_groups[a].group_description_index>0?(o=t.sample_groups[a].group_description_index>65535?(t.sample_groups[a].group_description_index>>16)-1:t.sample_groups[a].group_description_index-1,s&&o>=0&&(t.sample_groups[a].description=s.entries[o])):s&&s.version>=2&&s.default_group_description_index>0&&(t.sample_groups[a].description=s.entries[s.default_group_description_index-1])}},h.process_sdtp=function(e,t,n){t&&(e?(t.is_leading=e.is_leading[n],t.depends_on=e.sample_depends_on[n],t.is_depended_on=e.sample_is_depended_on[n],t.has_redundancy=e.sample_has_redundancy[n]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))},h.prototype.buildSampleLists=function(){var e,t;for(e=0;e<this.moov.traks.length;e++)t=this.moov.traks[e],this.buildTrakSampleLists(t)},h.prototype.buildTrakSampleLists=function(e){var t,n,r,a,o,s,c,l,u,d,f,p,m,g,_,v,y,b,x,S,C,w,T,E;if(e.samples=[],e.samples_duration=0,e.samples_size=0,n=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,r=e.mdia.minf.stbl.stsc,a=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,o=e.mdia.minf.stbl.stts,s=e.mdia.minf.stbl.ctts,c=e.mdia.minf.stbl.stss,l=e.mdia.minf.stbl.stsd,u=e.mdia.minf.stbl.subs,p=e.mdia.minf.stbl.stdp,d=e.mdia.minf.stbl.sbgps,f=e.mdia.minf.stbl.sgpds,b=-1,x=-1,S=-1,C=-1,w=0,T=0,E=0,h.initSampleGroups(e,null,d,f),a!==void 0){for(t=0;t<a.sample_sizes.length;t++){var D={};D.number=t,D.track_id=e.tkhd.track_id,D.timescale=e.mdia.mdhd.timescale,D.alreadyRead=0,e.samples[t]=D,D.size=a.sample_sizes[t],e.samples_size+=D.size,t===0?(g=1,m=0,D.chunk_index=g,D.chunk_run_index=m,y=r.samples_per_chunk[m],v=0,_=m+1<r.first_chunk.length?r.first_chunk[m+1]-1:1/0):t<y?(D.chunk_index=g,D.chunk_run_index=m):(g++,D.chunk_index=g,v=0,g<=_||(m++,_=m+1<r.first_chunk.length?r.first_chunk[m+1]-1:1/0),D.chunk_run_index=m,y+=r.samples_per_chunk[m]),D.description_index=r.sample_description_index[D.chunk_run_index]-1,D.description=l.entries[D.description_index],D.offset=n.chunk_offsets[D.chunk_index-1]+v,v+=D.size,t>b&&(x++,b<0&&(b=0),b+=o.sample_counts[x]),t>0?(e.samples[t-1].duration=o.sample_deltas[x],e.samples_duration+=e.samples[t-1].duration,D.dts=e.samples[t-1].dts+e.samples[t-1].duration):D.dts=0,s?(t>=S&&(C++,S<0&&(S=0),S+=s.sample_counts[C]),D.cts=e.samples[t].dts+s.sample_offsets[C]):D.cts=D.dts,c?(t==c.sample_numbers[w]-1?(D.is_sync=!0,w++):(D.is_sync=!1,D.degradation_priority=0),u&&u.entries[T].sample_delta+E==t+1&&(D.subsamples=u.entries[T].subsamples,E+=u.entries[T].sample_delta,T++)):D.is_sync=!0,h.process_sdtp(e.mdia.minf.stbl.sdtp,D,D.number),p?D.degradation_priority=p.priority[t]:D.degradation_priority=0,u&&u.entries[T].sample_delta+E==t&&(D.subsamples=u.entries[T].subsamples,E+=u.entries[T].sample_delta),(d.length>0||f.length>0)&&h.setSampleGroupProperties(e,D,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}},h.prototype.updateSampleLists=function(){var e,t,n,r,a,o,s,l,u,d,f,p,m,g,_;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(u=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,u.type==`moof`)for(d=u,e=0;e<d.trafs.length;e++){for(f=d.trafs[e],p=this.getTrackById(f.tfhd.track_id),m=this.getTrexById(f.tfhd.track_id),r=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_DESC?f.tfhd.default_sample_description_index:m?m.default_sample_description_index:1,a=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_DUR?f.tfhd.default_sample_duration:m?m.default_sample_duration:0,o=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_SIZE?f.tfhd.default_sample_size:m?m.default_sample_size:0,s=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_FLAGS?f.tfhd.default_sample_flags:m?m.default_sample_flags:0,f.sample_number=0,f.sbgps.length>0&&h.initSampleGroups(p,f,f.sbgps,p.mdia.minf.stbl.sgpds,f.sgpds),t=0;t<f.truns.length;t++){var v=f.truns[t];for(n=0;n<v.sample_count;n++){g={},g.moof_number=this.lastMoofIndex,g.number_in_traf=f.sample_number,f.sample_number++,g.number=p.samples.length,f.first_sample_index=p.samples.length,p.samples.push(g),g.track_id=p.tkhd.track_id,g.timescale=p.mdia.mdhd.timescale,g.description_index=r-1,g.description=p.mdia.minf.stbl.stsd.entries[g.description_index],g.size=o,v.flags&c.TRUN_FLAGS_SIZE&&(g.size=v.sample_size[n]),p.samples_size+=g.size,g.duration=a,v.flags&c.TRUN_FLAGS_DURATION&&(g.duration=v.sample_duration[n]),p.samples_duration+=g.duration,p.first_traf_merged||n>0?g.dts=p.samples[p.samples.length-2].dts+p.samples[p.samples.length-2].duration:(f.tfdt?g.dts=f.tfdt.baseMediaDecodeTime:g.dts=0,p.first_traf_merged=!0),g.cts=g.dts,v.flags&c.TRUN_FLAGS_CTS_OFFSET&&(g.cts=g.dts+v.sample_composition_time_offset[n]),_=s,v.flags&c.TRUN_FLAGS_FLAGS?_=v.sample_flags[n]:n===0&&v.flags&c.TRUN_FLAGS_FIRST_FLAG&&(_=v.first_sample_flags),g.is_sync=!(_>>16&1),g.is_leading=_>>26&3,g.depends_on=_>>24&3,g.is_depended_on=_>>22&3,g.has_redundancy=_>>20&3,g.degradation_priority=_&65535;var y=!!(f.tfhd.flags&c.TFHD_FLAG_BASE_DATA_OFFSET),b=!!(f.tfhd.flags&c.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),x=!!(v.flags&c.TRUN_FLAGS_DATA_OFFSET),S=0;S=y?f.tfhd.base_data_offset:b||t===0?d.start:l,t===0&&n===0?x?g.offset=S+v.data_offset:g.offset=S:g.offset=l,l=g.offset+g.size,(f.sbgps.length>0||f.sgpds.length>0||p.mdia.minf.stbl.sbgps.length>0||p.mdia.minf.stbl.sgpds.length>0)&&h.setSampleGroupProperties(p,g,g.number_in_traf,f.sample_groups_info)}}if(f.subs){p.has_fragment_subsamples=!0;var C=f.first_sample_index;for(t=0;t<f.subs.entries.length;t++)C+=f.subs.entries[t].sample_delta,g=p.samples[C-1],g.subsamples=f.subs.entries[t].subsamples}}}},h.prototype.getSample=function(e,n){var a,o=e.samples[n];if(!this.moov)return null;if(!o.data)o.data=new Uint8Array(o.size),o.alreadyRead=0,this.samplesDataSize+=o.size,t.debug(`ISOFile`,`Allocating sample #`+n+` on track #`+e.tkhd.track_id+` of size `+o.size+` (total: `+this.samplesDataSize+`)`);else if(o.alreadyRead==o.size)return o;for(;;){var s=this.stream.findPosition(!0,o.offset+o.alreadyRead,!1);if(s>-1){a=this.stream.buffers[s];var c=a.byteLength-(o.offset+o.alreadyRead-a.fileStart);if(o.size-o.alreadyRead<=c)return t.debug(`ISOFile`,`Getting sample #`+n+` data (alreadyRead: `+o.alreadyRead+` offset: `+(o.offset+o.alreadyRead-a.fileStart)+` read size: `+(o.size-o.alreadyRead)+` full size: `+o.size+`)`),r.memcpy(o.data.buffer,o.alreadyRead,a,o.offset+o.alreadyRead-a.fileStart,o.size-o.alreadyRead),a.usedBytes+=o.size-o.alreadyRead,this.stream.logBufferLevel(),o.alreadyRead=o.size,o;if(c===0)return null;t.debug(`ISOFile`,`Getting sample #`+n+` partial data (alreadyRead: `+o.alreadyRead+` offset: `+(o.offset+o.alreadyRead-a.fileStart)+` read size: `+c+` full size: `+o.size+`)`),r.memcpy(o.data.buffer,o.alreadyRead,a,o.offset+o.alreadyRead-a.fileStart,c),o.alreadyRead+=c,a.usedBytes+=c,this.stream.logBufferLevel()}else return null}},h.prototype.releaseSample=function(e,t){var n=e.samples[t];return n.data?(this.samplesDataSize-=n.size,n.data=null,n.alreadyRead=0,n.size):0},h.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},h.prototype.getCodecs=function(){var e,t=``;for(e=0;e<this.moov.traks.length;e++){var n=this.moov.traks[e];e>0&&(t+=`,`),t+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return t},h.prototype.getTrexById=function(e){var t;if(!this.moov||!this.moov.mvex)return null;for(t=0;t<this.moov.mvex.trexs.length;t++){var n=this.moov.mvex.trexs[t];if(n.track_id==e)return n}return null},h.prototype.getTrackById=function(e){if(this.moov===void 0)return null;for(var t=0;t<this.moov.traks.length;t++){var n=this.moov.traks[t];if(n.tkhd.track_id==e)return n}return null},h.prototype.itemsDataSize=0,h.prototype.flattenItemInfo=function(){var e=this.items,n=this.entity_groups,r,a,o,s=this.meta;if(s!=null&&s.hdlr!==void 0&&s.iinf!==void 0){for(r=0;r<s.iinf.item_infos.length;r++)o={},o.id=s.iinf.item_infos[r].item_ID,e[o.id]=o,o.ref_to=[],o.name=s.iinf.item_infos[r].item_name,s.iinf.item_infos[r].protection_index>0&&(o.protection=s.ipro.protections[s.iinf.item_infos[r].protection_index-1]),s.iinf.item_infos[r].item_type?o.type=s.iinf.item_infos[r].item_type:o.type=`mime`,o.content_type=s.iinf.item_infos[r].content_type,o.content_encoding=s.iinf.item_infos[r].content_encoding,o.item_uri_type=s.iinf.item_infos[r].item_uri_type;if(s.grpl)for(r=0;r<s.grpl.boxes.length;r++)entity_group={},entity_group.id=s.grpl.boxes[r].group_id,entity_group.entity_ids=s.grpl.boxes[r].entity_ids,entity_group.type=s.grpl.boxes[r].type,n[entity_group.id]=entity_group;if(s.iloc)for(r=0;r<s.iloc.items.length;r++){var c=s.iloc.items[r];switch(o=e[c.item_ID],c.data_reference_index!==0&&(t.warn(`Item storage with reference to other files: not supported`),o.source=s.dinf.boxes[c.data_reference_index-1]),c.construction_method){case 0:break;case 1:break;case 2:t.warn(`Item storage with construction_method : not supported`);break}for(o.extents=[],o.size=0,a=0;a<c.extents.length;a++)o.extents[a]={},o.extents[a].offset=c.extents[a].extent_offset+c.base_offset,c.construction_method==1&&(o.extents[a].offset+=s.idat.start+s.idat.hdr_size),o.extents[a].length=c.extents[a].extent_length,o.extents[a].alreadyRead=0,o.size+=o.extents[a].length}if(s.pitm&&(e[s.pitm.item_id].primary=!0),s.iref)for(r=0;r<s.iref.references.length;r++){var l=s.iref.references[r];for(a=0;a<l.references.length;a++)e[l.from_item_ID].ref_to.push({type:l.type,id:l.references[a]})}if(s.iprp)for(var u=0;u<s.iprp.ipmas.length;u++){var d=s.iprp.ipmas[u];for(r=0;r<d.associations.length;r++){var f=d.associations[r];if(o=e[f.id],o||=n[f.id],o)for(o.properties===void 0&&(o.properties={},o.properties.boxes=[]),a=0;a<f.props.length;a++){var p=f.props[a];if(p.property_index>0&&p.property_index-1<s.iprp.ipco.boxes.length){var m=s.iprp.ipco.boxes[p.property_index-1];o.properties[m.type]=m,o.properties.boxes.push(m)}}}}}},h.prototype.getItem=function(e){var n,a;if(!this.meta)return null;if(a=this.items[e],!a.data&&a.size)a.data=new Uint8Array(a.size),a.alreadyRead=0,this.itemsDataSize+=a.size,t.debug(`ISOFile`,`Allocating item #`+e+` of size `+a.size+` (total: `+this.itemsDataSize+`)`);else if(a.alreadyRead===a.size)return a;for(var o=0;o<a.extents.length;o++){var s=a.extents[o];if(s.alreadyRead!==s.length){var c=this.stream.findPosition(!0,s.offset+s.alreadyRead,!1);if(c>-1){n=this.stream.buffers[c];var l=n.byteLength-(s.offset+s.alreadyRead-n.fileStart);if(s.length-s.alreadyRead<=l)t.debug(`ISOFile`,`Getting item #`+e+` extent #`+o+` data (alreadyRead: `+s.alreadyRead+` offset: `+(s.offset+s.alreadyRead-n.fileStart)+` read size: `+(s.length-s.alreadyRead)+` full extent size: `+s.length+` full item size: `+a.size+`)`),r.memcpy(a.data.buffer,a.alreadyRead,n,s.offset+s.alreadyRead-n.fileStart,s.length-s.alreadyRead),n.usedBytes+=s.length-s.alreadyRead,this.stream.logBufferLevel(),a.alreadyRead+=s.length-s.alreadyRead,s.alreadyRead=s.length;else return t.debug(`ISOFile`,`Getting item #`+e+` extent #`+o+` partial data (alreadyRead: `+s.alreadyRead+` offset: `+(s.offset+s.alreadyRead-n.fileStart)+` read size: `+l+` full extent size: `+s.length+` full item size: `+a.size+`)`),r.memcpy(a.data.buffer,a.alreadyRead,n,s.offset+s.alreadyRead-n.fileStart,l),s.alreadyRead+=l,a.alreadyRead+=l,n.usedBytes+=l,this.stream.logBufferLevel(),null}else return null}}return a.alreadyRead===a.size?a:null},h.prototype.releaseItem=function(e){var t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=null,t.alreadyRead=0;for(var n=0;n<t.extents.length;n++){var r=t.extents[n];r.alreadyRead=0}return t.size}else return 0},h.prototype.processItems=function(e){for(var t in this.items){var n=this.items[t];this.getItem(n.id),e&&!n.sent&&(e(n),n.sent=!0,n.data=null)}},h.prototype.hasItem=function(e){for(var t in this.items){var n=this.items[t];if(n.name===e)return n.id}return-1},h.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},h.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},h.prototype.itemToFragmentedTrackFile=function(e){var t=e||{},n=null;if(n=t.itemId?this.getItem(t.itemId):this.getPrimaryItem(),n==null)return null;var r=new h;r.discardMdatData=!1;var a={type:n.type,description_boxes:n.properties.boxes};n.properties.ispe&&(a.width=n.properties.ispe.image_width,a.height=n.properties.ispe.image_height);var o=r.addTrack(a);return o?(r.addSample(o,n.data),r):null},h.prototype.write=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e)},h.prototype.createFragment=function(e,n,a){var o=this.getTrackById(e),s=this.getSample(o,n);if(s==null)return this.setNextSeekPositionFromSample(o.samples[n]),null;var l=a||new r;l.endianness=r.BIG_ENDIAN;var u=this.createSingleSampleMoof(s);u.write(l),u.trafs[0].truns[0].data_offset=u.size+8,t.debug(`MP4Box`,`Adjusting data_offset with new value `+u.trafs[0].truns[0].data_offset),l.adjustUint32(u.trafs[0].truns[0].data_offset_position,u.trafs[0].truns[0].data_offset);var d=new c.mdatBox;return d.data=s.data,d.write(l),l},h.writeInitializationSegment=function(e,n,a,o){var s;t.debug(`ISOFile`,`Generating initialization segment`);var c=new r;c.endianness=r.BIG_ENDIAN,e.write(c);var l=n.add(`mvex`);for(a&&l.add(`mehd`).set(`fragment_duration`,a),s=0;s<n.traks.length;s++)l.add(`trex`).set(`track_id`,n.traks[s].tkhd.track_id).set(`default_sample_description_index`,1).set(`default_sample_duration`,o).set(`default_sample_size`,0).set(`default_sample_flags`,65536);return n.write(c),c.buffer},h.prototype.save=function(e){var t=new r;t.endianness=r.BIG_ENDIAN,this.write(t),t.save(e)},h.prototype.getBuffer=function(){var e=new r;return e.endianness=r.BIG_ENDIAN,this.write(e),e.buffer},h.prototype.initializeSegmentation=function(){var e,n,r,a;for(this.onSegment===null&&t.warn(`MP4Box`,`No segmentation callback set!`),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),n=[],e=0;e<this.fragmentedTracks.length;e++){var o=new c.moovBox;o.mvhd=this.moov.mvhd,o.boxes.push(o.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),o.boxes.push(r),o.traks.push(r),a={},a.id=r.tkhd.track_id,a.user=this.fragmentedTracks[e].user,a.buffer=h.writeInitializationSegment(this.ftyp,o,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[e].samples.length>0?this.moov.traks[e].samples[0].duration:0),n.push(a)}return n},c.Box.prototype.printHeader=function(e){this.size+=8,this.size>a&&(this.size+=8),this.type===`uuid`&&(this.size+=16),e.log(e.indent+`size:`+this.size),e.log(e.indent+`type:`+this.type)},c.FullBox.prototype.printHeader=function(e){this.size+=4,c.Box.prototype.printHeader.call(this,e),e.log(e.indent+`version:`+this.version),e.log(e.indent+`flags:`+this.flags)},c.Box.prototype.print=function(e){this.printHeader(e)},c.ContainerBox.prototype.print=function(e){this.printHeader(e);for(var t=0;t<this.boxes.length;t++)if(this.boxes[t]){var n=e.indent;e.indent+=` `,this.boxes[t].print(e),e.indent=n}},h.prototype.print=function(e){e.indent=``;for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)},c.mvhdBox.prototype.print=function(e){c.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`timescale: `+this.timescale),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`rate: `+this.rate),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`next_track_id: `+this.next_track_id)},c.tkhdBox.prototype.print=function(e){c.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`track_id: `+this.track_id),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`layer: `+this.layer),e.log(e.indent+`alternate_group: `+this.alternate_group),e.log(e.indent+`width: `+this.width),e.log(e.indent+`height: `+this.height)};var g={};g.createFile=function(e,t){var n=e===void 0?!0:e,r=new h(t);return r.discardMdatData=!n,r},e!==void 0&&(e.createFile=g.createFile)}))()),cJ=class extends Error{unsupported=!0;codec;constructor(e){super(`unsupported codec: ${e}`),this.name=`UnsupportedCodecError`,this.codec=e}};function lJ(e){return e instanceof Error&&e.unsupported===!0}function uJ(e){return e.replace(/^hev1\./i,`hvc1.`)}function dJ(e,t){let n=e.getTrackById(t)?.mdia?.minf?.stbl?.stsd?.entries??[];for(let e of n){let t=e.hvcC??e.avcC;if(t){let e=new sJ.DataStream(void 0,0,sJ.DataStream.BIG_ENDIAN);return t.write(e),new Uint8Array(e.buffer,8)}}}function fJ(e,t){if(e.length===0)return null;let n=e.findIndex(e=>e.is_sync);n<0&&(n=0);let r=e[n],a=r.cts/r.timescale*1e3,o=n;for(let r=n+1;r<e.length;r++){let n=e[r];if(n.cts/n.timescale*1e3-a<=t)o=r;else break}return{start:n,end:o}}function pJ(e,t){return new Promise((n,r)=>{e.onError=e=>r(Error(`mp4box: ${e}`)),e.onReady=t=>{let a=t.videoTracks?.[0];if(!a){r(Error(`no video track`));return}let o=dJ(e,a.id);n({config:{codec:uJ(a.codec),codedWidth:a.video?.width,codedHeight:a.video?.height,...o?{description:o}:{}},trackId:a.id})};let a=t;a.fileStart=0,e.appendBuffer(a),e.flush()})}async function mJ(e){let t=sJ.createFile(),{config:n,trackId:r}=await pJ(t,e);return{config:n,chunk:await new Promise((e,n)=>{t.onSamples=(t,r,a)=>{let o=a.find(e=>e.is_sync)??a[0];if(!o){n(Error(`no sample`));return}e(new EncodedVideoChunk({type:`key`,timestamp:Math.round(o.cts/o.timescale*1e6),data:o.data}))},t.setExtractionOptions(r,null,{nbSamples:1}),t.start()})}}var hJ=2048;async function gJ(e,t){let n=sJ.createFile(),{config:r,trackId:a}=await pJ(n,e);return{config:r,chunks:await new Promise((e,r)=>{n.onSamples=(n,a,o)=>{let s=fJ(o,t);if(!s){r(Error(`no sample`));return}let c=[];for(let e=s.start;e<=s.end;e++){let t=o[e];c.push(new EncodedVideoChunk({type:t.is_sync?`key`:`delta`,timestamp:Math.round(t.cts/t.timescale*1e6),data:t.data}))}e(c)},n.setExtractionOptions(a,null,{nbSamples:hJ}),n.start()})}}var _J=class{decoder=null;async decodeSegment(e){let{config:t,chunk:n}=await mJ(e);if(!(await VideoDecoder.isConfigSupported(t)).supported)throw new cJ(t.codec);return await new Promise((e,r)=>{this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let a=new VideoDecoder({output:t=>e(t),error:e=>r(e)});a.configure(t),this.decoder=a,a.decode(n),a.flush().catch(r)})}async decodeSegmentAt(e,t){let{config:n,chunks:r}=await gJ(e,t);if(!(await VideoDecoder.isConfigSupported(n)).supported)throw new cJ(n.codec);return await new Promise((e,t)=>{this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let a=null,o=new VideoDecoder({output:e=>{a?.close(),a=e},error:e=>t(e)});o.configure(n),this.decoder=o;for(let e of r)o.decode(e);o.flush().then(()=>{a?e(a):t(Error(`no frame decoded`))}).catch(t)})}close(){this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}},vJ=class{windowMs;maxSamples;samples=[];constructor(e){this.windowMs=e.windowMs,this.maxSamples=Math.max(2,e.maxSamples??6)}add(e,t){this.samples.push({epochMs:e,at:t}),this.samples.length>this.maxSamples&&(this.samples=this.samples.slice(this.samples.length-this.maxSamples))}velocity(){if(this.samples.length<2)return 0;let e=this.samples[0],t=this.samples[this.samples.length-1],n=t.at-e.at;return n<=0?0:(t.epochMs-e.epochMs)/n}windowKey(e){return Math.floor(e/this.windowMs)*this.windowMs}projectedWindowKeys(e,t,n){let r=Math.max(1,n),a=this.windowKey(e),o=this.velocity();if(o===0)return[a,a-this.windowMs,a+this.windowMs].slice(0,r);let s=e+o*t,c=o>0?1:-1,l=[a],u=a;for(;l.length<r&&(u+=c*this.windowMs,!(c>0&&u>s+this.windowMs||c<0&&u<s-this.windowMs));)l.push(u);return l.slice(0,r)}reset(){this.samples=[]}};function yJ(e){return e instanceof Error&&e.unsupported===!0}var bJ=class extends Error{permanent=!0;constructor(e){super(e),this.name=`PackPermanentError`}};function xJ(e){return e instanceof Error&&e.permanent===!0}var SJ=class{deps;windowMs;maxWindows;states=new Map;lru=[];dead=!1;maxPrefetch;prefetchHorizonMs;tracker;prefetches=new Map;disposed=!1;scrubSeq=0;constructor(e){this.deps=e,this.windowMs=e.windowMs??6e4,this.maxWindows=e.maxWindows??8,this.maxPrefetch=e.maxPrefetch??3,this.prefetchHorizonMs=e.prefetchHorizonMs??400,this.tracker=new vJ({windowMs:this.windowMs})}windowKey(e){return Math.floor(e/this.windowMs)*this.windowMs}touch(e){let t=this.lru.indexOf(e);for(t>=0&&this.lru.splice(t,1),this.lru.push(e);this.lru.length>this.maxWindows;){let e=this.lru.shift();if(e===void 0)break;let t=this.states.get(e);t?.kind===`decoded`&&t.window.close(),this.states.delete(e)}}ensureWindow(e,t){let n=this.states.get(e);if(n?.kind===`decoded`)return Promise.resolve(n.window);if(n?.kind===`empty`)return Promise.resolve(null);if(n?.kind===`loading`)return n.promise;let r=new AbortController,a=(async()=>{let n=await this.deps.fetchPack(e,r.signal);if(this.disposed)return null;if(n===null)return this.states.set(e,{kind:`empty`}),null;t?.(n);let a=await this.deps.decodePack(n);return this.disposed?(a.close(),null):(this.states.set(e,{kind:`decoded`,window:a}),this.touch(e),a)})().catch(t=>{throw this.states.delete(e),t});return this.states.set(e,{kind:`loading`,promise:a,abort:r}),a}nearest(e,t,n){let r=null,a=1/0,o=t=>{let n=0,o=t.ts.length-1;for(;n<o;){let r=n+o>>1;t.ts[r]<e?n=r+1:o=r}for(let o of[n-1,n]){if(o<0||o>=t.ts.length)continue;let n=Math.abs(t.ts[o]-e);n<a&&(a=n,r=t.bitmaps[o]??null)}};o(t);let s=this.windowMs/10;for(let t of[n-this.windowMs,n+this.windowMs]){let r=t<n?e-n<s:n+this.windowMs-e<s,a=this.states.get(t);r&&a?.kind===`decoded`&&o(a.window)}return r}async scrubTo(e){if(this.dead||this.disposed)return!1;let t=++this.scrubSeq,n=Date.now(),r=this.windowKey(e),a=this.states.get(r)?.kind===`decoded`,o;try{o=await this.ensureWindow(r,n=>this.tryFastPaint(n,e,t))}catch(e){if(yJ(e)||xJ(e))throw this.dead=!0,e;return!1}if(t!==this.scrubSeq||o===null)return!1;this.touch(r);let s=this.nearest(e,o,r);return s?(this.deps.draw(s),this.deps.onTiming?.({epochMs:e,cached:a,totalMs:Date.now()-n}),this.tracker.add(e,Date.now()),this.prefetchWindows(this.tracker.projectedWindowKeys(e,this.prefetchHorizonMs,this.maxPrefetch)),!0):!1}tryFastPaint(e,t,n){let r=this.deps.decodeFirstFrame;r&&r(e,t).then(e=>{if(e){if(n!==this.scrubSeq||this.disposed||this.dead){e.bitmap.close();return}this.deps.draw(e.bitmap),e.bitmap.close()}}).catch(()=>{})}prefetchWindows(e){if(!(this.dead||this.disposed))for(let t of e){if(this.prefetches.size>=this.maxPrefetch)break;if(this.states.has(t)||this.prefetches.has(t))continue;let e=new AbortController;this.prefetches.set(t,e),this.ensureWindow(t).catch(()=>{}).finally(()=>{this.prefetches.get(t)===e&&this.prefetches.delete(t)})}}armPrefetch(e){let t=this.windowKey(e);this.prefetchWindows([t,t-this.windowMs,t+this.windowMs])}dispose(){this.disposed=!0,this.scrubSeq++;for(let e of this.states.values())e.kind===`decoded`&&e.window.close(),e.kind===`loading`&&e.abort.abort();this.states.clear(),this.lru.length=0;for(let e of this.prefetches.values())e.abort();this.prefetches.clear(),this.tracker.reset()}};function CJ(e){if(e.byteLength<4)throw Error(`scrub pack: truncated (no length prefix)`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0);if(t<=0||4+t>e.byteLength)throw Error(`scrub pack: bogus header length ${t}`);let n=new TextDecoder().decode(e.subarray(4,4+t)),r=JSON.parse(n);if(r.v!==1)throw Error(`scrub pack: unsupported version ${String(r.v)}`);if(!Array.isArray(r.frames))throw Error(`scrub pack: malformed header (frames)`);return{header:r,payloadOffset:4+t}}function wJ(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function TJ(e){return{codec:e.codec,description:wJ(e.description),optimizeForLatency:!0}}function EJ(e,t){let n=-1,r=1/0;for(let a=0;a<e.length;a++){let o=Math.abs(e[a].ts-t);o<r&&(r=o,n=a)}return n}async function DJ(e){let t=new Uint8Array(e),{header:n,payloadOffset:r}=CJ(t),a=TJ(n);if(!(await VideoDecoder.isConfigSupported(a)).supported)throw new cJ(n.codec);let o=[],s=[],c=new Promise((e,c)=>{let l=new VideoDecoder({output:e=>{let t=e.timestamp/1e3;s.push(createImageBitmap(e).then(e=>{o.push({ts:t,bitmap:e})}).finally(()=>{e.close()}))},error:e=>c(e)});l.configure(a);for(let e of n.frames)l.decode(new EncodedVideoChunk({type:`key`,timestamp:e.ts*1e3,data:t.subarray(r+e.offset,r+e.offset+e.size)}));l.flush().then(()=>{l.close(),e()}).catch(c)});try{await c,await Promise.all(s)}catch(e){await Promise.allSettled(s);for(let e of o)e.bitmap.close();throw e}o.sort((e,t)=>e.ts-t.ts);let l=o.map(e=>e.ts),u=o.map(e=>e.bitmap);return{ts:l,bitmaps:u,close(){for(let e of u)e.close()}}}async function OJ(e,t){let n=new Uint8Array(e),{header:r,payloadOffset:a}=CJ(n),o=r.frames[t];if(!o)return null;let s=TJ(r);if(!(await VideoDecoder.isConfigSupported(s)).supported)throw new cJ(r.codec);try{return await new Promise((e,t)=>{let r=null,c=new VideoDecoder({output:e=>{let t=e.timestamp/1e3;r=createImageBitmap(e).then(e=>({ts:t,bitmap:e})).finally(()=>e.close())},error:e=>t(e)});c.configure(s),c.decode(new EncodedVideoChunk({type:`key`,timestamp:o.ts*1e3,data:n.subarray(a+o.offset,a+o.offset+o.size)})),c.flush().then(async()=>{c.close(),e(r?await r:null)}).catch(t)})}catch(e){if(e instanceof cJ)throw e;return null}}async function kJ(e,t){let{header:n}=CJ(new Uint8Array(e)),r=EJ(n.frames,t);return r<0?null:OJ(e,r)}var AJ=class{deps;engine=null;dead=!1;constructor(e){this.deps=e}isDead(){return this.dead}async scrubTo(e){if(this.dead)return`fallthrough`;this.engine||=this.buildEngine();try{return await this.engine.scrubTo(e)?(this.deps.onDrawn(),`drawn`):`fallthrough`}catch(e){return this.dead=!0,this.deps.onDead?.(e),`fallthrough`}}armPrefetch(e){this.dead||(this.engine||=this.buildEngine(),this.engine.armPrefetch(e))}dispose(){this.engine?.dispose(),this.engine=null}buildEngine(){let e=this.deps.fetchImpl??fetch,t=this.deps.decodeWindow??DJ;return new SJ({fetchPack:async(t,n)=>{let r=await e(`/addon/recorder/scrub/${this.deps.deviceId}/${t/1e3}`,{signal:n,credentials:`include`,headers:this.deps.requestHeaders});if(r.status===204)return null;if(r.status===404||r.status===400)throw new bJ(`scrub pack endpoint absent/drift: ${r.status}`);if(!r.ok)throw Error(`scrub pack fetch failed: ${r.status}`);return r.arrayBuffer()},decodePack:async e=>{try{return await t(e)}catch(e){throw e instanceof Error&&e.message.startsWith(`scrub pack:`)?new bJ(e.message):e}},decodeFirstFrame:this.deps.decodeFirstFrame??kJ,draw:e=>{this.deps.draw(e),this.deps.onDrawn()},onTiming:this.deps.onTiming})}};function jJ(){let e=!1;return{fire(){return e?!1:(e=!0,!0)},reset(){e=!1}}}async function MJ(e){if(!e.hasVideoDecoder)return{capability:`unavailable`,reason:`no VideoDecoder`};let t=!1;try{t=await e.isVideoSupported(e.videoConfig)}catch{t=!1}return t?e.hasAudioDecoder?{capability:`webcodecs-av`,reason:`ok`}:{capability:`webcodecs-video-only`,reason:`no AudioDecoder`}:{capability:`unavailable`,reason:`video config unsupported: ${e.videoConfig.codec}`}}function NJ(e){return!Number.isFinite(e)||e<=0?0:Math.min(4,Math.max(.25,e))}function PJ(e,t,n,r){return e<t&&n<r}var FJ=1500,IJ=8,LJ=1e3,RJ=2,zJ=50,BJ=30;function VJ(e){typeof e==`object`&&e&&`unref`in e&&e.unref()}var HJ=class{deps;gen=0;disposed=!1;dead=!1;requestedRate=0;requestedProfile;activeProfile;current=null;lastDrawn=null;cancelRaf=null;positionTimer=null;submittedUpToUs=0;activeLoadAc=null;targetAheadMs;maxQueue;constructor(e){this.deps=e,this.requestedProfile=e.profile,this.activeProfile=e.profile,this.targetAheadMs=e.targetAheadMs??FJ,this.maxQueue=e.maxQueue??IJ,this.scheduleDraw()}mode(){return this.requestedRate===1&&this.deps.audio?`audio`:`video`}supersede(){return this.activeLoadAc?.abort(),this.activeLoadAc=null,++this.gen}abortDead(e,t){this.dead||this.disposed||(this.dead=!0,this.supersede(),this.deps.clock.pause(),this.deps.audio?.stop(),this.cancelRaf?.(),this.cancelRaf=null,this.stopPositionReports(),this.deps.onState(`error`),this.deps.onDead(t??this.deps.clock.playheadMs(),e))}async seek(e){let t=this.supersede();this.deps.onState(`loading`),this.deps.video.reset(),this.deps.ring.clear(),this.deps.audio?.stop(),this.lastDrawn=null;try{await this.deps.ensureIndex(e)}catch(n){t===this.gen&&this.abortDead(n,e);return}if(this.disposed||t!==this.gen)return;let n=this.deps.locate(e),r=e;if(n.kind===`gap`){if(n.nearestEdgeMs===null){this.deps.clock.seekTo(e),this.deps.onState(`ended`),this.stopPositionReports();return}if(r=n.nearestEdgeMs,n=this.deps.locate(r),n.kind!==`segment`){this.deps.onState(`gap`);return}}let a=n.seg,o=new AbortController;this.activeLoadAc=o;let s;try{s=await this.deps.loadSegment(a.startMs,o.signal)}catch(n){t===this.gen&&this.abortDead(n,e);return}if(this.disposed||t!==this.gen)return;this.current={startMs:a.startMs,durMs:a.durMs,demux:s},this.deps.video.configure(s.video.config);let c=r*1e3,l=0;for(let e of s.video.chunks)if(this.deps.video.submit(e),l=e.timestamp,e.timestamp>=c)break;if(this.submittedUpToUs=l,await this.deps.video.flush(),this.disposed||t!==this.gen)return;this.deps.clock.seekTo(r);let u=this.deps.ring.frameFor(r);if(u&&(this.deps.draw(u),this.lastDrawn=u),this.deps.onPosition(r),this.requestedRate===0){this.deps.onState(`paused`),this.stopPositionReports();return}this.startPlaying(r,s)}startPlaying(e,t){this.deps.audio?.stop();let n=this.deps.audio,r=t.audio,a=this.gen;this.deps.onState(`playing`),this.startPositionReports(),this.mode()===`audio`&&n&&r?(n.configure(r.config),n.resumeContext().then(()=>{this.disposed||a!==this.gen||(n.enqueue(r.chunks,e),this.deps.clock.play(1,`audio`,e,()=>n.audioNowSec()),this.decodeAheadLoop(a))})):(this.deps.clock.play(this.requestedRate,`video`),this.decodeAheadLoop(a))}async decodeAheadLoop(e){for(;!this.disposed&&e===this.gen&&!this.deps.clock.paused;){let t=this.deps.clock.playheadMs(),n=this.deps.ring.bufferedAheadMs(t);if(PJ(this.deps.video.queueSize,this.maxQueue,n,this.targetAheadMs)){let t;try{t=await this.nextChunk(e)}catch(t){if(this.disposed||e!==this.gen)return;this.abortDead(t);return}if(this.disposed||e!==this.gen)return;t?this.deps.video.submit(t):await this.sleep(zJ)}else await this.sleep(BJ)}}async nextChunk(e){let t=this.current;if(!t)return null;for(let e of t.demux.video.chunks)if(e.timestamp>this.submittedUpToUs)return this.submittedUpToUs=e.timestamp,e;let n=this.deps.locate(t.startMs+t.durMs),r;if(n.kind===`segment`)r=n.seg.startMs;else if(n.nearestEdgeMs!==null)r=n.nearestEdgeMs;else return null;let a=this.deps.locate(r);if(a.kind!==`segment`)return null;let o=new AbortController;this.activeLoadAc=o;let s=await this.deps.loadSegment(a.seg.startMs,o.signal);if(this.disposed||e!==this.gen)return null;this.current={startMs:a.seg.startMs,durMs:a.seg.durMs,demux:s},this.deps.video.configure(s.video.config);let c=s.video.chunks[0];return c?(this.submittedUpToUs=c.timestamp,c):null}tick(){if(this.disposed||this.dead)return;let e=this.deps.clock.playheadMs();if(this.current&&!this.deps.clock.paused&&e>=this.current.startMs+this.current.durMs){let t=this.deps.locate(e);if(t.kind===`gap`){if(t.nearestEdgeMs===null){this.deps.clock.pause(),this.deps.onState(`ended`),this.stopPositionReports();return}this.deps.onState(`gap`),this.deps.clock.seekTo(t.nearestEdgeMs),this.seek(t.nearestEdgeMs);return}}let t=this.deps.ring.frameFor(e);t&&t!==this.lastDrawn&&(this.deps.draw(t),this.lastDrawn=t),this.deps.ring.evictBehind(e)}scheduleDraw(){let e=()=>{this.tick(),!this.disposed&&!this.dead&&(this.cancelRaf=this.deps.raf(e))};this.cancelRaf=this.deps.raf(e)}setRate(e){let t=NJ(e);if(t===this.requestedRate)return;this.requestedRate=t;let n=t>RJ?`low`:this.requestedProfile;if(n!==this.activeProfile){this.setProfile(n,!0).catch(e=>{this.disposed||this.abortDead(e)});return}if(this.supersede(),t===0){this.deps.clock.pause(),this.deps.audio?.stop(),this.deps.onState(`paused`),this.stopPositionReports();return}let r=this.deps.clock.playheadMs();if(!this.current){this.seek(r);return}this.startPlaying(r,this.current.demux)}getActiveProfile(){return this.activeProfile}async setProfile(e,t=!1){t||(this.requestedProfile=e),this.activeProfile=e;let n=this.deps.clock.playheadMs();await this.deps.ensureIndex(n),!this.disposed&&await this.seek(n)}stepFrame(e){if(this.disposed||this.requestedRate!==0)return;let t=this.current;if(!t)return;let n=this.deps.clock.playheadMs();if(e===1){let e=t.demux.video.chunks.find(e=>e.timestamp/1e3>n+1);if(e){this.paintExact(e.timestamp/1e3);return}let r=this.deps.locate(t.startMs+t.durMs);r.kind===`segment`?this.seek(r.seg.startMs):r.nearestEdgeMs!==null&&this.seek(r.nearestEdgeMs);return}let r=[...t.demux.video.chunks].reverse().find(e=>e.timestamp/1e3<n-1);if(r){this.paintExact(r.timestamp/1e3);return}let a=this.deps.locate(t.startMs-1);a.kind===`gap`&&a.prevEndMs!==null?this.seek(a.prevEndMs-1):a.kind===`segment`&&this.seek(a.seg.startMs+a.seg.durMs-1)}async paintExact(e){let t=this.supersede(),n=this.current;if(!n)return;this.deps.video.reset(),this.deps.ring.clear(),this.lastDrawn=null,this.deps.video.configure(n.demux.video.config);let r=e*1e3,a=0;for(let e of n.demux.video.chunks)if(this.deps.video.submit(e),a=e.timestamp,e.timestamp>=r)break;if(this.submittedUpToUs=a,await this.deps.video.flush(),this.disposed||t!==this.gen)return;this.deps.clock.seekTo(e);let o=this.deps.ring.frameFor(e);o&&(this.deps.draw(o),this.lastDrawn=o),this.deps.onPosition(e),this.deps.onState(`paused`)}pauseForScrub(){this.supersede(),this.deps.clock.pause(),this.deps.audio?.stop(),this.stopPositionReports()}async resumeFromScrub(e){await this.seek(e)}startPositionReports(){if(this.positionTimer)return;let e=setInterval(()=>{!this.disposed&&!this.deps.clock.paused&&this.deps.onPosition(this.deps.clock.playheadMs())},LJ);VJ(e),this.positionTimer=e}stopPositionReports(){this.positionTimer&&=(clearInterval(this.positionTimer),null)}sleep(e){return new Promise(t=>{VJ(setTimeout(t,e))})}dispose(){this.disposed=!0,this.supersede(),this.cancelRaf?.(),this.cancelRaf=null,this.stopPositionReports(),this.lastDrawn=null,this.deps.ring.clear(),this.deps.video.close(),this.deps.audio?.close()}};function UJ(e){try{return new URL(e).toString()}catch{let t=typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost`;return new URL(e,t).toString()}}function WJ(e){let t=(e.split(`/`).pop()??``).match(/^(\d+)-(\d+)(?:-\d+)?\.m4s$/);return t?{startMs:Number(t[1]),durMs:Number(t[2])}:null}function GJ(e,t,n){let r=e.split(`
|
|
114
|
+
`,s+=l.payl.text}return s};var p=function(){};p.prototype.parseSample=function(e){var t={},r;t.resources=[];var a=new n(e.data.buffer);if(!e.subsamples||e.subsamples.length===0)t.documentString=a.readString(e.data.length);else if(t.documentString=a.readString(e.subsamples[0].size),e.subsamples.length>1)for(r=1;r<e.subsamples.length;r++)t.resources[r]=a.readUint8Array(e.subsamples[r].size);return typeof DOMParser<`u`&&(t.document=new DOMParser().parseFromString(t.documentString,`application/xml`)),t};var m=function(){};m.prototype.parseSample=function(e){return new n(e.data.buffer).readString(e.data.length)},m.prototype.parseConfig=function(e){var t,r=new n(e.buffer);return r.readUint32(),t=r.readCString(),t},e!==void 0&&(e.VTTin4Parser=f,e.XMLSubtitlein4Parser=p,e.Textin4Parser=m);var h=function(e){this.stream=e||new o,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};h.prototype.setSegmentOptions=function(e,t,n){var r=this.getTrackById(e);if(r){var a={};this.fragmentedTracks.push(a),a.id=e,a.user=t,a.trak=r,r.nextSample=0,a.segmentStream=null,a.nb_samples=1e3,a.rapAlignement=!0,n&&(n.nbSamples&&(a.nb_samples=n.nbSamples),n.rapAlignement&&(a.rapAlignement=n.rapAlignement))}},h.prototype.unsetSegmentOptions=function(e){for(var t=-1,n=0;n<this.fragmentedTracks.length;n++)this.fragmentedTracks[n].id==e&&(t=n);t>-1&&this.fragmentedTracks.splice(t,1)},h.prototype.setExtractionOptions=function(e,t,n){var r=this.getTrackById(e);if(r){var a={};this.extractedTracks.push(a),a.id=e,a.user=t,a.trak=r,r.nextSample=0,a.nb_samples=1e3,a.samples=[],n&&n.nbSamples&&(a.nb_samples=n.nbSamples)}},h.prototype.unsetExtractionOptions=function(e){for(var t=-1,n=0;n<this.extractedTracks.length;n++)this.extractedTracks[n].id==e&&(t=n);t>-1&&this.extractedTracks.splice(t,1)},h.prototype.parse=function(){var e,n,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),e=c.parseOneBox(this.stream,r),e.code===c.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else{var a;switch(n=e.box,a=n.type===`uuid`?n.uuid:n.type,this.boxes.push(n),a){case`mdat`:this.mdats.push(n);break;case`moof`:this.moofs.push(n);break;case`moov`:this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[a]!==void 0&&t.warn(`ISOFile`,`Duplicate Box of type: `+a+`, overriding previous occurrence`),this[a]=n;break}this.updateUsedBytes&&this.updateUsedBytes(n,e)}},h.prototype.checkBuffer=function(e){if(e==null)throw`Buffer must be defined and non empty`;if(e.fileStart===void 0)throw`Buffer must have a fileStart property`;return e.byteLength===0?(t.warn(`ISOFile`,`Ignoring empty buffer (fileStart: `+e.fileStart+`)`),this.stream.logBufferLevel(),!1):(t.info(`ISOFile`,`Processing buffer (fileStart: `+e.fileStart+`)`),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(t.warn(`ISOFile`,`Not ready to start parsing`),!1))},h.prototype.appendBuffer=function(e,n){var r;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||=(this.buildSampleLists(),!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(n),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):r=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(t.info(`ISOFile`,`Done processing buffer (fileStart: `+e.fileStart+`) - next buffer to fetch should have a fileStart position of `+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),t.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize())),r},h.prototype.getInfo=function(){var e,t,n={},r,a,o,s,c=new Date(`1904-01-01T00:00:00Z`).getTime();if(this.moov)for(n.hasMoov=!0,n.duration=this.moov.mvhd.duration,n.timescale=this.moov.mvhd.timescale,n.isFragmented=this.moov.mvex!=null,n.isFragmented&&this.moov.mvex.mehd&&(n.fragment_duration=this.moov.mvex.mehd.fragment_duration),n.isProgressive=this.isProgressive,n.hasIOD=this.moov.iods!=null,n.brands=[],n.brands.push(this.ftyp.major_brand),n.brands=n.brands.concat(this.ftyp.compatible_brands),n.created=new Date(c+this.moov.mvhd.creation_time*1e3),n.modified=new Date(c+this.moov.mvhd.modification_time*1e3),n.tracks=[],n.audioTracks=[],n.videoTracks=[],n.subtitleTracks=[],n.metadataTracks=[],n.hintTracks=[],n.otherTracks=[],e=0;e<this.moov.traks.length;e++){if(r=this.moov.traks[e],s=r.mdia.minf.stbl.stsd.entries[0],a={},n.tracks.push(a),a.id=r.tkhd.track_id,a.name=r.mdia.hdlr.name,a.references=[],r.tref)for(t=0;t<r.tref.boxes.length;t++)o={},a.references.push(o),o.type=r.tref.boxes[t].type,o.track_ids=r.tref.boxes[t].track_ids;r.edts&&(a.edits=r.edts.elst.entries),a.created=new Date(c+r.tkhd.creation_time*1e3),a.modified=new Date(c+r.tkhd.modification_time*1e3),a.movie_duration=r.tkhd.duration,a.movie_timescale=n.timescale,a.layer=r.tkhd.layer,a.alternate_group=r.tkhd.alternate_group,a.volume=r.tkhd.volume,a.matrix=r.tkhd.matrix,a.track_width=r.tkhd.width/65536,a.track_height=r.tkhd.height/65536,a.timescale=r.mdia.mdhd.timescale,a.cts_shift=r.mdia.minf.stbl.cslg,a.duration=r.mdia.mdhd.duration,a.samples_duration=r.samples_duration,a.codec=s.getCodec(),a.kind=r.udta&&r.udta.kinds.length?r.udta.kinds[0]:{schemeURI:``,value:``},a.language=r.mdia.elng?r.mdia.elng.extended_language:r.mdia.mdhd.languageString,a.nb_samples=r.samples.length,a.size=r.samples_size,a.bitrate=a.size*8*a.timescale/a.samples_duration,s.isAudio()?(a.type=`audio`,n.audioTracks.push(a),a.audio={},a.audio.sample_rate=s.getSampleRate(),a.audio.channel_count=s.getChannelCount(),a.audio.sample_size=s.getSampleSize()):s.isVideo()?(a.type=`video`,n.videoTracks.push(a),a.video={},a.video.width=s.getWidth(),a.video.height=s.getHeight()):s.isSubtitle()?(a.type=`subtitles`,n.subtitleTracks.push(a)):s.isHint()?(a.type=`metadata`,n.hintTracks.push(a)):s.isMetadata()?(a.type=`metadata`,n.metadataTracks.push(a)):(a.type=`metadata`,n.otherTracks.push(a))}else n.hasMoov=!1;if(n.mime=``,n.hasMoov&&n.tracks){for(n.videoTracks&&n.videoTracks.length>0?n.mime+=`video/mp4; codecs="`:n.audioTracks&&n.audioTracks.length>0?n.mime+=`audio/mp4; codecs="`:n.mime+=`application/mp4; codecs="`,e=0;e<n.tracks.length;e++)e!==0&&(n.mime+=`,`),n.mime+=n.tracks[e].codec;n.mime+=`"; profiles="`,n.mime+=this.ftyp.compatible_brands.join(),n.mime+=`"`}return n},h.prototype.setNextSeekPositionFromSample=function(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)},h.prototype.processSamples=function(e){var n,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(n=0;n<this.fragmentedTracks.length;n++){var a=this.fragmentedTracks[n];for(r=a.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){t.debug(`ISOFile`,`Creating media fragment on track #`+a.id+` for sample `+r.nextSample);var o=this.createFragment(a.id,r.nextSample,a.segmentStream);if(o)a.segmentStream=o,r.nextSample++;else break;if((r.nextSample%a.nb_samples===0||e||r.nextSample>=r.samples.length)&&(t.info(`ISOFile`,`Sending fragmented data on track #`+a.id+` for samples [`+Math.max(0,r.nextSample-a.nb_samples)+`,`+(r.nextSample-1)+`]`),t.info(`ISOFile`,`Sample data size in memory: `+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(a.id,a.user,a.segmentStream.buffer,r.nextSample,e||r.nextSample>=r.samples.length),a.segmentStream=null,a!==this.fragmentedTracks[n]))break}}if(this.onSamples!==null)for(n=0;n<this.extractedTracks.length;n++){var s=this.extractedTracks[n];for(r=s.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){t.debug(`ISOFile`,`Exporting on track #`+s.id+` sample #`+r.nextSample);var c=this.getSample(r,r.nextSample);if(c)r.nextSample++,s.samples.push(c);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%s.nb_samples===0||r.nextSample>=r.samples.length)&&(t.debug(`ISOFile`,`Sending samples on track #`+s.id+` for sample `+r.nextSample),this.onSamples&&this.onSamples(s.id,s.user,s.samples),s.samples=[],s!==this.extractedTracks[n]))break}}}},h.prototype.getBox=function(e){var t=this.getBoxes(e,!0);return t.length?t[0]:null},h.prototype.getBoxes=function(e,t){var n=[];return h._sweep.call(this,e,n,t),n},h._sweep=function(e,t,n){for(var r in this.type&&this.type==e&&t.push(this),this.boxes){if(t.length&&n)return;h._sweep.call(this.boxes[r],e,t,n)}},h.prototype.getTrackSamplesInfo=function(e){var t=this.getTrackById(e);if(t)return t.samples},h.prototype.getTrackSample=function(e,t){var n=this.getTrackById(e);return this.getSample(n,t)},h.prototype.releaseUsedSamples=function(e,n){var r=0,a=this.getTrackById(e);a.lastValidSample||=0;for(var o=a.lastValidSample;o<n;o++)r+=this.releaseSample(a,o);t.info(`ISOFile`,`Track #`+e+` released samples up to `+n+` (released size: `+r+`, remaining: `+this.samplesDataSize+`)`),a.lastValidSample=n},h.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},h.prototype.stop=function(){this.sampleProcessingStarted=!1},h.prototype.flush=function(){t.info(`ISOFile`,`Flushing remaining samples`),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},h.prototype.seekTrack=function(e,n,r){var a,o,s=1/0,c=0,l=0,u;if(r.samples.length===0)return t.info(`ISOFile`,`No sample in track, cannot seek! Using time `+t.getDurationString(0,1)+` and offset: 0`),{offset:0,time:0};for(a=0;a<r.samples.length;a++){if(o=r.samples[a],a===0)l=0,u=o.timescale;else if(o.cts>e*o.timescale){l=a-1;break}n&&o.is_sync&&(c=a)}for(n&&(l=c),e=r.samples[l].cts,r.nextSample=l;r.samples[l].alreadyRead===r.samples[l].size&&r.samples[l+1];)l++;return s=r.samples[l].offset+r.samples[l].alreadyRead,t.info(`ISOFile`,`Seeking to `+(n?`RAP`:``)+` sample #`+r.nextSample+` on track `+r.tkhd.track_id+`, time `+t.getDurationString(e,u)+` and offset: `+s),{offset:s,time:e/u}},h.prototype.getTrackDuration=function(e){var t;return e.samples?(t=e.samples[e.samples.length-1],(t.cts+t.duration)/t.timescale):1/0},h.prototype.seek=function(e,n){var r=this.moov,a,o,s,c={offset:1/0,time:1/0};if(this.moov){for(s=0;s<r.traks.length;s++)a=r.traks[s],!(e>this.getTrackDuration(a))&&(o=this.seekTrack(e,n,a),o.offset<c.offset&&(c.offset=o.offset),o.time<c.time&&(c.time=o.time));return t.info(`ISOFile`,`Seeking at time `+t.getDurationString(c.time,1)+` needs a buffer with a fileStart position of `+c.offset),c.offset===1/0?c={offset:this.nextParsePosition,time:0}:c.offset=this.stream.getEndFilePositionAfter(c.offset),t.info(`ISOFile`,`Adjusted seek position (after checking data already in buffer): `+c.offset),c}else throw`Cannot seek: moov not received!`},h.prototype.equal=function(e){for(var t=0;t<this.boxes.length&&t<e.boxes.length;){var n=this.boxes[t],r=e.boxes[t];if(!c.boxEqual(n,r))return!1;t++}return!0},e!==void 0&&(e.ISOFile=h),h.prototype.lastBoxStartPosition=0,h.prototype.parsingMdat=null,h.prototype.nextParsePosition=0,h.prototype.discardMdatData=!1,h.prototype.processIncompleteBox=function(e){var t,n,r;return e.type===`mdat`?(t=new c[e.type+`Box`](e.size),this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,r=this.stream.seek(t.start+t.size,!1,this.discardMdatData),r?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)):(e.type===`moov`&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),n=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,n?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},h.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},h.prototype.processIncompleteMdat=function(){var e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(t.debug(`ISOFile`,`Found 'mdat' end in buffered data`),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},h.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},h.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},h.prototype.updateUsedBytes=function(e,t){this.stream.addUsedBytes&&(e.type===`mdat`?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))},h.prototype.add=c.Box.prototype.add,h.prototype.addBox=c.Box.prototype.addBox,h.prototype.init=function(e){var t=e||{};this.add(`ftyp`).set(`major_brand`,t.brands&&t.brands[0]||`iso4`).set(`minor_version`,0).set(`compatible_brands`,t.brands||[`iso4`]);var n=this.add(`moov`);return n.add(`mvhd`).set(`timescale`,t.timescale||600).set(`rate`,t.rate||65536).set(`creation_time`,0).set(`modification_time`,0).set(`duration`,t.duration||0).set(`volume`,t.width?0:256).set(`matrix`,[65536,0,0,0,65536,0,0,0,1073741824]).set(`next_track_id`,1),n.add(`mvex`),this},h.prototype.addTrack=function(e){this.moov||this.init(e);var t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||`avc1`;var r=this.moov.add(`trak`);this.moov.mvhd.next_track_id=t.id+1,r.add(`tkhd`).set(`flags`,c.TKHD_FLAG_ENABLED|c.TKHD_FLAG_IN_MOVIE|c.TKHD_FLAG_IN_PREVIEW).set(`creation_time`,0).set(`modification_time`,0).set(`track_id`,t.id).set(`duration`,t.duration||0).set(`layer`,t.layer||0).set(`alternate_group`,0).set(`volume`,1).set(`matrix`,[65536,0,0,0,65536,0,0,0,1073741824]).set(`width`,t.width<<16).set(`height`,t.height<<16);var a=r.add(`mdia`);a.add(`mdhd`).set(`creation_time`,0).set(`modification_time`,0).set(`timescale`,t.timescale||1).set(`duration`,t.media_duration||0).set(`language`,t.language||`und`),a.add(`hdlr`).set(`handler`,t.hdlr||`vide`).set(`name`,t.name||`Track created with MP4Box.js`),a.add(`elng`).set(`extended_language`,t.language||`fr-FR`);var o=a.add(`minf`);if(c[t.type+`SampleEntry`]!==void 0){var s=new c[t.type+`SampleEntry`];s.data_reference_index=1;var l=``;for(var u in c.sampleEntryCodes)for(var d=c.sampleEntryCodes[u],f=0;f<d.length;f++)if(d.indexOf(t.type)>-1){l=u;break}switch(l){case`Visual`:if(o.add(`vmhd`).set(`graphicsmode`,0).set(`opcolor`,[0,0,0]),s.set(`width`,t.width).set(`height`,t.height).set(`horizresolution`,72<<16).set(`vertresolution`,72<<16).set(`frame_count`,1).set(`compressorname`,t.type+` Compressor`).set(`depth`,24),t.avcDecoderConfigRecord){var p=new c.avcCBox;p.parse(new n(t.avcDecoderConfigRecord)),s.addBox(p)}else if(t.hevcDecoderConfigRecord){var m=new c.hvcCBox;m.parse(new n(t.hevcDecoderConfigRecord)),s.addBox(m)}break;case`Audio`:o.add(`smhd`).set(`balance`,t.balance||0),s.set(`channel_count`,t.channel_count||2).set(`samplesize`,t.samplesize||16).set(`samplerate`,t.samplerate||65536);break;case`Hint`:o.add(`hmhd`);break;case`Subtitle`:switch(o.add(`sthd`),t.type){case`stpp`:s.set(`namespace`,t.namespace||`nonamespace`).set(`schema_location`,t.schema_location||``).set(`auxiliary_mime_types`,t.auxiliary_mime_types||``);break}break;case`Metadata`:o.add(`nmhd`);break;case`System`:o.add(`nmhd`);break;default:o.add(`nmhd`);break}t.description&&s.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(e){s.addBox(e)}),o.add(`dinf`).add(`dref`).addEntry(new c[`url Box`]().set(`flags`,1));var h=o.add(`stbl`);return h.add(`stsd`).addEntry(s),h.add(`stts`).set(`sample_counts`,[]).set(`sample_deltas`,[]),h.add(`stsc`).set(`first_chunk`,[]).set(`samples_per_chunk`,[]).set(`sample_description_index`,[]),h.add(`stco`).set(`chunk_offsets`,[]),h.add(`stsz`).set(`sample_sizes`,[]),this.moov.mvex.add(`trex`).set(`track_id`,t.id).set(`default_sample_description_index`,t.default_sample_description_index||1).set(`default_sample_duration`,t.default_sample_duration||0).set(`default_sample_size`,t.default_sample_size||0).set(`default_sample_flags`,t.default_sample_flags||0),this.buildTrakSampleLists(r),t.id}},c.Box.prototype.computeSize=function(e){var t=e||new r;t.endianness=r.BIG_ENDIAN,this.write(t)},h.prototype.addSample=function(e,t,n){var r=n||{},a={},o=this.getTrackById(e);if(o!==null){a.number=o.samples.length,a.track_id=o.tkhd.track_id,a.timescale=o.mdia.mdhd.timescale,a.description_index=r.sample_description_index?r.sample_description_index-1:0,a.description=o.mdia.minf.stbl.stsd.entries[a.description_index],a.data=t,a.size=t.byteLength,a.alreadyRead=a.size,a.duration=r.duration||1,a.cts=r.cts||0,a.dts=r.dts||0,a.is_sync=r.is_sync||!1,a.is_leading=r.is_leading||0,a.depends_on=r.depends_on||0,a.is_depended_on=r.is_depended_on||0,a.has_redundancy=r.has_redundancy||0,a.degradation_priority=r.degradation_priority||0,a.offset=0,a.subsamples=r.subsamples,o.samples.push(a),o.samples_size+=a.size,o.samples_duration+=a.duration,o.first_dts===void 0&&(o.first_dts=r.dts),this.processSamples();var s=this.createSingleSampleMoof(a);return this.addBox(s),s.computeSize(),s.trafs[0].truns[0].data_offset=s.size+8,this.add(`mdat`).data=new Uint8Array(t),a}},h.prototype.createSingleSampleMoof=function(e){var t=0;t=e.is_sync?1<<25:65536;var n=new c.moofBox;n.add(`mfhd`).set(`sequence_number`,this.nextMoofNumber),this.nextMoofNumber++;var r=n.add(`traf`),a=this.getTrackById(e.track_id);return r.add(`tfhd`).set(`track_id`,e.track_id).set(`flags`,c.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),r.add(`tfdt`).set(`baseMediaDecodeTime`,e.dts-(a.first_dts||0)),r.add(`trun`).set(`flags`,c.TRUN_FLAGS_DATA_OFFSET|c.TRUN_FLAGS_DURATION|c.TRUN_FLAGS_SIZE|c.TRUN_FLAGS_FLAGS|c.TRUN_FLAGS_CTS_OFFSET).set(`data_offset`,0).set(`first_sample_flags`,0).set(`sample_count`,1).set(`sample_duration`,[e.duration]).set(`sample_size`,[e.size]).set(`sample_flags`,[t]).set(`sample_composition_time_offset`,[e.cts-e.dts]),n},h.prototype.lastMoofIndex=0,h.prototype.samplesDataSize=0,h.prototype.resetTables=function(){var e,t,n,r,a,o,s,c;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,e=0;e<this.moov.traks.length;e++){t=this.moov.traks[e],t.tkhd.duration=0,t.mdia.mdhd.duration=0,n=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,n.chunk_offsets=[],r=t.mdia.minf.stbl.stsc,r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[],a=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,a.sample_sizes=[],o=t.mdia.minf.stbl.stts,o.sample_counts=[],o.sample_deltas=[],s=t.mdia.minf.stbl.ctts,s&&(s.sample_counts=[],s.sample_offsets=[]),c=t.mdia.minf.stbl.stss;var l=t.mdia.minf.stbl.boxes.indexOf(c);l!=-1&&(t.mdia.minf.stbl.boxes[l]=null)}},h.initSampleGroups=function(e,t,n,r,a){var o,s,c,l;function u(e,t,n){this.grouping_type=e,this.grouping_type_parameter=t,this.sbgp=n,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||=[],s=0;s<n.length;s++){for(l=n[s].grouping_type+`/`+n[s].grouping_type_parameter,c=new u(n[s].grouping_type,n[s].grouping_type_parameter,n[s]),t&&(t.sample_groups_info[l]=c),e.sample_groups_info[l]||(e.sample_groups_info[l]=c),o=0;o<r.length;o++)r[o].grouping_type===n[s].grouping_type&&(c.description=r[o],c.description.used=!0);if(a)for(o=0;o<a.length;o++)a[o].grouping_type===n[s].grouping_type&&(c.fragment_description=a[o],c.fragment_description.used=!0,c.is_fragment=!0)}if(!t)for(s=0;s<r.length;s++)!r[s].used&&r[s].version>=2&&(l=r[s].grouping_type+`/0`,c=new u(r[s].grouping_type,0),e.sample_groups_info[l]||(e.sample_groups_info[l]=c));else if(a)for(s=0;s<a.length;s++)!a[s].used&&a[s].version>=2&&(l=a[s].grouping_type+`/0`,c=new u(a[s].grouping_type,0),c.is_fragment=!0,t.sample_groups_info[l]||(t.sample_groups_info[l]=c))},h.setSampleGroupProperties=function(e,t,n,r){var a,o;for(a in t.sample_groups=[],r)if(t.sample_groups[a]={},t.sample_groups[a].grouping_type=r[a].grouping_type,t.sample_groups[a].grouping_type_parameter=r[a].grouping_type_parameter,n>=r[a].last_sample_in_run&&(r[a].last_sample_in_run<0&&(r[a].last_sample_in_run=0),r[a].entry_index++,r[a].entry_index<=r[a].sbgp.entries.length-1&&(r[a].last_sample_in_run+=r[a].sbgp.entries[r[a].entry_index].sample_count)),r[a].entry_index<=r[a].sbgp.entries.length-1?t.sample_groups[a].group_description_index=r[a].sbgp.entries[r[a].entry_index].group_description_index:t.sample_groups[a].group_description_index=-1,t.sample_groups[a].group_description_index!==0){var s=r[a].fragment_description?r[a].fragment_description:r[a].description;t.sample_groups[a].group_description_index>0?(o=t.sample_groups[a].group_description_index>65535?(t.sample_groups[a].group_description_index>>16)-1:t.sample_groups[a].group_description_index-1,s&&o>=0&&(t.sample_groups[a].description=s.entries[o])):s&&s.version>=2&&s.default_group_description_index>0&&(t.sample_groups[a].description=s.entries[s.default_group_description_index-1])}},h.process_sdtp=function(e,t,n){t&&(e?(t.is_leading=e.is_leading[n],t.depends_on=e.sample_depends_on[n],t.is_depended_on=e.sample_is_depended_on[n],t.has_redundancy=e.sample_has_redundancy[n]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))},h.prototype.buildSampleLists=function(){var e,t;for(e=0;e<this.moov.traks.length;e++)t=this.moov.traks[e],this.buildTrakSampleLists(t)},h.prototype.buildTrakSampleLists=function(e){var t,n,r,a,o,s,c,l,u,d,f,p,m,g,_,v,y,b,x,S,C,w,T,E;if(e.samples=[],e.samples_duration=0,e.samples_size=0,n=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,r=e.mdia.minf.stbl.stsc,a=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,o=e.mdia.minf.stbl.stts,s=e.mdia.minf.stbl.ctts,c=e.mdia.minf.stbl.stss,l=e.mdia.minf.stbl.stsd,u=e.mdia.minf.stbl.subs,p=e.mdia.minf.stbl.stdp,d=e.mdia.minf.stbl.sbgps,f=e.mdia.minf.stbl.sgpds,b=-1,x=-1,S=-1,C=-1,w=0,T=0,E=0,h.initSampleGroups(e,null,d,f),a!==void 0){for(t=0;t<a.sample_sizes.length;t++){var D={};D.number=t,D.track_id=e.tkhd.track_id,D.timescale=e.mdia.mdhd.timescale,D.alreadyRead=0,e.samples[t]=D,D.size=a.sample_sizes[t],e.samples_size+=D.size,t===0?(g=1,m=0,D.chunk_index=g,D.chunk_run_index=m,y=r.samples_per_chunk[m],v=0,_=m+1<r.first_chunk.length?r.first_chunk[m+1]-1:1/0):t<y?(D.chunk_index=g,D.chunk_run_index=m):(g++,D.chunk_index=g,v=0,g<=_||(m++,_=m+1<r.first_chunk.length?r.first_chunk[m+1]-1:1/0),D.chunk_run_index=m,y+=r.samples_per_chunk[m]),D.description_index=r.sample_description_index[D.chunk_run_index]-1,D.description=l.entries[D.description_index],D.offset=n.chunk_offsets[D.chunk_index-1]+v,v+=D.size,t>b&&(x++,b<0&&(b=0),b+=o.sample_counts[x]),t>0?(e.samples[t-1].duration=o.sample_deltas[x],e.samples_duration+=e.samples[t-1].duration,D.dts=e.samples[t-1].dts+e.samples[t-1].duration):D.dts=0,s?(t>=S&&(C++,S<0&&(S=0),S+=s.sample_counts[C]),D.cts=e.samples[t].dts+s.sample_offsets[C]):D.cts=D.dts,c?(t==c.sample_numbers[w]-1?(D.is_sync=!0,w++):(D.is_sync=!1,D.degradation_priority=0),u&&u.entries[T].sample_delta+E==t+1&&(D.subsamples=u.entries[T].subsamples,E+=u.entries[T].sample_delta,T++)):D.is_sync=!0,h.process_sdtp(e.mdia.minf.stbl.sdtp,D,D.number),p?D.degradation_priority=p.priority[t]:D.degradation_priority=0,u&&u.entries[T].sample_delta+E==t&&(D.subsamples=u.entries[T].subsamples,E+=u.entries[T].sample_delta),(d.length>0||f.length>0)&&h.setSampleGroupProperties(e,D,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}},h.prototype.updateSampleLists=function(){var e,t,n,r,a,o,s,l,u,d,f,p,m,g,_;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(u=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,u.type==`moof`)for(d=u,e=0;e<d.trafs.length;e++){for(f=d.trafs[e],p=this.getTrackById(f.tfhd.track_id),m=this.getTrexById(f.tfhd.track_id),r=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_DESC?f.tfhd.default_sample_description_index:m?m.default_sample_description_index:1,a=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_DUR?f.tfhd.default_sample_duration:m?m.default_sample_duration:0,o=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_SIZE?f.tfhd.default_sample_size:m?m.default_sample_size:0,s=f.tfhd.flags&c.TFHD_FLAG_SAMPLE_FLAGS?f.tfhd.default_sample_flags:m?m.default_sample_flags:0,f.sample_number=0,f.sbgps.length>0&&h.initSampleGroups(p,f,f.sbgps,p.mdia.minf.stbl.sgpds,f.sgpds),t=0;t<f.truns.length;t++){var v=f.truns[t];for(n=0;n<v.sample_count;n++){g={},g.moof_number=this.lastMoofIndex,g.number_in_traf=f.sample_number,f.sample_number++,g.number=p.samples.length,f.first_sample_index=p.samples.length,p.samples.push(g),g.track_id=p.tkhd.track_id,g.timescale=p.mdia.mdhd.timescale,g.description_index=r-1,g.description=p.mdia.minf.stbl.stsd.entries[g.description_index],g.size=o,v.flags&c.TRUN_FLAGS_SIZE&&(g.size=v.sample_size[n]),p.samples_size+=g.size,g.duration=a,v.flags&c.TRUN_FLAGS_DURATION&&(g.duration=v.sample_duration[n]),p.samples_duration+=g.duration,p.first_traf_merged||n>0?g.dts=p.samples[p.samples.length-2].dts+p.samples[p.samples.length-2].duration:(f.tfdt?g.dts=f.tfdt.baseMediaDecodeTime:g.dts=0,p.first_traf_merged=!0),g.cts=g.dts,v.flags&c.TRUN_FLAGS_CTS_OFFSET&&(g.cts=g.dts+v.sample_composition_time_offset[n]),_=s,v.flags&c.TRUN_FLAGS_FLAGS?_=v.sample_flags[n]:n===0&&v.flags&c.TRUN_FLAGS_FIRST_FLAG&&(_=v.first_sample_flags),g.is_sync=!(_>>16&1),g.is_leading=_>>26&3,g.depends_on=_>>24&3,g.is_depended_on=_>>22&3,g.has_redundancy=_>>20&3,g.degradation_priority=_&65535;var y=!!(f.tfhd.flags&c.TFHD_FLAG_BASE_DATA_OFFSET),b=!!(f.tfhd.flags&c.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),x=!!(v.flags&c.TRUN_FLAGS_DATA_OFFSET),S=0;S=y?f.tfhd.base_data_offset:b||t===0?d.start:l,t===0&&n===0?x?g.offset=S+v.data_offset:g.offset=S:g.offset=l,l=g.offset+g.size,(f.sbgps.length>0||f.sgpds.length>0||p.mdia.minf.stbl.sbgps.length>0||p.mdia.minf.stbl.sgpds.length>0)&&h.setSampleGroupProperties(p,g,g.number_in_traf,f.sample_groups_info)}}if(f.subs){p.has_fragment_subsamples=!0;var C=f.first_sample_index;for(t=0;t<f.subs.entries.length;t++)C+=f.subs.entries[t].sample_delta,g=p.samples[C-1],g.subsamples=f.subs.entries[t].subsamples}}}},h.prototype.getSample=function(e,n){var a,o=e.samples[n];if(!this.moov)return null;if(!o.data)o.data=new Uint8Array(o.size),o.alreadyRead=0,this.samplesDataSize+=o.size,t.debug(`ISOFile`,`Allocating sample #`+n+` on track #`+e.tkhd.track_id+` of size `+o.size+` (total: `+this.samplesDataSize+`)`);else if(o.alreadyRead==o.size)return o;for(;;){var s=this.stream.findPosition(!0,o.offset+o.alreadyRead,!1);if(s>-1){a=this.stream.buffers[s];var c=a.byteLength-(o.offset+o.alreadyRead-a.fileStart);if(o.size-o.alreadyRead<=c)return t.debug(`ISOFile`,`Getting sample #`+n+` data (alreadyRead: `+o.alreadyRead+` offset: `+(o.offset+o.alreadyRead-a.fileStart)+` read size: `+(o.size-o.alreadyRead)+` full size: `+o.size+`)`),r.memcpy(o.data.buffer,o.alreadyRead,a,o.offset+o.alreadyRead-a.fileStart,o.size-o.alreadyRead),a.usedBytes+=o.size-o.alreadyRead,this.stream.logBufferLevel(),o.alreadyRead=o.size,o;if(c===0)return null;t.debug(`ISOFile`,`Getting sample #`+n+` partial data (alreadyRead: `+o.alreadyRead+` offset: `+(o.offset+o.alreadyRead-a.fileStart)+` read size: `+c+` full size: `+o.size+`)`),r.memcpy(o.data.buffer,o.alreadyRead,a,o.offset+o.alreadyRead-a.fileStart,c),o.alreadyRead+=c,a.usedBytes+=c,this.stream.logBufferLevel()}else return null}},h.prototype.releaseSample=function(e,t){var n=e.samples[t];return n.data?(this.samplesDataSize-=n.size,n.data=null,n.alreadyRead=0,n.size):0},h.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},h.prototype.getCodecs=function(){var e,t=``;for(e=0;e<this.moov.traks.length;e++){var n=this.moov.traks[e];e>0&&(t+=`,`),t+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return t},h.prototype.getTrexById=function(e){var t;if(!this.moov||!this.moov.mvex)return null;for(t=0;t<this.moov.mvex.trexs.length;t++){var n=this.moov.mvex.trexs[t];if(n.track_id==e)return n}return null},h.prototype.getTrackById=function(e){if(this.moov===void 0)return null;for(var t=0;t<this.moov.traks.length;t++){var n=this.moov.traks[t];if(n.tkhd.track_id==e)return n}return null},h.prototype.itemsDataSize=0,h.prototype.flattenItemInfo=function(){var e=this.items,n=this.entity_groups,r,a,o,s=this.meta;if(s!=null&&s.hdlr!==void 0&&s.iinf!==void 0){for(r=0;r<s.iinf.item_infos.length;r++)o={},o.id=s.iinf.item_infos[r].item_ID,e[o.id]=o,o.ref_to=[],o.name=s.iinf.item_infos[r].item_name,s.iinf.item_infos[r].protection_index>0&&(o.protection=s.ipro.protections[s.iinf.item_infos[r].protection_index-1]),s.iinf.item_infos[r].item_type?o.type=s.iinf.item_infos[r].item_type:o.type=`mime`,o.content_type=s.iinf.item_infos[r].content_type,o.content_encoding=s.iinf.item_infos[r].content_encoding,o.item_uri_type=s.iinf.item_infos[r].item_uri_type;if(s.grpl)for(r=0;r<s.grpl.boxes.length;r++)entity_group={},entity_group.id=s.grpl.boxes[r].group_id,entity_group.entity_ids=s.grpl.boxes[r].entity_ids,entity_group.type=s.grpl.boxes[r].type,n[entity_group.id]=entity_group;if(s.iloc)for(r=0;r<s.iloc.items.length;r++){var c=s.iloc.items[r];switch(o=e[c.item_ID],c.data_reference_index!==0&&(t.warn(`Item storage with reference to other files: not supported`),o.source=s.dinf.boxes[c.data_reference_index-1]),c.construction_method){case 0:break;case 1:break;case 2:t.warn(`Item storage with construction_method : not supported`);break}for(o.extents=[],o.size=0,a=0;a<c.extents.length;a++)o.extents[a]={},o.extents[a].offset=c.extents[a].extent_offset+c.base_offset,c.construction_method==1&&(o.extents[a].offset+=s.idat.start+s.idat.hdr_size),o.extents[a].length=c.extents[a].extent_length,o.extents[a].alreadyRead=0,o.size+=o.extents[a].length}if(s.pitm&&(e[s.pitm.item_id].primary=!0),s.iref)for(r=0;r<s.iref.references.length;r++){var l=s.iref.references[r];for(a=0;a<l.references.length;a++)e[l.from_item_ID].ref_to.push({type:l.type,id:l.references[a]})}if(s.iprp)for(var u=0;u<s.iprp.ipmas.length;u++){var d=s.iprp.ipmas[u];for(r=0;r<d.associations.length;r++){var f=d.associations[r];if(o=e[f.id],o||=n[f.id],o)for(o.properties===void 0&&(o.properties={},o.properties.boxes=[]),a=0;a<f.props.length;a++){var p=f.props[a];if(p.property_index>0&&p.property_index-1<s.iprp.ipco.boxes.length){var m=s.iprp.ipco.boxes[p.property_index-1];o.properties[m.type]=m,o.properties.boxes.push(m)}}}}}},h.prototype.getItem=function(e){var n,a;if(!this.meta)return null;if(a=this.items[e],!a.data&&a.size)a.data=new Uint8Array(a.size),a.alreadyRead=0,this.itemsDataSize+=a.size,t.debug(`ISOFile`,`Allocating item #`+e+` of size `+a.size+` (total: `+this.itemsDataSize+`)`);else if(a.alreadyRead===a.size)return a;for(var o=0;o<a.extents.length;o++){var s=a.extents[o];if(s.alreadyRead!==s.length){var c=this.stream.findPosition(!0,s.offset+s.alreadyRead,!1);if(c>-1){n=this.stream.buffers[c];var l=n.byteLength-(s.offset+s.alreadyRead-n.fileStart);if(s.length-s.alreadyRead<=l)t.debug(`ISOFile`,`Getting item #`+e+` extent #`+o+` data (alreadyRead: `+s.alreadyRead+` offset: `+(s.offset+s.alreadyRead-n.fileStart)+` read size: `+(s.length-s.alreadyRead)+` full extent size: `+s.length+` full item size: `+a.size+`)`),r.memcpy(a.data.buffer,a.alreadyRead,n,s.offset+s.alreadyRead-n.fileStart,s.length-s.alreadyRead),n.usedBytes+=s.length-s.alreadyRead,this.stream.logBufferLevel(),a.alreadyRead+=s.length-s.alreadyRead,s.alreadyRead=s.length;else return t.debug(`ISOFile`,`Getting item #`+e+` extent #`+o+` partial data (alreadyRead: `+s.alreadyRead+` offset: `+(s.offset+s.alreadyRead-n.fileStart)+` read size: `+l+` full extent size: `+s.length+` full item size: `+a.size+`)`),r.memcpy(a.data.buffer,a.alreadyRead,n,s.offset+s.alreadyRead-n.fileStart,l),s.alreadyRead+=l,a.alreadyRead+=l,n.usedBytes+=l,this.stream.logBufferLevel(),null}else return null}}return a.alreadyRead===a.size?a:null},h.prototype.releaseItem=function(e){var t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=null,t.alreadyRead=0;for(var n=0;n<t.extents.length;n++){var r=t.extents[n];r.alreadyRead=0}return t.size}else return 0},h.prototype.processItems=function(e){for(var t in this.items){var n=this.items[t];this.getItem(n.id),e&&!n.sent&&(e(n),n.sent=!0,n.data=null)}},h.prototype.hasItem=function(e){for(var t in this.items){var n=this.items[t];if(n.name===e)return n.id}return-1},h.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},h.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},h.prototype.itemToFragmentedTrackFile=function(e){var t=e||{},n=null;if(n=t.itemId?this.getItem(t.itemId):this.getPrimaryItem(),n==null)return null;var r=new h;r.discardMdatData=!1;var a={type:n.type,description_boxes:n.properties.boxes};n.properties.ispe&&(a.width=n.properties.ispe.image_width,a.height=n.properties.ispe.image_height);var o=r.addTrack(a);return o?(r.addSample(o,n.data),r):null},h.prototype.write=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e)},h.prototype.createFragment=function(e,n,a){var o=this.getTrackById(e),s=this.getSample(o,n);if(s==null)return this.setNextSeekPositionFromSample(o.samples[n]),null;var l=a||new r;l.endianness=r.BIG_ENDIAN;var u=this.createSingleSampleMoof(s);u.write(l),u.trafs[0].truns[0].data_offset=u.size+8,t.debug(`MP4Box`,`Adjusting data_offset with new value `+u.trafs[0].truns[0].data_offset),l.adjustUint32(u.trafs[0].truns[0].data_offset_position,u.trafs[0].truns[0].data_offset);var d=new c.mdatBox;return d.data=s.data,d.write(l),l},h.writeInitializationSegment=function(e,n,a,o){var s;t.debug(`ISOFile`,`Generating initialization segment`);var c=new r;c.endianness=r.BIG_ENDIAN,e.write(c);var l=n.add(`mvex`);for(a&&l.add(`mehd`).set(`fragment_duration`,a),s=0;s<n.traks.length;s++)l.add(`trex`).set(`track_id`,n.traks[s].tkhd.track_id).set(`default_sample_description_index`,1).set(`default_sample_duration`,o).set(`default_sample_size`,0).set(`default_sample_flags`,65536);return n.write(c),c.buffer},h.prototype.save=function(e){var t=new r;t.endianness=r.BIG_ENDIAN,this.write(t),t.save(e)},h.prototype.getBuffer=function(){var e=new r;return e.endianness=r.BIG_ENDIAN,this.write(e),e.buffer},h.prototype.initializeSegmentation=function(){var e,n,r,a;for(this.onSegment===null&&t.warn(`MP4Box`,`No segmentation callback set!`),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),n=[],e=0;e<this.fragmentedTracks.length;e++){var o=new c.moovBox;o.mvhd=this.moov.mvhd,o.boxes.push(o.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),o.boxes.push(r),o.traks.push(r),a={},a.id=r.tkhd.track_id,a.user=this.fragmentedTracks[e].user,a.buffer=h.writeInitializationSegment(this.ftyp,o,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[e].samples.length>0?this.moov.traks[e].samples[0].duration:0),n.push(a)}return n},c.Box.prototype.printHeader=function(e){this.size+=8,this.size>a&&(this.size+=8),this.type===`uuid`&&(this.size+=16),e.log(e.indent+`size:`+this.size),e.log(e.indent+`type:`+this.type)},c.FullBox.prototype.printHeader=function(e){this.size+=4,c.Box.prototype.printHeader.call(this,e),e.log(e.indent+`version:`+this.version),e.log(e.indent+`flags:`+this.flags)},c.Box.prototype.print=function(e){this.printHeader(e)},c.ContainerBox.prototype.print=function(e){this.printHeader(e);for(var t=0;t<this.boxes.length;t++)if(this.boxes[t]){var n=e.indent;e.indent+=` `,this.boxes[t].print(e),e.indent=n}},h.prototype.print=function(e){e.indent=``;for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)},c.mvhdBox.prototype.print=function(e){c.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`timescale: `+this.timescale),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`rate: `+this.rate),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`next_track_id: `+this.next_track_id)},c.tkhdBox.prototype.print=function(e){c.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+`creation_time: `+this.creation_time),e.log(e.indent+`modification_time: `+this.modification_time),e.log(e.indent+`track_id: `+this.track_id),e.log(e.indent+`duration: `+this.duration),e.log(e.indent+`volume: `+(this.volume>>8)),e.log(e.indent+`matrix: `+this.matrix.join(`, `)),e.log(e.indent+`layer: `+this.layer),e.log(e.indent+`alternate_group: `+this.alternate_group),e.log(e.indent+`width: `+this.width),e.log(e.indent+`height: `+this.height)};var g={};g.createFile=function(e,t){var n=e===void 0?!0:e,r=new h(t);return r.discardMdatData=!n,r},e!==void 0&&(e.createFile=g.createFile)}))()),cJ=class extends Error{unsupported=!0;codec;constructor(e){super(`unsupported codec: ${e}`),this.name=`UnsupportedCodecError`,this.codec=e}};function lJ(e){return e instanceof Error&&e.unsupported===!0}function uJ(e){return e.replace(/^hev1\./i,`hvc1.`)}function dJ(e,t){let n=e.getTrackById(t)?.mdia?.minf?.stbl?.stsd?.entries??[];for(let e of n){let t=e.hvcC??e.avcC;if(t){let e=new sJ.DataStream(void 0,0,sJ.DataStream.BIG_ENDIAN);return t.write(e),new Uint8Array(e.buffer,8)}}}function fJ(e,t){if(e.length===0)return null;let n=e.findIndex(e=>e.is_sync);n<0&&(n=0);let r=e[n],a=r.cts/r.timescale*1e3,o=n;for(let r=n+1;r<e.length;r++){let n=e[r];if(n.cts/n.timescale*1e3-a<=t)o=r;else break}return{start:n,end:o}}function pJ(e,t){return new Promise((n,r)=>{e.onError=e=>r(Error(`mp4box: ${e}`)),e.onReady=t=>{let a=t.videoTracks?.[0];if(!a){r(Error(`no video track`));return}let o=dJ(e,a.id);n({config:{codec:uJ(a.codec),codedWidth:a.video?.width,codedHeight:a.video?.height,...o?{description:o}:{}},trackId:a.id})};let a=t;a.fileStart=0,e.appendBuffer(a),e.flush()})}async function mJ(e){let t=sJ.createFile(),{config:n,trackId:r}=await pJ(t,e);return{config:n,chunk:await new Promise((e,n)=>{t.onSamples=(t,r,a)=>{let o=a.find(e=>e.is_sync)??a[0];if(!o){n(Error(`no sample`));return}e(new EncodedVideoChunk({type:`key`,timestamp:Math.round(o.cts/o.timescale*1e6),data:o.data}))},t.setExtractionOptions(r,null,{nbSamples:1}),t.start()})}}var hJ=2048;async function gJ(e,t){let n=sJ.createFile(),{config:r,trackId:a}=await pJ(n,e);return{config:r,chunks:await new Promise((e,r)=>{n.onSamples=(n,a,o)=>{let s=fJ(o,t);if(!s){r(Error(`no sample`));return}let c=[];for(let e=s.start;e<=s.end;e++){let t=o[e];c.push(new EncodedVideoChunk({type:t.is_sync?`key`:`delta`,timestamp:Math.round(t.cts/t.timescale*1e6),data:t.data}))}e(c)},n.setExtractionOptions(a,null,{nbSamples:hJ}),n.start()})}}var _J=class{decoder=null;async decodeSegment(e){let{config:t,chunk:n}=await mJ(e);if(!(await VideoDecoder.isConfigSupported(t)).supported)throw new cJ(t.codec);return await new Promise((e,r)=>{this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let a=new VideoDecoder({output:t=>e(t),error:e=>r(e)});a.configure(t),this.decoder=a,a.decode(n),a.flush().catch(r)})}async decodeSegmentAt(e,t){let{config:n,chunks:r}=await gJ(e,t);if(!(await VideoDecoder.isConfigSupported(n)).supported)throw new cJ(n.codec);return await new Promise((e,t)=>{this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let a=null,o=new VideoDecoder({output:e=>{a?.close(),a=e},error:e=>t(e)});o.configure(n),this.decoder=o;for(let e of r)o.decode(e);o.flush().then(()=>{a?e(a):t(Error(`no frame decoded`))}).catch(t)})}close(){this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}},vJ=class{windowMs;maxSamples;samples=[];constructor(e){this.windowMs=e.windowMs,this.maxSamples=Math.max(2,e.maxSamples??6)}add(e,t){this.samples.push({epochMs:e,at:t}),this.samples.length>this.maxSamples&&(this.samples=this.samples.slice(this.samples.length-this.maxSamples))}velocity(){if(this.samples.length<2)return 0;let e=this.samples[0],t=this.samples[this.samples.length-1],n=t.at-e.at;return n<=0?0:(t.epochMs-e.epochMs)/n}windowKey(e){return Math.floor(e/this.windowMs)*this.windowMs}projectedWindowKeys(e,t,n){let r=Math.max(1,n),a=this.windowKey(e),o=this.velocity();if(o===0)return[a,a-this.windowMs,a+this.windowMs].slice(0,r);let s=e+o*t,c=o>0?1:-1,l=[a],u=a;for(;l.length<r&&(u+=c*this.windowMs,!(c>0&&u>s+this.windowMs||c<0&&u<s-this.windowMs));)l.push(u);return l.slice(0,r)}reset(){this.samples=[]}};function yJ(e){return e instanceof Error&&e.unsupported===!0}var bJ=class extends Error{permanent=!0;constructor(e){super(e),this.name=`PackPermanentError`}};function xJ(e){return e instanceof Error&&e.permanent===!0}var SJ=class{deps;windowMs;maxWindows;states=new Map;lru=[];dead=!1;maxPrefetch;prefetchHorizonMs;tracker;prefetches=new Map;disposed=!1;scrubSeq=0;constructor(e){this.deps=e,this.windowMs=e.windowMs??6e4,this.maxWindows=e.maxWindows??8,this.maxPrefetch=e.maxPrefetch??3,this.prefetchHorizonMs=e.prefetchHorizonMs??400,this.tracker=new vJ({windowMs:this.windowMs})}windowKey(e){return Math.floor(e/this.windowMs)*this.windowMs}touch(e){let t=this.lru.indexOf(e);for(t>=0&&this.lru.splice(t,1),this.lru.push(e);this.lru.length>this.maxWindows;){let e=this.lru.shift();if(e===void 0)break;let t=this.states.get(e);t?.kind===`decoded`&&t.window.close(),this.states.delete(e)}}ensureWindow(e,t){let n=this.states.get(e);if(n?.kind===`decoded`)return Promise.resolve(n.window);if(n?.kind===`empty`)return Promise.resolve(null);if(n?.kind===`loading`)return n.promise;let r=new AbortController,a=(async()=>{let n=await this.deps.fetchPack(e,r.signal);if(this.disposed)return null;if(n===null)return this.states.set(e,{kind:`empty`}),null;t?.(n);let a=await this.deps.decodePack(n);return this.disposed?(a.close(),null):(this.states.set(e,{kind:`decoded`,window:a}),this.touch(e),a)})().catch(t=>{throw this.states.delete(e),t});return this.states.set(e,{kind:`loading`,promise:a,abort:r}),a}nearest(e,t,n){let r=null,a=1/0,o=t=>{let n=0,o=t.ts.length-1;for(;n<o;){let r=n+o>>1;t.ts[r]<e?n=r+1:o=r}for(let o of[n-1,n]){if(o<0||o>=t.ts.length)continue;let n=Math.abs(t.ts[o]-e);n<a&&(a=n,r=t.bitmaps[o]??null)}};o(t);let s=this.windowMs/10;for(let t of[n-this.windowMs,n+this.windowMs]){let r=t<n?e-n<s:n+this.windowMs-e<s,a=this.states.get(t);r&&a?.kind===`decoded`&&o(a.window)}return r}async scrubTo(e){if(this.dead||this.disposed)return!1;let t=++this.scrubSeq,n=Date.now(),r=this.windowKey(e),a=this.states.get(r)?.kind===`decoded`,o;try{o=await this.ensureWindow(r,n=>this.tryFastPaint(n,e,t))}catch(e){if(yJ(e)||xJ(e))throw this.dead=!0,e;return!1}if(t!==this.scrubSeq||o===null)return!1;this.touch(r);let s=this.nearest(e,o,r);return s?(this.deps.draw(s),this.deps.onTiming?.({epochMs:e,cached:a,totalMs:Date.now()-n}),this.tracker.add(e,Date.now()),this.prefetchWindows(this.tracker.projectedWindowKeys(e,this.prefetchHorizonMs,this.maxPrefetch)),!0):!1}tryFastPaint(e,t,n){let r=this.deps.decodeFirstFrame;r&&r(e,t).then(e=>{if(e){if(n!==this.scrubSeq||this.disposed||this.dead){e.bitmap.close();return}this.deps.draw(e.bitmap),e.bitmap.close()}}).catch(()=>{})}prefetchWindows(e){if(!(this.dead||this.disposed))for(let t of e){if(this.prefetches.size>=this.maxPrefetch)break;if(this.states.has(t)||this.prefetches.has(t))continue;let e=new AbortController;this.prefetches.set(t,e),this.ensureWindow(t).catch(()=>{}).finally(()=>{this.prefetches.get(t)===e&&this.prefetches.delete(t)})}}armPrefetch(e){let t=this.windowKey(e);this.prefetchWindows([t,t-this.windowMs,t+this.windowMs])}dispose(){this.disposed=!0,this.scrubSeq++;for(let e of this.states.values())e.kind===`decoded`&&e.window.close(),e.kind===`loading`&&e.abort.abort();this.states.clear(),this.lru.length=0;for(let e of this.prefetches.values())e.abort();this.prefetches.clear(),this.tracker.reset()}};function CJ(e){if(e.byteLength<4)throw Error(`scrub pack: truncated (no length prefix)`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0);if(t<=0||4+t>e.byteLength)throw Error(`scrub pack: bogus header length ${t}`);let n=new TextDecoder().decode(e.subarray(4,4+t)),r=JSON.parse(n);if(r.v!==1)throw Error(`scrub pack: unsupported version ${String(r.v)}`);if(!Array.isArray(r.frames))throw Error(`scrub pack: malformed header (frames)`);return{header:r,payloadOffset:4+t}}function wJ(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function TJ(e){return{codec:e.codec,description:wJ(e.description),optimizeForLatency:!0}}function EJ(e,t){let n=-1,r=1/0;for(let a=0;a<e.length;a++){let o=Math.abs(e[a].ts-t);o<r&&(r=o,n=a)}return n}async function DJ(e){let t=new Uint8Array(e),{header:n,payloadOffset:r}=CJ(t),a=TJ(n);if(!(await VideoDecoder.isConfigSupported(a)).supported)throw new cJ(n.codec);let o=[],s=[],c=new Promise((e,c)=>{let l=new VideoDecoder({output:e=>{let t=e.timestamp/1e3;s.push(createImageBitmap(e).then(e=>{o.push({ts:t,bitmap:e})}).finally(()=>{e.close()}))},error:e=>c(e)});l.configure(a);for(let e of n.frames)l.decode(new EncodedVideoChunk({type:`key`,timestamp:e.ts*1e3,data:t.subarray(r+e.offset,r+e.offset+e.size)}));l.flush().then(()=>{l.close(),e()}).catch(c)});try{await c,await Promise.all(s)}catch(e){await Promise.allSettled(s);for(let e of o)e.bitmap.close();throw e}o.sort((e,t)=>e.ts-t.ts);let l=o.map(e=>e.ts),u=o.map(e=>e.bitmap);return{ts:l,bitmaps:u,close(){for(let e of u)e.close()}}}async function OJ(e,t){let n=new Uint8Array(e),{header:r,payloadOffset:a}=CJ(n),o=r.frames[t];if(!o)return null;let s=TJ(r);if(!(await VideoDecoder.isConfigSupported(s)).supported)throw new cJ(r.codec);try{return await new Promise((e,t)=>{let r=null,c=new VideoDecoder({output:e=>{let t=e.timestamp/1e3;r=createImageBitmap(e).then(e=>({ts:t,bitmap:e})).finally(()=>e.close())},error:e=>t(e)});c.configure(s),c.decode(new EncodedVideoChunk({type:`key`,timestamp:o.ts*1e3,data:n.subarray(a+o.offset,a+o.offset+o.size)})),c.flush().then(async()=>{c.close(),e(r?await r:null)}).catch(t)})}catch(e){if(e instanceof cJ)throw e;return null}}async function kJ(e,t){let{header:n}=CJ(new Uint8Array(e)),r=EJ(n.frames,t);return r<0?null:OJ(e,r)}var AJ=class{deps;engine=null;dead=!1;constructor(e){this.deps=e}isDead(){return this.dead}async scrubTo(e){if(this.dead)return`fallthrough`;this.engine||=this.buildEngine();try{return await this.engine.scrubTo(e)?(this.deps.onDrawn(),`drawn`):`fallthrough`}catch(e){return this.dead=!0,this.deps.onDead?.(e),`fallthrough`}}armPrefetch(e){this.dead||(this.engine||=this.buildEngine(),this.engine.armPrefetch(e))}dispose(){this.engine?.dispose(),this.engine=null}buildEngine(){let e=this.deps.fetchImpl??fetch,t=this.deps.decodeWindow??DJ;return new SJ({fetchPack:async(t,n)=>{let r=await e(`/addon/recorder/scrub/${this.deps.deviceId}/${t/1e3}`,{signal:n,credentials:`include`,headers:this.deps.requestHeaders});if(r.status===204)return null;if(r.status===404||r.status===400)throw new bJ(`scrub pack endpoint absent/drift: ${r.status}`);if(!r.ok)throw Error(`scrub pack fetch failed: ${r.status}`);return r.arrayBuffer()},decodePack:async e=>{try{return await t(e)}catch(e){throw e instanceof Error&&e.message.startsWith(`scrub pack:`)?new bJ(e.message):e}},decodeFirstFrame:this.deps.decodeFirstFrame??kJ,draw:e=>{this.deps.draw(e),this.deps.onDrawn()},onTiming:this.deps.onTiming})}};function jJ(){let e=!1;return{fire(){return e?!1:(e=!0,!0)},reset(){e=!1}}}async function MJ(e){if(!e.hasVideoDecoder)return{capability:`unavailable`,reason:`no VideoDecoder`};let t=!1;try{t=await e.isVideoSupported(e.videoConfig)}catch{t=!1}return t?e.hasAudioDecoder?{capability:`webcodecs-av`,reason:`ok`}:{capability:`webcodecs-video-only`,reason:`no AudioDecoder`}:{capability:`unavailable`,reason:`video config unsupported: ${e.videoConfig.codec}`}}function NJ(e){return!Number.isFinite(e)||e<=0?0:Math.min(4,Math.max(.25,e))}function PJ(e,t,n,r){return e<t&&n<r}var FJ=1500,IJ=8,LJ=1e3,RJ=2,zJ=50,BJ=30;function VJ(e){typeof e==`object`&&e&&`unref`in e&&e.unref()}var HJ=class{deps;gen=0;disposed=!1;dead=!1;requestedRate;requestedProfile;activeProfile;current=null;lastDrawn=null;cancelRaf=null;positionTimer=null;submittedUpToUs=0;activeLoadAc=null;targetAheadMs;maxQueue;constructor(e){this.deps=e,this.requestedRate=e.initialRate??0,this.requestedProfile=e.profile,this.activeProfile=e.profile,this.targetAheadMs=e.targetAheadMs??FJ,this.maxQueue=e.maxQueue??IJ,this.scheduleDraw()}mode(){return this.requestedRate===1&&this.deps.audio?`audio`:`video`}supersede(){return this.activeLoadAc?.abort(),this.activeLoadAc=null,++this.gen}abortDead(e,t){this.dead||this.disposed||(this.dead=!0,this.supersede(),this.deps.clock.pause(),this.deps.audio?.stop(),this.cancelRaf?.(),this.cancelRaf=null,this.stopPositionReports(),this.deps.onState(`error`),this.deps.onDead(t??this.deps.clock.playheadMs(),e))}async seek(e){let t=this.supersede();this.deps.onState(`loading`),this.deps.video.reset(),this.deps.ring.clear(),this.deps.audio?.stop(),this.lastDrawn=null;try{await this.deps.ensureIndex(e)}catch(n){t===this.gen&&this.abortDead(n,e);return}if(this.disposed||t!==this.gen)return;let n=this.deps.locate(e),r=e;if(n.kind===`gap`){if(n.nearestEdgeMs===null){this.deps.clock.seekTo(e),this.deps.onState(`ended`),this.stopPositionReports();return}if(r=n.nearestEdgeMs,n=this.deps.locate(r),n.kind!==`segment`){this.deps.onState(`gap`);return}}let a=n.seg,o=new AbortController;this.activeLoadAc=o;let s;try{s=await this.deps.loadSegment(a.startMs,o.signal)}catch(n){t===this.gen&&this.abortDead(n,e);return}if(this.disposed||t!==this.gen)return;this.current={startMs:a.startMs,durMs:a.durMs,demux:s},this.deps.video.configure(s.video.config);let c=r*1e3,l=0;for(let e of s.video.chunks)if(this.deps.video.submit(e),l=e.timestamp,e.timestamp>=c)break;if(this.submittedUpToUs=l,await this.deps.video.flush(),this.disposed||t!==this.gen)return;this.deps.clock.seekTo(r);let u=this.deps.ring.frameFor(r);if(u&&(this.deps.draw(u),this.lastDrawn=u),this.deps.onPosition(r),this.requestedRate===0){this.deps.onState(`paused`),this.stopPositionReports();return}this.startPlaying(r,s)}startPlaying(e,t){this.deps.audio?.stop();let n=this.deps.audio,r=t.audio,a=this.gen;this.deps.onState(`playing`),this.startPositionReports(),this.mode()===`audio`&&n&&r?(n.configure(r.config),n.resumeContext().then(()=>{this.disposed||a!==this.gen||(n.enqueue(r.chunks,e),this.deps.clock.play(1,`audio`,e,()=>n.audioNowSec()),this.decodeAheadLoop(a))})):(this.deps.clock.play(this.requestedRate,`video`),this.decodeAheadLoop(a))}async decodeAheadLoop(e){for(;!this.disposed&&e===this.gen&&!this.deps.clock.paused;){let t=this.deps.clock.playheadMs(),n=this.deps.ring.bufferedAheadMs(t);if(PJ(this.deps.video.queueSize,this.maxQueue,n,this.targetAheadMs)){let t;try{t=await this.nextChunk(e)}catch(t){if(this.disposed||e!==this.gen)return;this.abortDead(t);return}if(this.disposed||e!==this.gen)return;t?this.deps.video.submit(t):await this.sleep(zJ)}else await this.sleep(BJ)}}async nextChunk(e){let t=this.current;if(!t)return null;for(let e of t.demux.video.chunks)if(e.timestamp>this.submittedUpToUs)return this.submittedUpToUs=e.timestamp,e;let n=this.deps.locate(t.startMs+t.durMs),r;if(n.kind===`segment`)r=n.seg.startMs;else if(n.nearestEdgeMs!==null)r=n.nearestEdgeMs;else return null;let a=this.deps.locate(r);if(a.kind!==`segment`)return null;let o=new AbortController;this.activeLoadAc=o;let s=await this.deps.loadSegment(a.seg.startMs,o.signal);if(this.disposed||e!==this.gen)return null;this.current={startMs:a.seg.startMs,durMs:a.seg.durMs,demux:s},this.deps.video.configure(s.video.config);let c=s.video.chunks[0];return c?(this.submittedUpToUs=c.timestamp,c):null}tick(){if(this.disposed||this.dead)return;let e=this.deps.clock.playheadMs();if(this.current&&!this.deps.clock.paused&&e>=this.current.startMs+this.current.durMs){let t=this.deps.locate(e);if(t.kind===`gap`){if(t.nearestEdgeMs===null){this.deps.clock.pause(),this.deps.onState(`ended`),this.stopPositionReports();return}this.deps.onState(`gap`),this.deps.clock.seekTo(t.nearestEdgeMs),this.seek(t.nearestEdgeMs);return}}let t=this.deps.ring.frameFor(e);t&&t!==this.lastDrawn&&(this.deps.draw(t),this.lastDrawn=t),this.deps.ring.evictBehind(e)}scheduleDraw(){let e=()=>{this.tick(),!this.disposed&&!this.dead&&(this.cancelRaf=this.deps.raf(e))};this.cancelRaf=this.deps.raf(e)}setRate(e){let t=NJ(e);if(t===this.requestedRate)return;this.requestedRate=t;let n=t>RJ?`low`:this.requestedProfile;if(n!==this.activeProfile){this.setProfile(n,!0).catch(e=>{this.disposed||this.abortDead(e)});return}if(this.supersede(),t===0){this.deps.clock.pause(),this.deps.audio?.stop(),this.deps.onState(`paused`),this.stopPositionReports();return}let r=this.deps.clock.playheadMs();if(!this.current){this.seek(r);return}this.startPlaying(r,this.current.demux)}getActiveProfile(){return this.activeProfile}async setProfile(e,t=!1){t||(this.requestedProfile=e),this.activeProfile=e;let n=this.deps.clock.playheadMs();await this.deps.ensureIndex(n),!this.disposed&&await this.seek(n)}stepFrame(e){if(this.disposed||this.requestedRate!==0)return;let t=this.current;if(!t)return;let n=this.deps.clock.playheadMs();if(e===1){let e=t.demux.video.chunks.find(e=>e.timestamp/1e3>n+1);if(e){this.paintExact(e.timestamp/1e3);return}let r=this.deps.locate(t.startMs+t.durMs);r.kind===`segment`?this.seek(r.seg.startMs):r.nearestEdgeMs!==null&&this.seek(r.nearestEdgeMs);return}let r=[...t.demux.video.chunks].reverse().find(e=>e.timestamp/1e3<n-1);if(r){this.paintExact(r.timestamp/1e3);return}let a=this.deps.locate(t.startMs-1);a.kind===`gap`&&a.prevEndMs!==null?this.seek(a.prevEndMs-1):a.kind===`segment`&&this.seek(a.seg.startMs+a.seg.durMs-1)}async paintExact(e){let t=this.supersede(),n=this.current;if(!n)return;this.deps.video.reset(),this.deps.ring.clear(),this.lastDrawn=null,this.deps.video.configure(n.demux.video.config);let r=e*1e3,a=0;for(let e of n.demux.video.chunks)if(this.deps.video.submit(e),a=e.timestamp,e.timestamp>=r)break;if(this.submittedUpToUs=a,await this.deps.video.flush(),this.disposed||t!==this.gen)return;this.deps.clock.seekTo(e);let o=this.deps.ring.frameFor(e);o&&(this.deps.draw(o),this.lastDrawn=o),this.deps.onPosition(e),this.deps.onState(`paused`)}pauseForScrub(){this.supersede(),this.deps.clock.pause(),this.deps.audio?.stop(),this.stopPositionReports()}async resumeFromScrub(e){await this.seek(e)}startPositionReports(){if(this.positionTimer)return;let e=setInterval(()=>{!this.disposed&&!this.deps.clock.paused&&this.deps.onPosition(this.deps.clock.playheadMs())},LJ);VJ(e),this.positionTimer=e}stopPositionReports(){this.positionTimer&&=(clearInterval(this.positionTimer),null)}sleep(e){return new Promise(t=>{VJ(setTimeout(t,e))})}dispose(){this.disposed=!0,this.supersede(),this.cancelRaf?.(),this.cancelRaf=null,this.stopPositionReports(),this.lastDrawn=null,this.deps.ring.clear(),this.deps.video.close(),this.deps.audio?.close()}};function UJ(e){try{return new URL(e).toString()}catch{let t=typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost`;return new URL(e,t).toString()}}function WJ(e){let t=(e.split(`/`).pop()??``).match(/^(\d+)-(\d+)(?:-\d+)?\.m4s$/);return t?{startMs:Number(t[1]),durMs:Number(t[2])}:null}function GJ(e,t,n){let r=e.split(`
|
|
115
115
|
`).map(e=>e.trim()),a=RegExp(`NAME="${n}"`,`i`);for(let e=0;e<r.length;e++){let n=r[e],o=r[e+1];if(n&&n.startsWith(`#EXT-X-STREAM-INF`)&&a.test(n)&&o&&!o.startsWith(`#`))return new URL(o,t).toString()}let o=RegExp(`(^|/)${n}\\.m3u8$`,`i`);for(let e of r)if(e&&!e.startsWith(`#`)&&o.test(e))return new URL(e,t).toString();return null}async function KJ(e,t,n){let r=await n(e,t?{headers:t}:void 0);if(!r.ok)throw Error(`playlist fetch ${r.status} for ${e}`);return r.text()}async function qJ(e,t,n,r=fetch){let a=UJ(e),o=GJ(await KJ(a,n,r),a,t);if(!o)return[];let s=await KJ(o,n,r),c=[];for(let e of s.split(`
|
|
116
|
-
`).map(e=>e.trim())){if(!e||e.startsWith(`#`))continue;let t=new URL(e,o).toString(),n=WJ(t);n&&c.push({uri:t,startMs:n.startMs,durMs:n.durMs})}return c.sort((e,t)=>e.startMs-t.startMs),c}function JJ(e,t){if(e.length===0)return{kind:`gap`,nearestEdgeMs:null,prevEndMs:null};let n=null,r=null;for(let a of e){let e=a.startMs+a.durMs;if(t>=a.startMs&&t<e)return{kind:`segment`,seg:a};e<=t&&(n=n===null?e:Math.max(n,e)),a.startMs>t&&(r===null||a.startMs<r)&&(r=a.startMs)}if(r!==null&&n!==null&&r-n<=40&&t>=n&&t<r){let t=e.find(e=>e.startMs===r);if(t)return{kind:`segment`,seg:t}}return{kind:`gap`,nearestEdgeMs:r,prevEndMs:n}}var YJ={video:e=>new EncodedVideoChunk(e),audio:e=>new EncodedAudioChunk(e)};function XJ(e){return e.replace(/^hev1\./i,`hvc1.`)}function ZJ(e,t,n,r){return Math.round((e+(t-n)/r*1e3)*1e3)}function QJ(e,t){let n=e.getTrackById(t)?.mdia?.minf?.stbl?.stsd?.entries??[];for(let e of n){let t=e.hvcC??e.avcC;if(t){let e=new sJ.DataStream(void 0,0,sJ.DataStream.BIG_ENDIAN);return t.write(e),new Uint8Array(e.buffer,8)}}}function $J(e,t){return new Promise((n,r)=>{e.onError=e=>r(Error(`mp4box: ${e}`)),e.onReady=t=>{let a=t.videoTracks?.[0];if(!a){r(Error(`no video track`));return}let o=QJ(e,a.id),s={codec:XJ(a.codec),codedWidth:a.video?.width,codedHeight:a.video?.height,optimizeForLatency:!0,...o?{description:o}:{}},c=t.audioTracks?.[0],l=null,u=null;c&&(l=c.id,u={codec:c.codec,sampleRate:c.audio?.sample_rate??48e3,numberOfChannels:c.audio?.channel_count??1}),n({videoTrackId:a.id,videoConfig:s,audioTrackId:l,audioConfig:u})};let a=t;a.fileStart=0,e.appendBuffer(a),e.flush()})}async function eY(e,t,n,r=YJ){let a=await $J(e,t),o=[],s=[],c=null,l=null;e.onSamples=(e,t,u)=>{for(let t of u)e===a.videoTrackId?(c===null&&(c=t.cts),o.push(r.video({type:t.is_sync?`key`:`delta`,timestamp:ZJ(n,t.cts,c,t.timescale),data:t.data}))):a.audioTrackId!==null&&e===a.audioTrackId&&(l===null&&(l=t.cts),s.push(r.audio({type:`key`,timestamp:ZJ(n,t.cts,l,t.timescale),data:t.data})))},e.setExtractionOptions(a.videoTrackId,null,{nbSamples:1e5}),a.audioTrackId!==null&&e.setExtractionOptions(a.audioTrackId,null,{nbSamples:1e5});try{e.start()}catch{}let u=a.audioConfig&&s.length>0?{config:a.audioConfig,chunks:s}:null;return{video:{config:a.videoConfig,chunks:o},audio:u}}function tY(e,t){return eY(sJ.createFile(),e,t)}var nY=class{deps;decoder=null;config=null;factory;constructor(e){this.deps=e,this.factory=e.decoderFactory??(e=>new VideoDecoder(e))}ensureDecoder(){if(this.decoder&&this.decoder.state!==`closed`)return this.decoder;let e=this.factory({output:e=>{this.deps.ring.push({tsMs:e.timestamp/1e3,frame:e,close:()=>e.close()})},error:e=>this.deps.onError(e)});return this.decoder=e,this.config&&e.configure(this.config),e}configure(e){this.config=e;let t=this.ensureDecoder();t.state!==`closed`&&t.configure(e)}submit(e){this.ensureDecoder().decode(e)}get queueSize(){return this.decoder?.decodeQueueSize??0}async flush(){if(this.decoder&&this.decoder.state===`configured`)try{await this.decoder.flush()}catch(e){this.deps.onError(e)}}reset(){this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}close(){this.reset()}},rY=class{ctx=null;decoder=null;config=null;base=0;nextStartTime=0;sources=[];ensureCtx(){return this.ctx||=new AudioContext,this.ctx}configure(e){this.config=e}async resumeContext(){let e=this.ensureCtx();e.state===`suspended`&&await e.resume()}enqueue(e,t){if(!this.config||e.length===0)return;let n=this.ensureCtx();this.base=t,this.nextStartTime=n.currentTime,this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let r=new AudioDecoder({output:e=>this.scheduleAudioData(n,e),error:()=>{}});r.configure(this.config),this.decoder=r;for(let n of e)n.timestamp/1e3>=t&&r.decode(n)}scheduleAudioData(e,t){let n=t.numberOfFrames,r=t.numberOfChannels,a=t.sampleRate,o;try{o=e.createBuffer(r,n,a);for(let e=0;e<r;e++){let n=o.getChannelData(e);t.copyTo(n,{planeIndex:e,format:`f32-planar`})}}finally{t.close()}let s=e.createBufferSource();s.buffer=o,s.connect(e.destination);let c=Math.max(e.currentTime,this.nextStartTime);s.start(c),this.nextStartTime=c+o.duration,this.sources.push(s),s.onended=()=>{this.sources=this.sources.filter(e=>e!==s)}}audioNowSec(){return this.ctx?this.ctx.currentTime:0}baseEpochMs(){return this.base}stop(){for(let e of this.sources)try{e.stop()}catch{}this.sources=[],this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}close(){this.stop(),this.ctx&&this.ctx.close(),this.ctx=null}},iY=class{opts;frames=[];constructor(e){this.opts=e}get size(){return this.frames.length}push(e){let t=0,n=this.frames.length;for(;t<n;){let r=t+n>>1;this.frames[r].tsMs<e.tsMs?t=r+1:n=r}for(this.frames.splice(t,0,e);this.frames.length>this.opts.maxFrames;)this.frames.shift()?.close()}frameFor(e){let t=null;for(let n of this.frames)if(n.tsMs<=e)t=n;else break;return t}bufferedAheadMs(e){let t=this.frames[this.frames.length-1];return t?Math.max(0,t.tsMs-e):0}evictBehind(e){let t=e-this.opts.keepBehindMs;for(;this.frames.length>0&&this.frames[0].tsMs<t;)this.frames.shift().close()}clear(){for(let e of this.frames)e.close();this.frames=[]}},aY=class{now;baseEpochMs=0;wallAnchorMs=0;_rate=0;_paused=!0;mode=`video`;audioAnchorS=0;audioNow=null;constructor(e=()=>performance.now()){this.now=e}get rate(){return this._rate}get paused(){return this._paused}seekTo(e){this.baseEpochMs=e,this.wallAnchorMs=this.now(),this._paused=!0,this._rate=0,this.audioNow=null}play(e,t,n,r){this.baseEpochMs=t===`audio`&&n!==void 0?n:this.playheadMs(),this.wallAnchorMs=this.now(),this._rate=e,this._paused=!1,this.mode=t,t===`audio`&&r?(this.audioNow=r,this.audioAnchorS=r()):this.audioNow=null}pause(){this.baseEpochMs=this.playheadMs(),this._paused=!0,this._rate=0,this.audioNow=null}setRate(e,t){this.baseEpochMs=this.playheadMs(),this.wallAnchorMs=this.now(),this._rate=e,this._paused=e===0,this.mode=t,this.audioNow=null}playheadMs(){return this._paused?this.baseEpochMs:this.mode===`audio`&&this.audioNow?this.baseEpochMs+(this.audioNow()-this.audioAnchorS)*1e3:this.baseEpochMs+(this.now()-this.wallAnchorMs)*this._rate}},oY=90,sY=250,cY=6,lY=1440*60*1e3,uY=class{deps;engine=null;profile;index=[];indexWindow=null;bytes=new Yq(cY);ring=new iY({maxFrames:oY,keepBehindMs:sY});clock=new aY;constructor(e){this.deps=e,this.profile=`mid`}doFetch(){let e=this.deps.fetchImpl??fetch,t=this.deps.requestHeaders;return(n,r)=>{let a=new Headers(t);return r?.headers&&new Headers(r.headers).forEach((e,t)=>a.set(t,e)),e(n,{...r,credentials:`include`,headers:a})}}ensureIndex=async e=>{let t=this.engine?.getActiveProfile();t&&t!==this.profile&&(this.profile=t,this.indexWindow=null);let n=this.indexWindow;if(n&&e>=n.fromMs&&e<n.toMs&&this.index.length>0)return;let r=new Date(e);r.setHours(0,0,0,0);let a=r.getTime(),o=a+lY,s=await this.deps.getManifestUrl(a,o);if(!s){this.index=[],this.indexWindow=null;return}this.index=await qJ(s,this.profile,this.deps.requestHeaders,this.doFetch()),this.indexWindow={fromMs:a,toMs:o}};locate=e=>JJ(this.index,e);loadSegment=async(e,t)=>{let n=this.index.find(t=>t.startMs===e);if(!n)throw Error(`no segment at ${e}`);let r=this.bytes.get(n.uri);if(!r){let e=await this.doFetch()(n.uri,{signal:t});if(!e.ok)throw Error(`segment fetch failed: ${e.status}`);r=await e.arrayBuffer(),this.bytes.set(n.uri,r)}return(this.deps.demuxImpl??tY)(r,n.startMs)};buildEngine(){let e=this.deps.videoFactory??(e=>new nY(e)),t=null,n=e({ring:this.ring,onError:e=>t?.abortDead(e)}),r=this.deps.audioFactory??(()=>new rY),a=this.deps.hasAudio?r():null,o=new HJ({locate:this.locate,loadSegment:this.loadSegment,video:n,audio:a,ring:this.ring,clock:this.clock,draw:e=>this.deps.draw(e),onState:e=>this.deps.onState(e),onPosition:e=>this.deps.onPosition(e),now:()=>performance.now(),raf:this.deps.raf??(e=>{let t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)}),onDead:(e,t)=>this.deps.onDead(e,t),ensureIndex:this.ensureIndex,profile:this.profile});return t=o,o}async playRecorded(e,t,n){this.engine&&n!==this.profile&&(this.engine.dispose(),this.engine=null),this.profile=n,this.indexWindow=null,this.engine||=this.buildEngine(),await this.engine.seek(t)}async seek(e){this.engine&&await this.engine.seek(e)}async commit(e){this.engine&&await this.engine.resumeFromScrub(e)}setRate(e){this.engine?.setRate(e)}stepFrame(e){this.engine?.stepFrame(e)}pauseForScrub(){this.engine?.pauseForScrub()}dispose(){this.engine?.dispose(),this.engine=null,this.ring.clear(),this.bytes.clear(),this.index=[],this.indexWindow=null}},dY=Co([B({kind:U(`adaptive`)}),B({kind:U(`profile`),profile:ps})]),fY=B({serverUrl:P().min(1),token:P().min(1),deviceId:F().int().nonnegative(),target:dY,muted:I(),stats:I().optional(),highlight:NK.optional(),snapshot:P().optional()});function pY(e,t){try{return new URL(t,e).toString()}catch{return t}}function mY(e,t){RK(t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t})}function hY(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function gY(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function _Y(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function vY(e){let t=fY.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function yY({message:e}){return(0,S.useEffect)(()=>{mY(`error`,e)},[e]),(0,C.jsxs)(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function bY({system:e,deviceId:t,token:n,initialTarget:r,initialMuted:a,initialStats:o,initialHighlight:s,initialSnapshot:c}){let[l,u]=(0,S.useState)(r),[d,f]=(0,S.useState)(a),[p,m]=(0,S.useState)(o),[h,g]=(0,S.useState)(s),[_,v]=(0,S.useState)(c),[y,b]=(0,S.useState)(0),[x,w]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),T=Mq(e,t,h),E=aq(),D=(0,S.useRef)(E.setActiveMic);D.current=E.setActiveMic;let ee=(0,S.useRef)(0),{handleOffer:te,getIceServers:O,addIceCandidate:ne,getIceCandidates:re,closeSession:ie,getSessionState:ae}=AK(e.trpcClient,t),oe=(0,S.useMemo)(()=>gY(l),[l]),se=(0,S.useMemo)(()=>(e,t,n)=>te(oe,e,t,n),[te,oe]),k=(0,S.useMemo)(()=>(e,t,n,r)=>te(n,t,e,r),[te]),A=(0,S.useRef)(null),[ce,le]=(0,S.useState)(!1),[ue,de]=(0,S.useState)(!1),j=(0,S.useRef)(null),M=(0,S.useRef)(null),fe=(0,S.useRef)(null),pe=(0,S.useRef)(jJ()),me=(0,S.useRef)([]),he=(0,S.useRef)(null),ge=(0,S.useRef)(!1),_e=(0,S.useMemo)(()=>({Authorization:`Bearer ${n}`}),[n]),N=(0,S.useMemo)(()=>async n=>{let r=he.current;if(r&&n>=r.fromMs&&n<r.toMs&&me.current.length>0)return me.current;let a=new Date(n);a.setHours(0,0,0,0);let o=a.getTime(),s=o+1440*60*1e3,c=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t,fromMs:o,toMs:s});return c?.playbackUrl?(me.current=await tJ(c.playbackUrl,_e),he.current={fromMs:o,toMs:s},me.current):me.current},[e,t,_e]),ve=(0,S.useMemo)(()=>e=>{let t=A.current,n=t?.getContext(`2d`);if(!t||!n)return;t.width=x.w,t.height=x.h;let r=`displayWidth`in e?e.displayWidth||e.codedWidth:typeof e.width==`number`?e.width:0,a=`displayHeight`in e?e.displayHeight||e.codedHeight:typeof e.height==`number`?e.height:0;if(r<=0||a<=0)return;let o=Math.min(x.w/r,x.h/a),s=r*o,c=a*o;n.clearRect(0,0,x.w,x.h),n.drawImage(e,(x.w-s)/2,(x.h-c)/2,s,c),de(!0)},[x.w,x.h]),ye=(0,S.useRef)(ve);ye.current=ve;let[be,xe]=(0,S.useState)(null),Se=(0,S.useRef)(null),[Ce,we]=(0,S.useState)(!1);(0,S.useEffect)(()=>{let e=!0;return(async()=>{let t=typeof VideoDecoder<`u`,n=await MJ({videoConfig:{codec:`hvc1.1.6.L120.B0`},hasVideoDecoder:t,hasAudioDecoder:typeof AudioDecoder<`u`,isVideoSupported:async e=>t?(await VideoDecoder.isConfigSupported(e)).supported===!0:!1});e&&xe(n.capability)})(),()=>{e=!1}},[]);let Te=(0,S.useCallback)(()=>{if(Se.current)return Se.current;let n=new uY({deviceId:t,requestHeaders:_e,getManifestUrl:async(n,r)=>{let a=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t,fromMs:n,toMs:r});return a?.playbackUrl?pY(e.serverUrl,a.playbackUrl):null},draw:e=>{e.frame&&ye.current(e.frame)},onState:e=>RK({type:`recState`,state:e}),onPosition:e=>{ee.current=e,RK({type:`position`,positionMs:e})},onDead:(e,t)=>{Se.current?.dispose(),Se.current=null,we(!1),RK({type:`log`,scope:`wc-playback`,msg:`tier dead — no recorded surface`,data:{epoch:e,cause:t instanceof Error?t.message:t}}),RK({type:`recState`,state:`error`})},hasAudio:be===`webcodecs-av`});return Se.current=n,n},[t,_e,e,be]),Ee=(0,S.useRef)(Te);Ee.current=Te;let De=(0,S.useRef)(be);De.current=be;let Oe=(0,S.useMemo)(()=>async e=>{if(fe.current||=new AJ({deviceId:t,requestHeaders:_e,draw:e=>ye.current(e),onDrawn:()=>{pe.current.fire()&&RK({type:`scrubDrawn`})},onDead:e=>RK({type:`log`,scope:`scrub`,msg:`pack tier dead — legacy tier takes over`,data:{msg:e instanceof Error?e.message:String(e)}}),onTiming:e=>RK({type:`log`,scope:`scrub`,msg:`pack timing`,data:e})}),await fe.current.scrubTo(e)!==`drawn`){j.current||=new _J,M.current||=new oJ({ensureIndex:e=>N(e),fetchBytes:async(e,t)=>{let n=await fetch(e,{signal:t,headers:_e});if(!n.ok)throw Error(`segment fetch failed: ${n.status}`);return n.arrayBuffer()},decode:e=>{let t=j.current;if(!t)throw Error(`decoder not initialised`);return t.decodeSegment(e)},decodeAt:(e,t)=>{let n=j.current;if(!n)throw Error(`decoder not initialised`);return n.decodeSegmentAt(e,t)},draw:e=>ye.current(e)});try{await M.current.scrubTo(e)}catch(e){lJ(e)&&!ge.current&&(ge.current=!0,RK({type:`log`,scope:`scrub`,msg:`webcodecs-unsupported`,data:{codec:e.codec}}))}}},[N,_e,t]),ke=(0,S.useRef)(Oe);ke.current=Oe,(0,S.useEffect)(()=>()=>{M.current?.dispose(),fe.current?.dispose(),Se.current?.dispose()},[]),(0,S.useEffect)(()=>{let e=e=>{le(!1);let n=Se.current;if(n){n.commit(e);return}if(De.current===`unavailable`){RK({type:`recState`,state:`error`});return}we(!0),Ee.current().playRecorded(t,e,`mid`)};return window.__camstackEmbed={setMuted:e=>f(e),setTarget:e=>{let t=dY.safeParse(e);t.success&&u(t.data)},setStats:e=>m(e),setHighlight:e=>g(e),setSnapshot:e=>v(e),setMic:e=>D.current(e?t:null),fit:(e,t)=>w({w:e,h:t}),reconnect:()=>b(e=>e+1),playRecorded:(e,t,n)=>{if(De.current===`unavailable`){RK({type:`log`,scope:`recorded:engine`,msg:`webcodecs-unavailable`,data:{capability:De.current}}),RK({type:`recState`,state:`error`});return}we(!0),Ee.current().playRecorded(e,t,n)},seek:e=>{Number.isFinite(e)&&Se.current?.seek(e)},scrubCommit:t=>{Number.isFinite(t)&&e(t)},scrubStart:()=>{RK({type:`log`,scope:`recorded:scrub`,msg:`pack`,data:{route:`pack`}}),Se.current?.pauseForScrub(),de(!1),pe.current.reset(),le(!0),ee.current>0&&fe.current?.armPrefetch(ee.current)},scrubTo:e=>{Number.isFinite(e)&&ke.current(e)},scrubEnd:t=>{Number.isFinite(t)&&e(t)},setRate:e=>{Number.isFinite(e)&&Se.current?.setRate(e)},stepFrame:e=>{e!==1&&e!==-1||Se.current?.stepFrame(e)},goLive:()=>{Se.current?.dispose(),Se.current=null,we(!1),RK({type:`recState`,state:`live`})}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}},[t]),(0,S.useEffect)(()=>{RK({type:`micState`,state:E.micState})},[E.micState]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackEmbed;if(t)switch(e.kind){case`setMuted`:t.setMuted(e.value);break;case`setTarget`:t.setTarget(e.value);break;case`setStats`:t.setStats(e.value);break;case`setHighlight`:t.setHighlight(e.value);break;case`setSnapshot`:t.setSnapshot(e.value);break;case`setMic`:t.setMic(e.value);break;case`fit`:t.fit(e.w,e.h);break;case`reconnect`:t.reconnect();break;case`playRecorded`:t.playRecorded(e.deviceId,e.epochMs,e.profile);break;case`seek`:t.seek(e.epochMs??e.value);break;case`scrubCommit`:t.scrubCommit(e.epochMs??e.value);break;case`scrubStart`:t.scrubStart();break;case`scrubTo`:t.scrubTo(e.epochMs??e.value);break;case`scrubEnd`:t.scrubEnd(e.epochMs??e.value);break;case`setRate`:t.setRate(e.rate??e.value);break;case`stepFrame`:{let n=e.dir;(n===1||n===-1)&&t.stepFrame(n);break}case`goLive`:t.goLive();break;default:break}}),[]);let Ae=_Y(l);return(0,C.jsxs)(`div`,{style:{position:`fixed`,left:0,top:0,width:x.w,height:x.h,background:`#000`},children:[(0,C.jsx)(_K,{serverUrl:e.serverUrl,streamKey:Ae,autoPlay:!0,muted:d,showControls:!1,showStats:p,onPlaybackStats:e=>RK({type:`log`,scope:`playback`,msg:`stats`,data:e}),onConnectTiming:e=>RK({type:`log`,scope:`webrtc-timing`,msg:`connect`,data:e}),onClientNetworkSample:l.kind===`adaptive`?n=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...n}).catch(()=>{})}:void 0,className:`w-full h-full`,handleOffer:se,reoffer:k,getSessionState:ae,getIceServers:O,addIceCandidate:ne,getIceCandidates:re,closeSession:ie,reconnectSignal:y,posterUrl:_,onStateChange:e=>mY(hY(e)),onError:e=>mY(`error`,e)},Ae),(0,C.jsx)(`canvas`,{ref:A,style:{position:`absolute`,inset:0,width:`100%`,height:`100%`,background:`#000`,pointerEvents:`none`,transform:`translateZ(0)`,zIndex:2,display:Ce||ce&&ue?`block`:`none`}}),T&&(()=>{let e=h?.appearance,t=T===`motion`?e?.motionColor??Nq.motion:T===`audio`?e?.audioColor??Nq.audio:e?.detectionColor??Nq.detection;return(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,border:`${e?.thickness??3}px solid ${t}`,boxShadow:`inset 0 0 12px ${t}`,pointerEvents:`none`,transform:`translateZ(0)`}})})()]})}function xY(){let e=VK(`player`,()=>window.__CAMSTACK_EMBED__,vY),t=(0,S.useMemo)(()=>e===null||!e.ok?null:{system:XA({serverUrl:e.config.serverUrl,token:e.config.token}),queryClient:new hE({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}})},[e]);return(0,S.useEffect)(()=>{if(t)return()=>{t.system.close()}},[t]),e===null?null:e.ok?t?(0,C.jsx)(Az,{system:t.system,children:(0,C.jsx)(vE,{client:t.queryClient,children:(0,C.jsx)($.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:(0,C.jsx)(bY,{system:t.system,deviceId:e.config.deviceId,token:e.config.token,initialTarget:e.config.target,initialMuted:e.config.muted,initialStats:e.config.stats??!1,initialHighlight:e.config.highlight,initialSnapshot:e.config.snapshot})})})}):(0,C.jsx)(yY,{message:`Failed to initialise the embed player`}):(0,C.jsx)(yY,{message:e.error})}var SY=B({serverUrl:P().min(1),token:P().min(1),deviceId:F().int().nonnegative(),startMs:F().int().nonnegative().optional()});function CY(e){if(e==null)return{ok:!1,error:`config is required`};let t=SY.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function wY(e,t){let n=(e-t)/1e3;return Number.isFinite(n)&&n>0?n:0}var TY=360*60*1e3;function EY(e){RK(e)}function DY(e,t,n){try{RK({type:`log`,scope:e,msg:t,data:n})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,n??``)}catch{}}function OY({system:e,config:t}){let n=(0,S.useRef)(null),r=(0,S.useRef)(null),a=(0,S.useRef)(0),o=(0,S.useRef)(0),s=(0,S.useRef)(0),[c,l]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),[u,d]=(0,S.useState)(!1),f=(0,S.useRef)(!1),p=(0,S.useRef)(null),m=(0,S.useRef)(null),h=(0,S.useRef)(null),g=(0,S.useRef)(jJ()),_=(0,S.useRef)([]),v=(0,S.useRef)(null),y=(0,S.useMemo)(()=>async r=>{let c=n.current;if(!c)return;let l=++s.current;o.current=performance.now(),DY(`loadAt`,`start`,{epochMs:r,window:TY}),EY({type:`state`,state:`loading`});try{let n=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:r,toMs:r+TY});if(l!==s.current){DY(`loadAt`,`superseded`,{epochMs:r});return}if(DY(`loadAt`,`manifest`,{playbackUrl:n?.playbackUrl??null,endpoints:n?.playbackEndpoints?.length??0,localMaster:!!n?.localMasterPath}),!n?.playbackUrl){EY({type:`state`,state:`error`,message:`no footage`}),d(!1);return}c.src=n.playbackUrl;let o=()=>{if(l!==s.current)return;let e=typeof c.getStartDate==`function`?c.getStartDate():null,t=e instanceof Date&&!Number.isNaN(e.getTime())?e.getTime():r;a.current=t;let n=wY(r,t);if(n>0)try{c.currentTime=n}catch(e){DY(`loadAt`,`seek-failed`,{msg:String(e)})}c.play().catch(e=>{DY(`loadAt`,`play-rejected`,{msg:String(e)})}),DY(`loadAt`,`seek`,{epochMs:r,media0Ms:t,offsetSec:n})};c.readyState>=HTMLMediaElement.HAVE_METADATA?o():c.addEventListener(`loadedmetadata`,o,{once:!0}),DY(`loadAt`,`src-set`,{src:n.playbackUrl})}catch(e){DY(`loadAt`,`error`,{msg:e instanceof Error?e.message:String(e)}),EY({type:`state`,state:`error`,message:e instanceof Error?e.message:String(e)}),d(!1)}},[e,t.deviceId]),b=(0,S.useMemo)(()=>async n=>{let r=v.current;if(r&&n>=r.fromMs&&n<r.toMs&&_.current.length>0)return _.current;let a=new Date(n);a.setHours(0,0,0,0);let o=a.getTime(),s=o+1440*60*1e3,c=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:o,toMs:s});return DY(`scrub`,`dayIndex-manifest`,{playbackUrl:c?.playbackUrl??null,fromMs:o,toMs:s}),c?.playbackUrl?(_.current=await tJ(c.playbackUrl),v.current={fromMs:o,toMs:s},DY(`scrub`,`dayIndex-built`,{len:_.current.length,fromMs:o,toMs:s}),_.current):_.current},[e,t.deviceId]),x=(0,S.useMemo)(()=>e=>{let t=r.current,n=t?.getContext(`2d`);if(!t||!n)return;t.width=c.w,t.height=c.h;let a=`displayWidth`in e?e.displayWidth||e.codedWidth:e.width,o=`displayHeight`in e?e.displayHeight||e.codedHeight:e.height,s=Math.min(c.w/a,c.h/o),l=a*s,u=o*s;n.clearRect(0,0,c.w,c.h),n.drawImage(e,(c.w-l)/2,(c.h-u)/2,l,u)},[c.w,c.h]),w=(0,S.useRef)(x);w.current=x;let T=(0,S.useMemo)(()=>async e=>{if(h.current||=new AJ({deviceId:t.deviceId,draw:e=>w.current(e),onDrawn:()=>{g.current.fire()&&EY({type:`scrubDrawn`})},onDead:e=>DY(`scrub`,`pack tier failed — legacy tier takes over`,{msg:e instanceof Error?e.message:String(e)}),onTiming:e=>DY(`scrub`,`pack timing`,e)}),await h.current.scrubTo(e)===`drawn`){DY(`scrub`,`pack drawn`,{epochMs:e});return}p.current||=new _J,m.current||=new oJ({ensureIndex:e=>b(e),fetchBytes:async(e,t)=>{let n=await fetch(e,{signal:t});if(!n.ok)throw Error(`segment fetch failed: ${n.status}`);return n.arrayBuffer()},decode:e=>{let t=p.current;if(!t)throw Error(`decoder not initialised`);return t.decodeSegment(e)},decodeAt:(e,t)=>{let n=p.current;if(!n)throw Error(`decoder not initialised`);return n.decodeSegmentAt(e,t)},draw:e=>w.current(e),onTiming:e=>DY(`scrub`,`timing`,e)});let n=m.current;if(n)try{await n.scrubTo(e),DY(`scrub`,`drawn`,{epochMs:e}),g.current.fire()&&EY({type:`scrubDrawn`})}catch(e){DY(`scrub`,`error`,{msg:e instanceof Error?e.message:String(e)}),f.current||(f.current=!0,EY({type:`state`,state:`error`,message:`scrub: ${e instanceof Error?e.message:String(e)}`}))}},[b,t.deviceId]);return(0,S.useEffect)(()=>(DY(`init`,`mounted`,{deviceId:t.deviceId,startMs:t.startMs??null,hasWebCodecs:window.VideoDecoder!==void 0,ua:navigator.userAgent}),window.__camstackRecording={seekTo:e=>{DY(`cmd`,`seekTo`,{epochMs:e}),y(e)},play:()=>{DY(`cmd`,`play`),n.current?.play().catch(()=>{})},pause:()=>{DY(`cmd`,`pause`),n.current?.pause()},setRate:e=>{DY(`cmd`,`setRate`,{rate:e}),n.current&&(n.current.playbackRate=e)},fit:(e,t)=>{DY(`cmd`,`fit`,{w:e,h:t}),l({w:e,h:t})},scrubStart:()=>{DY(`cmd`,`scrubStart`),f.current=!1,g.current.reset(),d(!0);let e=n.current;e&&h.current?.armPrefetch(a.current+e.currentTime*1e3)},scrubTo:e=>{DY(`cmd`,`scrubTo`,{epochMs:e}),T(e)},scrubEnd:e=>{DY(`cmd`,`scrubEnd`,{epochMs:e}),m.current?.dispose(),m.current=null,y(e)}},t.startMs&&t.startMs>0&&y(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording,m.current?.dispose(),m.current=null,h.current?.dispose(),h.current=null,p.current?.close(),p.current=null}),[y,T,t.startMs,t.deviceId]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackRecording;if(t)switch(e.kind){case`seekTo`:t.seekTo(e.value);break;case`play`:t.play();break;case`pause`:t.pause();break;case`setRate`:t.setRate(e.value);break;case`scrubStart`:t.scrubStart();break;case`scrubTo`:t.scrubTo(e.value);break;case`scrubEnd`:t.scrubEnd(e.value);break;case`fit`:t.fit(e.w,e.h);break;default:break}}),[]),(0,C.jsxs)(`div`,{style:{position:`fixed`,left:0,top:0,width:c.w,height:c.h,background:`#000`},children:[(0,C.jsx)(`video`,{ref:n,playsInline:!0,controls:!1,style:{width:`100%`,height:`100%`,objectFit:`contain`,background:`#000`},onLoadedMetadata:e=>DY(`video`,`loadedmetadata`,{w:e.currentTarget.videoWidth,h:e.currentTarget.videoHeight,dur:e.currentTarget.duration}),onPlaying:()=>{DY(`video`,`playing`,{vodStartMs:Math.round(performance.now()-o.current)}),EY({type:`state`,state:`playing`}),d(!1)},onPause:()=>EY({type:`state`,state:`paused`}),onEnded:()=>EY({type:`state`,state:`ended`}),onError:e=>{let t=e.currentTarget.error;DY(`video`,`error`,{code:t?.code??null,message:t?.message??null}),EY({type:`state`,state:`error`,message:t?.message||`video error`}),d(!1)},onTimeUpdate:e=>EY({type:`position`,positionMs:a.current+e.currentTarget.currentTime*1e3})}),(0,C.jsx)(`canvas`,{ref:r,style:{position:`absolute`,left:0,top:0,width:`100%`,height:`100%`,background:`#000`,display:u?`block`:`none`}})]})}function kY(){let e=VK(`recording`,()=>window.__CAMSTACK_RECORDING__,CY),t=(0,S.useMemo)(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,XA({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return(0,S.useEffect)(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?(0,C.jsx)(OY,{system:t,config:e.config}):(EY({type:`state`,state:`error`,message:`init failed`}),null):(EY({type:`state`,state:`error`,message:e.error}),null)}function AY(){let e=new URLSearchParams(location.search).get(`mode`)??`grid`;return e===`player`?(0,C.jsx)(xY,{}):e===`recording`?(0,C.jsx)(kY,{}):(0,C.jsx)(Jq,{})}var jY=document.getElementById(`root`);jY&&(0,x.createRoot)(jY).render((0,C.jsx)(AY,{}));export{IG as a,Pz as c,b as d,m as f,u as g,c as h,IR as i,xK as l,s as m,kR as n,Q as o,f as p,XM as r,YM as s,jL as t,jz as u};
|
|
116
|
+
`).map(e=>e.trim())){if(!e||e.startsWith(`#`))continue;let t=new URL(e,o).toString(),n=WJ(t);n&&c.push({uri:t,startMs:n.startMs,durMs:n.durMs})}return c.sort((e,t)=>e.startMs-t.startMs),c}function JJ(e,t){if(e.length===0)return{kind:`gap`,nearestEdgeMs:null,prevEndMs:null};let n=null,r=null;for(let a of e){let e=a.startMs+a.durMs;if(t>=a.startMs&&t<e)return{kind:`segment`,seg:a};e<=t&&(n=n===null?e:Math.max(n,e)),a.startMs>t&&(r===null||a.startMs<r)&&(r=a.startMs)}if(r!==null&&n!==null&&r-n<=40&&t>=n&&t<r){let t=e.find(e=>e.startMs===r);if(t)return{kind:`segment`,seg:t}}return{kind:`gap`,nearestEdgeMs:r,prevEndMs:n}}var YJ={video:e=>new EncodedVideoChunk(e),audio:e=>new EncodedAudioChunk(e)};function XJ(e){return e.replace(/^hev1\./i,`hvc1.`)}function ZJ(e,t,n,r){return Math.round((e+(t-n)/r*1e3)*1e3)}function QJ(e,t){let n=e.getTrackById(t)?.mdia?.minf?.stbl?.stsd?.entries??[];for(let e of n){let t=e.hvcC??e.avcC;if(t){let e=new sJ.DataStream(void 0,0,sJ.DataStream.BIG_ENDIAN);return t.write(e),new Uint8Array(e.buffer,8)}}}function $J(e,t){return new Promise((n,r)=>{e.onError=e=>r(Error(`mp4box: ${e}`)),e.onReady=t=>{let a=t.videoTracks?.[0];if(!a){r(Error(`no video track`));return}let o=QJ(e,a.id),s={codec:XJ(a.codec),codedWidth:a.video?.width,codedHeight:a.video?.height,optimizeForLatency:!0,...o?{description:o}:{}},c=t.audioTracks?.[0],l=null,u=null;c&&(l=c.id,u={codec:c.codec,sampleRate:c.audio?.sample_rate??48e3,numberOfChannels:c.audio?.channel_count??1}),n({videoTrackId:a.id,videoConfig:s,audioTrackId:l,audioConfig:u})};let a=t;a.fileStart=0,e.appendBuffer(a),e.flush()})}async function eY(e,t,n,r=YJ){let a=await $J(e,t),o=[],s=[],c=null,l=null;e.onSamples=(e,t,u)=>{for(let t of u)e===a.videoTrackId?(c===null&&(c=t.cts),o.push(r.video({type:t.is_sync?`key`:`delta`,timestamp:ZJ(n,t.cts,c,t.timescale),data:t.data}))):a.audioTrackId!==null&&e===a.audioTrackId&&(l===null&&(l=t.cts),s.push(r.audio({type:`key`,timestamp:ZJ(n,t.cts,l,t.timescale),data:t.data})))},e.setExtractionOptions(a.videoTrackId,null,{nbSamples:1e5}),a.audioTrackId!==null&&e.setExtractionOptions(a.audioTrackId,null,{nbSamples:1e5});try{e.start()}catch{}let u=a.audioConfig&&s.length>0?{config:a.audioConfig,chunks:s}:null;return{video:{config:a.videoConfig,chunks:o},audio:u}}function tY(e,t){return eY(sJ.createFile(),e,t)}var nY=class{deps;decoder=null;config=null;factory;constructor(e){this.deps=e,this.factory=e.decoderFactory??(e=>new VideoDecoder(e))}ensureDecoder(){if(this.decoder&&this.decoder.state!==`closed`)return this.decoder;let e=this.factory({output:e=>{this.deps.ring.push({tsMs:e.timestamp/1e3,frame:e,close:()=>e.close()})},error:e=>this.deps.onError(e)});return this.decoder=e,this.config&&e.configure(this.config),e}configure(e){this.config=e;let t=this.ensureDecoder();t.state!==`closed`&&t.configure(e)}submit(e){this.ensureDecoder().decode(e)}get queueSize(){return this.decoder?.decodeQueueSize??0}async flush(){if(this.decoder&&this.decoder.state===`configured`)try{await this.decoder.flush()}catch(e){this.deps.onError(e)}}reset(){this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}close(){this.reset()}},rY=class{ctx=null;decoder=null;config=null;base=0;nextStartTime=0;sources=[];ensureCtx(){return this.ctx||=new AudioContext,this.ctx}configure(e){this.config=e}async resumeContext(){let e=this.ensureCtx();e.state===`suspended`&&await e.resume()}enqueue(e,t){if(!this.config||e.length===0)return;let n=this.ensureCtx();this.base=t,this.nextStartTime=n.currentTime,this.decoder&&this.decoder.state!==`closed`&&this.decoder.close();let r=new AudioDecoder({output:e=>this.scheduleAudioData(n,e),error:()=>{}});r.configure(this.config),this.decoder=r;for(let n of e)n.timestamp/1e3>=t&&r.decode(n)}scheduleAudioData(e,t){let n=t.numberOfFrames,r=t.numberOfChannels,a=t.sampleRate,o;try{o=e.createBuffer(r,n,a);for(let e=0;e<r;e++){let n=o.getChannelData(e);t.copyTo(n,{planeIndex:e,format:`f32-planar`})}}finally{t.close()}let s=e.createBufferSource();s.buffer=o,s.connect(e.destination);let c=Math.max(e.currentTime,this.nextStartTime);s.start(c),this.nextStartTime=c+o.duration,this.sources.push(s),s.onended=()=>{this.sources=this.sources.filter(e=>e!==s)}}audioNowSec(){return this.ctx?this.ctx.currentTime:0}baseEpochMs(){return this.base}stop(){for(let e of this.sources)try{e.stop()}catch{}this.sources=[],this.decoder&&this.decoder.state!==`closed`&&this.decoder.close(),this.decoder=null}close(){this.stop(),this.ctx&&this.ctx.close(),this.ctx=null}},iY=class{opts;frames=[];constructor(e){this.opts=e}get size(){return this.frames.length}push(e){let t=0,n=this.frames.length;for(;t<n;){let r=t+n>>1;this.frames[r].tsMs<e.tsMs?t=r+1:n=r}for(this.frames.splice(t,0,e);this.frames.length>this.opts.maxFrames;)this.frames.shift()?.close()}frameFor(e){let t=null;for(let n of this.frames)if(n.tsMs<=e)t=n;else break;return t}bufferedAheadMs(e){let t=this.frames[this.frames.length-1];return t?Math.max(0,t.tsMs-e):0}evictBehind(e){let t=e-this.opts.keepBehindMs;for(;this.frames.length>0&&this.frames[0].tsMs<t;)this.frames.shift().close()}clear(){for(let e of this.frames)e.close();this.frames=[]}},aY=class{now;baseEpochMs=0;wallAnchorMs=0;_rate=0;_paused=!0;mode=`video`;audioAnchorS=0;audioNow=null;constructor(e=()=>performance.now()){this.now=e}get rate(){return this._rate}get paused(){return this._paused}seekTo(e){this.baseEpochMs=e,this.wallAnchorMs=this.now(),this._paused=!0,this._rate=0,this.audioNow=null}play(e,t,n,r){this.baseEpochMs=t===`audio`&&n!==void 0?n:this.playheadMs(),this.wallAnchorMs=this.now(),this._rate=e,this._paused=!1,this.mode=t,t===`audio`&&r?(this.audioNow=r,this.audioAnchorS=r()):this.audioNow=null}pause(){this.baseEpochMs=this.playheadMs(),this._paused=!0,this._rate=0,this.audioNow=null}setRate(e,t){this.baseEpochMs=this.playheadMs(),this.wallAnchorMs=this.now(),this._rate=e,this._paused=e===0,this.mode=t,this.audioNow=null}playheadMs(){return this._paused?this.baseEpochMs:this.mode===`audio`&&this.audioNow?this.baseEpochMs+(this.audioNow()-this.audioAnchorS)*1e3:this.baseEpochMs+(this.now()-this.wallAnchorMs)*this._rate}},oY=90,sY=250,cY=6,lY=1440*60*1e3,uY=class{deps;engine=null;profile;desiredRate=1;index=[];indexWindow=null;bytes=new Yq(cY);ring=new iY({maxFrames:oY,keepBehindMs:sY});clock=new aY;constructor(e){this.deps=e,this.profile=`mid`}doFetch(){let e=this.deps.fetchImpl??fetch,t=this.deps.requestHeaders;return(n,r)=>{let a=new Headers(t);return r?.headers&&new Headers(r.headers).forEach((e,t)=>a.set(t,e)),e(n,{...r,credentials:`include`,headers:a})}}ensureIndex=async e=>{let t=this.engine?.getActiveProfile();t&&t!==this.profile&&(this.profile=t,this.indexWindow=null);let n=this.indexWindow;if(n&&e>=n.fromMs&&e<n.toMs&&this.index.length>0)return;let r=new Date(e);r.setHours(0,0,0,0);let a=r.getTime(),o=a+lY,s=await this.deps.getManifestUrl(a,o);if(!s){this.index=[],this.indexWindow=null;return}this.index=await qJ(s,this.profile,this.deps.requestHeaders,this.doFetch()),this.indexWindow={fromMs:a,toMs:o}};locate=e=>JJ(this.index,e);loadSegment=async(e,t)=>{let n=this.index.find(t=>t.startMs===e);if(!n)throw Error(`no segment at ${e}`);let r=this.bytes.get(n.uri);if(!r){let e=await this.doFetch()(n.uri,{signal:t});if(!e.ok)throw Error(`segment fetch failed: ${e.status}`);r=await e.arrayBuffer(),this.bytes.set(n.uri,r)}return(this.deps.demuxImpl??tY)(r,n.startMs)};buildEngine(){let e=this.deps.videoFactory??(e=>new nY(e)),t=null,n=e({ring:this.ring,onError:e=>t?.abortDead(e)}),r=this.deps.audioFactory??(()=>new rY),a=this.deps.hasAudio?r():null,o=new HJ({locate:this.locate,loadSegment:this.loadSegment,video:n,audio:a,ring:this.ring,clock:this.clock,draw:e=>this.deps.draw(e),onState:e=>this.deps.onState(e),onPosition:e=>this.deps.onPosition(e),now:()=>performance.now(),raf:this.deps.raf??(e=>{let t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)}),onDead:(e,t)=>this.deps.onDead(e,t),ensureIndex:this.ensureIndex,profile:this.profile,initialRate:this.desiredRate});return t=o,o}async playRecorded(e,t,n){this.engine&&n!==this.profile&&(this.engine.dispose(),this.engine=null),this.profile=n,this.indexWindow=null,this.engine||=this.buildEngine(),await this.engine.seek(t)}async seek(e){this.engine&&await this.engine.seek(e)}async commit(e){this.engine&&await this.engine.resumeFromScrub(e)}setRate(e){this.desiredRate=e,this.engine?.setRate(e)}stepFrame(e){this.engine?.stepFrame(e)}pauseForScrub(){this.engine?.pauseForScrub()}dispose(){this.engine?.dispose(),this.engine=null,this.ring.clear(),this.bytes.clear(),this.index=[],this.indexWindow=null}},dY=Co([B({kind:U(`adaptive`)}),B({kind:U(`profile`),profile:ps})]),fY=B({serverUrl:P().min(1),token:P().min(1),deviceId:F().int().nonnegative(),target:dY,muted:I(),stats:I().optional(),highlight:NK.optional(),snapshot:P().optional()});function pY(e,t){try{return new URL(t,e).toString()}catch{return t}}function mY(e,t){RK(t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t})}function hY(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function gY(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function _Y(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function vY(e){let t=fY.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function yY({message:e}){return(0,S.useEffect)(()=>{mY(`error`,e)},[e]),(0,C.jsxs)(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function bY({system:e,deviceId:t,token:n,initialTarget:r,initialMuted:a,initialStats:o,initialHighlight:s,initialSnapshot:c}){let[l,u]=(0,S.useState)(r),[d,f]=(0,S.useState)(a),[p,m]=(0,S.useState)(o),[h,g]=(0,S.useState)(s),[_,v]=(0,S.useState)(c),[y,b]=(0,S.useState)(0),[x,w]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),T=Mq(e,t,h),E=aq(),D=(0,S.useRef)(E.setActiveMic);D.current=E.setActiveMic;let ee=(0,S.useRef)(0),{handleOffer:te,getIceServers:O,addIceCandidate:ne,getIceCandidates:re,closeSession:ie,getSessionState:ae}=AK(e.trpcClient,t),oe=(0,S.useMemo)(()=>gY(l),[l]),se=(0,S.useMemo)(()=>(e,t,n)=>te(oe,e,t,n),[te,oe]),k=(0,S.useMemo)(()=>(e,t,n,r)=>te(n,t,e,r),[te]),A=(0,S.useRef)(null),[ce,le]=(0,S.useState)(!1),[ue,de]=(0,S.useState)(!1),j=(0,S.useRef)(null),M=(0,S.useRef)(null),fe=(0,S.useRef)(null),pe=(0,S.useRef)(jJ()),me=(0,S.useRef)([]),he=(0,S.useRef)(null),ge=(0,S.useRef)(!1),_e=(0,S.useMemo)(()=>({Authorization:`Bearer ${n}`}),[n]),N=(0,S.useMemo)(()=>async n=>{let r=he.current;if(r&&n>=r.fromMs&&n<r.toMs&&me.current.length>0)return me.current;let a=new Date(n);a.setHours(0,0,0,0);let o=a.getTime(),s=o+1440*60*1e3,c=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t,fromMs:o,toMs:s});return c?.playbackUrl?(me.current=await tJ(c.playbackUrl,_e),he.current={fromMs:o,toMs:s},me.current):me.current},[e,t,_e]),ve=(0,S.useMemo)(()=>e=>{let t=A.current,n=t?.getContext(`2d`);if(!t||!n)return;t.width=x.w,t.height=x.h;let r=`displayWidth`in e?e.displayWidth||e.codedWidth:typeof e.width==`number`?e.width:0,a=`displayHeight`in e?e.displayHeight||e.codedHeight:typeof e.height==`number`?e.height:0;if(r<=0||a<=0)return;let o=Math.min(x.w/r,x.h/a),s=r*o,c=a*o;n.clearRect(0,0,x.w,x.h),n.drawImage(e,(x.w-s)/2,(x.h-c)/2,s,c),de(!0)},[x.w,x.h]),ye=(0,S.useRef)(ve);ye.current=ve;let[be,xe]=(0,S.useState)(null),Se=(0,S.useRef)(null),[Ce,we]=(0,S.useState)(!1);(0,S.useEffect)(()=>{let e=!0;return(async()=>{let t=typeof VideoDecoder<`u`,n=await MJ({videoConfig:{codec:`hvc1.1.6.L120.B0`},hasVideoDecoder:t,hasAudioDecoder:typeof AudioDecoder<`u`,isVideoSupported:async e=>t?(await VideoDecoder.isConfigSupported(e)).supported===!0:!1});e&&xe(n.capability)})(),()=>{e=!1}},[]);let Te=(0,S.useCallback)(()=>{if(Se.current)return Se.current;let n=new uY({deviceId:t,requestHeaders:_e,getManifestUrl:async(n,r)=>{let a=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t,fromMs:n,toMs:r});return a?.playbackUrl?pY(e.serverUrl,a.playbackUrl):null},draw:e=>{e.frame&&ye.current(e.frame)},onState:e=>RK({type:`recState`,state:e}),onPosition:e=>{ee.current=e,RK({type:`position`,positionMs:e})},onDead:(e,t)=>{Se.current?.dispose(),Se.current=null,we(!1),RK({type:`log`,scope:`wc-playback`,msg:`tier dead — no recorded surface`,data:{epoch:e,cause:t instanceof Error?t.message:t}}),RK({type:`recState`,state:`error`})},hasAudio:be===`webcodecs-av`});return Se.current=n,n},[t,_e,e,be]),Ee=(0,S.useRef)(Te);Ee.current=Te;let De=(0,S.useRef)(be);De.current=be;let Oe=(0,S.useMemo)(()=>async e=>{if(fe.current||=new AJ({deviceId:t,requestHeaders:_e,draw:e=>ye.current(e),onDrawn:()=>{pe.current.fire()&&RK({type:`scrubDrawn`})},onDead:e=>RK({type:`log`,scope:`scrub`,msg:`pack tier dead — legacy tier takes over`,data:{msg:e instanceof Error?e.message:String(e)}}),onTiming:e=>RK({type:`log`,scope:`scrub`,msg:`pack timing`,data:e})}),await fe.current.scrubTo(e)!==`drawn`){j.current||=new _J,M.current||=new oJ({ensureIndex:e=>N(e),fetchBytes:async(e,t)=>{let n=await fetch(e,{signal:t,headers:_e});if(!n.ok)throw Error(`segment fetch failed: ${n.status}`);return n.arrayBuffer()},decode:e=>{let t=j.current;if(!t)throw Error(`decoder not initialised`);return t.decodeSegment(e)},decodeAt:(e,t)=>{let n=j.current;if(!n)throw Error(`decoder not initialised`);return n.decodeSegmentAt(e,t)},draw:e=>ye.current(e)});try{await M.current.scrubTo(e)}catch(e){lJ(e)&&!ge.current&&(ge.current=!0,RK({type:`log`,scope:`scrub`,msg:`webcodecs-unsupported`,data:{codec:e.codec}}))}}},[N,_e,t]),ke=(0,S.useRef)(Oe);ke.current=Oe,(0,S.useEffect)(()=>()=>{M.current?.dispose(),fe.current?.dispose(),Se.current?.dispose()},[]),(0,S.useEffect)(()=>{let e=e=>{le(!1);let n=Se.current;if(n){n.commit(e);return}if(De.current===`unavailable`){RK({type:`recState`,state:`error`});return}we(!0),Ee.current().playRecorded(t,e,`mid`)};return window.__camstackEmbed={setMuted:e=>f(e),setTarget:e=>{let t=dY.safeParse(e);t.success&&u(t.data)},setStats:e=>m(e),setHighlight:e=>g(e),setSnapshot:e=>v(e),setMic:e=>D.current(e?t:null),fit:(e,t)=>w({w:e,h:t}),reconnect:()=>b(e=>e+1),playRecorded:(e,t,n)=>{if(De.current===`unavailable`){RK({type:`log`,scope:`recorded:engine`,msg:`webcodecs-unavailable`,data:{capability:De.current}}),RK({type:`recState`,state:`error`});return}we(!0),Ee.current().playRecorded(e,t,n)},seek:e=>{Number.isFinite(e)&&Se.current?.seek(e)},scrubCommit:t=>{Number.isFinite(t)&&e(t)},scrubStart:()=>{RK({type:`log`,scope:`recorded:scrub`,msg:`pack`,data:{route:`pack`}}),Se.current?.pauseForScrub(),de(!1),pe.current.reset(),le(!0),ee.current>0&&fe.current?.armPrefetch(ee.current)},scrubTo:e=>{Number.isFinite(e)&&ke.current(e)},scrubEnd:t=>{Number.isFinite(t)&&e(t)},setRate:e=>{Number.isFinite(e)&&Se.current?.setRate(e)},stepFrame:e=>{e!==1&&e!==-1||Se.current?.stepFrame(e)},goLive:()=>{Se.current?.dispose(),Se.current=null,we(!1),RK({type:`recState`,state:`live`})}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}},[t]),(0,S.useEffect)(()=>{RK({type:`micState`,state:E.micState})},[E.micState]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackEmbed;if(t)switch(e.kind){case`setMuted`:t.setMuted(e.value);break;case`setTarget`:t.setTarget(e.value);break;case`setStats`:t.setStats(e.value);break;case`setHighlight`:t.setHighlight(e.value);break;case`setSnapshot`:t.setSnapshot(e.value);break;case`setMic`:t.setMic(e.value);break;case`fit`:t.fit(e.w,e.h);break;case`reconnect`:t.reconnect();break;case`playRecorded`:t.playRecorded(e.deviceId,e.epochMs,e.profile);break;case`seek`:t.seek(e.epochMs??e.value);break;case`scrubCommit`:t.scrubCommit(e.epochMs??e.value);break;case`scrubStart`:t.scrubStart();break;case`scrubTo`:t.scrubTo(e.epochMs??e.value);break;case`scrubEnd`:t.scrubEnd(e.epochMs??e.value);break;case`setRate`:t.setRate(e.rate??e.value);break;case`stepFrame`:{let n=e.dir;(n===1||n===-1)&&t.stepFrame(n);break}case`goLive`:t.goLive();break;default:break}}),[]);let Ae=_Y(l);return(0,C.jsxs)(`div`,{style:{position:`fixed`,left:0,top:0,width:x.w,height:x.h,background:`#000`},children:[(0,C.jsx)(_K,{serverUrl:e.serverUrl,streamKey:Ae,autoPlay:!0,muted:d,showControls:!1,showStats:p,onPlaybackStats:e=>RK({type:`log`,scope:`playback`,msg:`stats`,data:e}),onConnectTiming:e=>RK({type:`log`,scope:`webrtc-timing`,msg:`connect`,data:e}),onClientNetworkSample:l.kind===`adaptive`?n=>{e.trpcClient.networkQuality.reportClientStats.mutate({deviceId:t,...n}).catch(()=>{})}:void 0,className:`w-full h-full`,handleOffer:se,reoffer:k,getSessionState:ae,getIceServers:O,addIceCandidate:ne,getIceCandidates:re,closeSession:ie,reconnectSignal:y,posterUrl:_,onStateChange:e=>mY(hY(e)),onError:e=>mY(`error`,e)},Ae),(0,C.jsx)(`canvas`,{ref:A,style:{position:`absolute`,inset:0,width:`100%`,height:`100%`,background:`#000`,pointerEvents:`none`,transform:`translateZ(0)`,zIndex:2,display:Ce||ce&&ue?`block`:`none`}}),T&&(()=>{let e=h?.appearance,t=T===`motion`?e?.motionColor??Nq.motion:T===`audio`?e?.audioColor??Nq.audio:e?.detectionColor??Nq.detection;return(0,C.jsx)(`div`,{style:{position:`absolute`,inset:0,border:`${e?.thickness??3}px solid ${t}`,boxShadow:`inset 0 0 12px ${t}`,pointerEvents:`none`,transform:`translateZ(0)`}})})()]})}function xY(){let e=VK(`player`,()=>window.__CAMSTACK_EMBED__,vY),t=(0,S.useMemo)(()=>e===null||!e.ok?null:{system:XA({serverUrl:e.config.serverUrl,token:e.config.token}),queryClient:new hE({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}})},[e]);return(0,S.useEffect)(()=>{if(t)return()=>{t.system.close()}},[t]),e===null?null:e.ok?t?(0,C.jsx)(Az,{system:t.system,children:(0,C.jsx)(vE,{client:t.queryClient,children:(0,C.jsx)($.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:(0,C.jsx)(bY,{system:t.system,deviceId:e.config.deviceId,token:e.config.token,initialTarget:e.config.target,initialMuted:e.config.muted,initialStats:e.config.stats??!1,initialHighlight:e.config.highlight,initialSnapshot:e.config.snapshot})})})}):(0,C.jsx)(yY,{message:`Failed to initialise the embed player`}):(0,C.jsx)(yY,{message:e.error})}var SY=B({serverUrl:P().min(1),token:P().min(1),deviceId:F().int().nonnegative(),startMs:F().int().nonnegative().optional()});function CY(e){if(e==null)return{ok:!1,error:`config is required`};let t=SY.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function wY(e,t){let n=(e-t)/1e3;return Number.isFinite(n)&&n>0?n:0}var TY=360*60*1e3;function EY(e){RK(e)}function DY(e,t,n){try{RK({type:`log`,scope:e,msg:t,data:n})}catch{}try{console.debug(`[rec-embed:${e}] ${t}`,n??``)}catch{}}function OY({system:e,config:t}){let n=(0,S.useRef)(null),r=(0,S.useRef)(null),a=(0,S.useRef)(0),o=(0,S.useRef)(0),s=(0,S.useRef)(0),[c,l]=(0,S.useState)({w:window.innerWidth,h:window.innerHeight}),[u,d]=(0,S.useState)(!1),f=(0,S.useRef)(!1),p=(0,S.useRef)(null),m=(0,S.useRef)(null),h=(0,S.useRef)(null),g=(0,S.useRef)(jJ()),_=(0,S.useRef)([]),v=(0,S.useRef)(null),y=(0,S.useMemo)(()=>async r=>{let c=n.current;if(!c)return;let l=++s.current;o.current=performance.now(),DY(`loadAt`,`start`,{epochMs:r,window:TY}),EY({type:`state`,state:`loading`});try{let n=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:r,toMs:r+TY});if(l!==s.current){DY(`loadAt`,`superseded`,{epochMs:r});return}if(DY(`loadAt`,`manifest`,{playbackUrl:n?.playbackUrl??null,endpoints:n?.playbackEndpoints?.length??0,localMaster:!!n?.localMasterPath}),!n?.playbackUrl){EY({type:`state`,state:`error`,message:`no footage`}),d(!1);return}c.src=n.playbackUrl;let o=()=>{if(l!==s.current)return;let e=typeof c.getStartDate==`function`?c.getStartDate():null,t=e instanceof Date&&!Number.isNaN(e.getTime())?e.getTime():r;a.current=t;let n=wY(r,t);if(n>0)try{c.currentTime=n}catch(e){DY(`loadAt`,`seek-failed`,{msg:String(e)})}c.play().catch(e=>{DY(`loadAt`,`play-rejected`,{msg:String(e)})}),DY(`loadAt`,`seek`,{epochMs:r,media0Ms:t,offsetSec:n})};c.readyState>=HTMLMediaElement.HAVE_METADATA?o():c.addEventListener(`loadedmetadata`,o,{once:!0}),DY(`loadAt`,`src-set`,{src:n.playbackUrl})}catch(e){DY(`loadAt`,`error`,{msg:e instanceof Error?e.message:String(e)}),EY({type:`state`,state:`error`,message:e instanceof Error?e.message:String(e)}),d(!1)}},[e,t.deviceId]),b=(0,S.useMemo)(()=>async n=>{let r=v.current;if(r&&n>=r.fromMs&&n<r.toMs&&_.current.length>0)return _.current;let a=new Date(n);a.setHours(0,0,0,0);let o=a.getTime(),s=o+1440*60*1e3,c=await e.trpcClient.recording.getPlaybackManifest.query({deviceId:t.deviceId,fromMs:o,toMs:s});return DY(`scrub`,`dayIndex-manifest`,{playbackUrl:c?.playbackUrl??null,fromMs:o,toMs:s}),c?.playbackUrl?(_.current=await tJ(c.playbackUrl),v.current={fromMs:o,toMs:s},DY(`scrub`,`dayIndex-built`,{len:_.current.length,fromMs:o,toMs:s}),_.current):_.current},[e,t.deviceId]),x=(0,S.useMemo)(()=>e=>{let t=r.current,n=t?.getContext(`2d`);if(!t||!n)return;t.width=c.w,t.height=c.h;let a=`displayWidth`in e?e.displayWidth||e.codedWidth:e.width,o=`displayHeight`in e?e.displayHeight||e.codedHeight:e.height,s=Math.min(c.w/a,c.h/o),l=a*s,u=o*s;n.clearRect(0,0,c.w,c.h),n.drawImage(e,(c.w-l)/2,(c.h-u)/2,l,u)},[c.w,c.h]),w=(0,S.useRef)(x);w.current=x;let T=(0,S.useMemo)(()=>async e=>{if(h.current||=new AJ({deviceId:t.deviceId,draw:e=>w.current(e),onDrawn:()=>{g.current.fire()&&EY({type:`scrubDrawn`})},onDead:e=>DY(`scrub`,`pack tier failed — legacy tier takes over`,{msg:e instanceof Error?e.message:String(e)}),onTiming:e=>DY(`scrub`,`pack timing`,e)}),await h.current.scrubTo(e)===`drawn`){DY(`scrub`,`pack drawn`,{epochMs:e});return}p.current||=new _J,m.current||=new oJ({ensureIndex:e=>b(e),fetchBytes:async(e,t)=>{let n=await fetch(e,{signal:t});if(!n.ok)throw Error(`segment fetch failed: ${n.status}`);return n.arrayBuffer()},decode:e=>{let t=p.current;if(!t)throw Error(`decoder not initialised`);return t.decodeSegment(e)},decodeAt:(e,t)=>{let n=p.current;if(!n)throw Error(`decoder not initialised`);return n.decodeSegmentAt(e,t)},draw:e=>w.current(e),onTiming:e=>DY(`scrub`,`timing`,e)});let n=m.current;if(n)try{await n.scrubTo(e),DY(`scrub`,`drawn`,{epochMs:e}),g.current.fire()&&EY({type:`scrubDrawn`})}catch(e){DY(`scrub`,`error`,{msg:e instanceof Error?e.message:String(e)}),f.current||(f.current=!0,EY({type:`state`,state:`error`,message:`scrub: ${e instanceof Error?e.message:String(e)}`}))}},[b,t.deviceId]);return(0,S.useEffect)(()=>(DY(`init`,`mounted`,{deviceId:t.deviceId,startMs:t.startMs??null,hasWebCodecs:window.VideoDecoder!==void 0,ua:navigator.userAgent}),window.__camstackRecording={seekTo:e=>{DY(`cmd`,`seekTo`,{epochMs:e}),y(e)},play:()=>{DY(`cmd`,`play`),n.current?.play().catch(()=>{})},pause:()=>{DY(`cmd`,`pause`),n.current?.pause()},setRate:e=>{DY(`cmd`,`setRate`,{rate:e}),n.current&&(n.current.playbackRate=e)},fit:(e,t)=>{DY(`cmd`,`fit`,{w:e,h:t}),l({w:e,h:t})},scrubStart:()=>{DY(`cmd`,`scrubStart`),f.current=!1,g.current.reset(),d(!0);let e=n.current;e&&h.current?.armPrefetch(a.current+e.currentTime*1e3)},scrubTo:e=>{DY(`cmd`,`scrubTo`,{epochMs:e}),T(e)},scrubEnd:e=>{DY(`cmd`,`scrubEnd`,{epochMs:e}),m.current?.dispose(),m.current=null,y(e)}},t.startMs&&t.startMs>0&&y(t.startMs),()=>{window.__camstackRecording&&delete window.__camstackRecording,m.current?.dispose(),m.current=null,h.current?.dispose(),h.current=null,p.current?.close(),p.current=null}),[y,T,t.startMs,t.deviceId]),(0,S.useEffect)(()=>zK(e=>{let t=window.__camstackRecording;if(t)switch(e.kind){case`seekTo`:t.seekTo(e.value);break;case`play`:t.play();break;case`pause`:t.pause();break;case`setRate`:t.setRate(e.value);break;case`scrubStart`:t.scrubStart();break;case`scrubTo`:t.scrubTo(e.value);break;case`scrubEnd`:t.scrubEnd(e.value);break;case`fit`:t.fit(e.w,e.h);break;default:break}}),[]),(0,C.jsxs)(`div`,{style:{position:`fixed`,left:0,top:0,width:c.w,height:c.h,background:`#000`},children:[(0,C.jsx)(`video`,{ref:n,playsInline:!0,controls:!1,style:{width:`100%`,height:`100%`,objectFit:`contain`,background:`#000`},onLoadedMetadata:e=>DY(`video`,`loadedmetadata`,{w:e.currentTarget.videoWidth,h:e.currentTarget.videoHeight,dur:e.currentTarget.duration}),onPlaying:()=>{DY(`video`,`playing`,{vodStartMs:Math.round(performance.now()-o.current)}),EY({type:`state`,state:`playing`}),d(!1)},onPause:()=>EY({type:`state`,state:`paused`}),onEnded:()=>EY({type:`state`,state:`ended`}),onError:e=>{let t=e.currentTarget.error;DY(`video`,`error`,{code:t?.code??null,message:t?.message??null}),EY({type:`state`,state:`error`,message:t?.message||`video error`}),d(!1)},onTimeUpdate:e=>EY({type:`position`,positionMs:a.current+e.currentTarget.currentTime*1e3})}),(0,C.jsx)(`canvas`,{ref:r,style:{position:`absolute`,left:0,top:0,width:`100%`,height:`100%`,background:`#000`,display:u?`block`:`none`}})]})}function kY(){let e=VK(`recording`,()=>window.__CAMSTACK_RECORDING__,CY),t=(0,S.useMemo)(()=>e===null||!e.ok?null:(document.cookie=`camstack_session=${e.config.token}; path=/; SameSite=Lax`,XA({serverUrl:e.config.serverUrl,token:e.config.token})),[e]);return(0,S.useEffect)(()=>()=>t?.close(),[t]),e===null?null:e.ok?t?(0,C.jsx)(OY,{system:t,config:e.config}):(EY({type:`state`,state:`error`,message:`init failed`}),null):(EY({type:`state`,state:`error`,message:e.error}),null)}function AY(){let e=new URLSearchParams(location.search).get(`mode`)??`grid`;return e===`player`?(0,C.jsx)(xY,{}):e===`recording`?(0,C.jsx)(kY,{}):(0,C.jsx)(Jq,{})}var jY=document.getElementById(`root`);jY&&(0,x.createRoot)(jY).render((0,C.jsx)(AY,{}));export{IG as a,Pz as c,b as d,m as f,u as g,c as h,IR as i,xK as l,s as m,kR as n,Q as o,f as p,XM as r,YM as s,jL as t,jz as u};
|