demoman 0.9.2 → 0.9.3
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/README.md +2 -2
- package/THIRD_PARTY_NOTICES +1 -1
- package/dist/demoman.mjs +1550 -1052
- package/dist/page/mux-entry.js +40 -34
- package/dist/page/render-entry.js +58 -35
- package/dist/recipe.md +7 -7
- package/dist/studio/assets/editor-B0QH2SX6.js +4 -0
- package/dist/studio/assets/{editor-inline-07bcb316.css → editor-inline-61caf545.css} +47 -14
- package/dist/studio/assets/library-5-DKU9o1.js +1 -0
- package/dist/studio/assets/settings-DEDyzRMN.js +1 -0
- package/dist/studio/assets/state-BoH98Hy3.js +2 -0
- package/dist/studio/assets/toast-B_KSsgnJ.js +72 -0
- package/dist/studio/assets/toast-DoOgSxra.css +1 -0
- package/dist/studio/assets/view-DWP5EfCT.js +1 -0
- package/dist/studio/editor.html +6 -6
- package/dist/studio/library.html +4 -4
- package/dist/studio/settings.html +4 -4
- package/dist/studio/studio-build.json +3 -3
- package/package.json +1 -1
- package/dist/studio/assets/editor-BqUFP4jc.js +0 -4
- package/dist/studio/assets/library-BDaeqF3R.js +0 -1
- package/dist/studio/assets/settings-Dk_TSyaG.js +0 -1
- package/dist/studio/assets/state-CwX0hAy0.js +0 -2
- package/dist/studio/assets/toast-DV2oi8vF.css +0 -1
- package/dist/studio/assets/toast-DdGXRXQH.js +0 -72
- package/dist/studio/assets/view-B4EKYrze.js +0 -1
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l;function u(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var d=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},f=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(l=globalThis).__zod_globalConfig??(l.__zod_globalConfig={});var p=globalThis.__zod_globalConfig;function m(e){return e&&Object.assign(p,e),p}function h(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function g(e,t){return typeof t==`bigint`?t.toString():t}function _(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function v(e){return e==null}function y(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function b(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var x=Symbol(`evaluating`);function S(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==x)return r===void 0&&(r=x,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function C(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function w(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function T(e){return JSON.stringify(e)}function ee(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var te=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function E(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ne=_(()=>{if(p.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function D(e){if(E(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return E(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function re(e){return D(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var ie=new Set([`string`,`number`,`symbol`]);function ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function oe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function O(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function se(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var ce={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function le(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return oe(e,w(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return C(this,`shape`,e),e},checks:[]}))}function ue(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return oe(e,w(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return C(this,`shape`,r),r},checks:[]}))}function de(e,t){if(!D(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return oe(e,w(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return C(this,`shape`,n),n}}))}function fe(e,t){if(!D(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return oe(e,w(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return C(this,`shape`,n),n}}))}function pe(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return oe(e,w(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return C(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function me(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return oe(t,w(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return C(this,`shape`,i),i},checks:[]}))}function he(e,t,n){return oe(t,w(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return C(this,`shape`,i),i}}))}function ge(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function _e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ve(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ye(e){return typeof e==`string`?e:e?.message}function be(e,t,n){let r=e.message?e.message:ye(e.inst?._zod.def?.error?.(e))??ye(t?.error?.(e))??ye(n.customError?.(e))??ye(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function xe(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Se(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var Ce=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,g,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},we=u(`$ZodError`,Ce),Te=u(`$ZodError`,Ce,{Parent:Error});function Ee(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function De(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}var Oe=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new d;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>be(e,a,m())));throw te(t,i?.callee),t}return o.value},ke=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>be(e,a,m())));throw te(t,i?.callee),t}return o.value},Ae=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new d;return a.issues.length?{success:!1,error:new(e??we)(a.issues.map(e=>be(e,i,m())))}:{success:!0,data:a.value}},je=Ae(Te),Me=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>be(e,i,m())))}:{success:!0,data:a.value}},Ne=Me(Te),Pe=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Oe(e)(t,n,i)},Fe=e=>(t,n,r)=>Oe(e)(t,n,r),Ie=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ke(e)(t,n,i)},Le=e=>async(t,n,r)=>ke(e)(t,n,r),Re=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ae(e)(t,n,i)},ze=e=>(t,n,r)=>Ae(e)(t,n,r),Be=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Me(e)(t,n,i)},Ve=e=>async(t,n,r)=>Me(e)(t,n,r),He=/^[cC][0-9a-z]{6,}$/,Ue=/^[0-9a-z]+$/,We=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ge=/^[0-9a-vA-V]{20}$/,Ke=/^[A-Za-z0-9]{27}$/,qe=/^[a-zA-Z0-9_-]{21}$/,Je=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ye=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xe=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ze=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Qe=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function $e(){return new RegExp(Qe,`u`)}var et=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,tt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,nt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,rt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,it=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,at=/^[A-Za-z0-9_-]*$/,ot=/^https?$/,st=/^\+[1-9]\d{6,14}$/,ct=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,lt=RegExp(`^${ct}$`);function ut(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function dt(e){return RegExp(`^${ut(e)}$`)}function ft(e){let t=ut({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${ct}T(?:${r})$`)}var pt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},mt=/^-?\d+$/,ht=/^-?\d+(?:\.\d+)?$/,gt=/^(?:true|false)$/i,_t=/^null$/i,vt=/^[^A-Z]*$/,yt=/^[^a-z]*$/,bt=u(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xt={number:`number`,bigint:`bigint`,object:`date`},St=u(`$ZodCheckLessThan`,(e,t)=>{bt.init(e,t);let n=xt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ct=u(`$ZodCheckGreaterThan`,(e,t)=>{bt.init(e,t);let n=xt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wt=u(`$ZodCheckMultipleOf`,(e,t)=>{bt.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):b(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Tt=u(`$ZodCheckNumberFormat`,(e,t)=>{bt.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ce[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=mt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Et=u(`$ZodCheckMaxLength`,(e,t)=>{var n;bt.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!v(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=xe(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dt=u(`$ZodCheckMinLength`,(e,t)=>{var n;bt.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!v(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=xe(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ot=u(`$ZodCheckLengthEquals`,(e,t)=>{var n;bt.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!v(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=xe(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),kt=u(`$ZodCheckStringFormat`,(e,t)=>{var n,r;bt.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),At=u(`$ZodCheckRegex`,(e,t)=>{kt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),jt=u(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=vt,kt.init(e,t)}),Mt=u(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=yt,kt.init(e,t)}),Nt=u(`$ZodCheckIncludes`,(e,t)=>{bt.init(e,t);let n=ae(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Pt=u(`$ZodCheckStartsWith`,(e,t)=>{bt.init(e,t);let n=RegExp(`^${ae(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ft=u(`$ZodCheckEndsWith`,(e,t)=>{bt.init(e,t);let n=RegExp(`.*${ae(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),It=u(`$ZodCheckOverwrite`,(e,t)=>{bt.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Lt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
2
|
-
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
3
|
-
`))}},Rt={major:4,minor:4,patch:3},k=u(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Rt;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ge(e),i;for(let a of t){if(a._zod.def.when){if(_e(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new d;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ge(e,t))});else{if(e.issues.length===t)continue;r||=ge(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ge(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new d;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new d;return o.then(e=>t(e,r,a))}return t(o,r,a)}}S(e,`~standard`,()=>({validate:t=>{try{let n=je(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ne(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),zt=u(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??pt(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),A=u(`$ZodStringFormat`,(e,t)=>{kt.init(e,t),zt.init(e,t)}),Bt=u(`$ZodGUID`,(e,t)=>{t.pattern??=Ye,A.init(e,t)}),Vt=u(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Xe(e)}else t.pattern??=Xe();A.init(e,t)}),Ht=u(`$ZodEmail`,(e,t)=>{t.pattern??=Ze,A.init(e,t)}),Ut=u(`$ZodURL`,(e,t)=>{A.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===ot.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Wt=u(`$ZodEmoji`,(e,t)=>{t.pattern??=$e(),A.init(e,t)}),Gt=u(`$ZodNanoID`,(e,t)=>{t.pattern??=qe,A.init(e,t)}),Kt=u(`$ZodCUID`,(e,t)=>{t.pattern??=He,A.init(e,t)}),qt=u(`$ZodCUID2`,(e,t)=>{t.pattern??=Ue,A.init(e,t)}),Jt=u(`$ZodULID`,(e,t)=>{t.pattern??=We,A.init(e,t)}),Yt=u(`$ZodXID`,(e,t)=>{t.pattern??=Ge,A.init(e,t)}),Xt=u(`$ZodKSUID`,(e,t)=>{t.pattern??=Ke,A.init(e,t)}),Zt=u(`$ZodISODateTime`,(e,t)=>{t.pattern??=ft(t),A.init(e,t)}),Qt=u(`$ZodISODate`,(e,t)=>{t.pattern??=lt,A.init(e,t)}),$t=u(`$ZodISOTime`,(e,t)=>{t.pattern??=dt(t),A.init(e,t)}),en=u(`$ZodISODuration`,(e,t)=>{t.pattern??=Je,A.init(e,t)}),tn=u(`$ZodIPv4`,(e,t)=>{t.pattern??=et,A.init(e,t),e._zod.bag.format=`ipv4`}),nn=u(`$ZodIPv6`,(e,t)=>{t.pattern??=tt,A.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),rn=u(`$ZodCIDRv4`,(e,t)=>{t.pattern??=nt,A.init(e,t)}),an=u(`$ZodCIDRv6`,(e,t)=>{t.pattern??=rt,A.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function on(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var sn=u(`$ZodBase64`,(e,t)=>{t.pattern??=it,A.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{on(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function cn(e){if(!at.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return on(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var ln=u(`$ZodBase64URL`,(e,t)=>{t.pattern??=at,A.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{cn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),un=u(`$ZodE164`,(e,t)=>{t.pattern??=st,A.init(e,t)});function dn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var fn=u(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{dn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),pn=u(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??ht,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),mn=u(`$ZodNumberFormat`,(e,t)=>{Tt.init(e,t),pn.init(e,t)}),hn=u(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=gt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),gn=u(`$ZodNull`,(e,t)=>{k.init(e,t),e._zod.pattern=_t,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),_n=u(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),vn=u(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function yn(e,t,n){e.issues.length&&t.issues.push(...ve(n,e.issues)),t.value[n]=e.value}var bn=u(`$ZodArray`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>yn(t,n,e))):yn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function xn(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...ve(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Sn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=se(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Cn(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>xn(e,n,i,t,u,d))):xn(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var wn=u(`$ZodObject`,(e,t)=>{if(k.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=_(()=>Sn(t));S(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=E,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>xn(n,t,e,s,r,i))):xn(a,t,e,s,r,i)}return i?Cn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Tn=u(`$ZodObjectJIT`,(e,t)=>{wn.init(e,t);let n=e._zod.parse,r=_(()=>Sn(t)),i=e=>{let t=new Lt([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=T(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=T(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
4
|
-
if (${n}.issues.length) {
|
|
5
|
-
if (${o} in input) {
|
|
6
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
7
|
-
...iss,
|
|
8
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
9
|
-
})));
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
if (${n}.value === undefined) {
|
|
14
|
-
if (${o} in input) {
|
|
15
|
-
newResult[${o}] = undefined;
|
|
16
|
-
}
|
|
17
|
-
} else {
|
|
18
|
-
newResult[${o}] = ${n}.value;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
`):c?t.write(`
|
|
22
|
-
if (${n}.issues.length) {
|
|
23
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
24
|
-
...iss,
|
|
25
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
26
|
-
})));
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
if (${n}.value === undefined) {
|
|
30
|
-
if (${o} in input) {
|
|
31
|
-
newResult[${o}] = undefined;
|
|
32
|
-
}
|
|
33
|
-
} else {
|
|
34
|
-
newResult[${o}] = ${n}.value;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
`):t.write(`
|
|
38
|
-
const ${n}_present = ${o} in input;
|
|
39
|
-
if (${n}.issues.length) {
|
|
40
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
41
|
-
...iss,
|
|
42
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
43
|
-
})));
|
|
44
|
-
}
|
|
45
|
-
if (!${n}_present && !${n}.issues.length) {
|
|
46
|
-
payload.issues.push({
|
|
47
|
-
code: "invalid_type",
|
|
48
|
-
expected: "nonoptional",
|
|
49
|
-
input: undefined,
|
|
50
|
-
path: [${o}]
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
if (${n}_present) {
|
|
55
|
-
if (${n}.value === undefined) {
|
|
56
|
-
newResult[${o}] = undefined;
|
|
57
|
-
} else {
|
|
58
|
-
newResult[${o}] = ${n}.value;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=E,s=!p.jitless,c=s&&ne.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Cn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function En(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ge(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>be(e,r,m())))}),t)}var Dn=u(`$ZodUnion`,(e,t)=>{k.init(e,t),S(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),S(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),S(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),S(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>y(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>En(t,r,e,i)):En(o,r,e,i)}}),On=u(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Dn.init(e,t);let n=e._zod.parse;S(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=_(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!E(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),kn=u(`$ZodIntersection`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>jn(e,t,n)):jn(e,i,a)}});function An(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(D(e)&&D(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=An(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=An(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function jn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ge(e))return e;let o=An(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Mn=u(`$ZodEnum`,(e,t)=>{k.init(e,t);let n=h(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ie.has(typeof e)).map(e=>typeof e==`string`?ae(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Nn=u(`$ZodLiteral`,(e,t)=>{if(k.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ae(e):e?ae(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Pn=u(`$ZodTransform`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new f(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new d;return n.value=i,n.fallback=!0,n}});function Fn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var In=u(`$ZodOptional`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${y(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Fn(e,r)):Fn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Ln=u(`$ZodExactOptional`,(e,t)=>{In.init(e,t),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Rn=u(`$ZodNullable`,(e,t)=>{k.init(e,t),S(e._zod,`optin`,()=>t.innerType._zod.optin),S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${y(e.source)}|null)$`):void 0}),S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),zn=u(`$ZodDefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Bn(e,t)):Bn(r,t)}});function Bn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Vn=u(`$ZodPrefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Hn=u(`$ZodNonOptional`,(e,t)=>{k.init(e,t),S(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Un(t,e)):Un(i,e)}});function Un(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Wn=u(`$ZodCatch`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>be(e,n,m()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>be(e,n,m()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Gn=u(`$ZodPipe`,(e,t)=>{k.init(e,t),S(e._zod,`values`,()=>t.in._zod.values),S(e._zod,`optin`,()=>t.in._zod.optin),S(e._zod,`optout`,()=>t.out._zod.optout),S(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Kn(e,t.in,n)):Kn(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Kn(e,t.out,n)):Kn(r,t.out,n)}});function Kn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var qn=u(`$ZodPreprocess`,(e,t)=>{Gn.init(e,t)}),Jn=u(`$ZodReadonly`,(e,t)=>{k.init(e,t),S(e._zod,`propValues`,()=>t.innerType._zod.propValues),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`optin`,()=>t.innerType?._zod?.optin),S(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Yn):Yn(r)}});function Yn(e){return e.value=Object.freeze(e.value),e}var Xn=u(`$ZodCustom`,(e,t)=>{bt.init(e,t),k.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Zn(t,n,r,e));Zn(i,n,r,e)}});function Zn(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Se(e))}}var Qn,$n=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function er(){return new $n}(Qn=globalThis).__zod_globalRegistry??(Qn.__zod_globalRegistry=er());var tr=globalThis.__zod_globalRegistry;function nr(e,t){return new e({type:`string`,...O(t)})}function rr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...O(t)})}function ir(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...O(t)})}function ar(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...O(t)})}function or(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...O(t)})}function sr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...O(t)})}function cr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...O(t)})}function lr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...O(t)})}function ur(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...O(t)})}function dr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...O(t)})}function fr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...O(t)})}function pr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...O(t)})}function mr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...O(t)})}function hr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...O(t)})}function gr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...O(t)})}function _r(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...O(t)})}function vr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...O(t)})}function yr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...O(t)})}function br(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...O(t)})}function xr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...O(t)})}function Sr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...O(t)})}function Cr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...O(t)})}function wr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...O(t)})}function Tr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...O(t)})}function Er(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...O(t)})}function Dr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...O(t)})}function Or(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...O(t)})}function kr(e,t){return new e({type:`number`,checks:[],...O(t)})}function Ar(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...O(t)})}function jr(e,t){return new e({type:`boolean`,...O(t)})}function Mr(e,t){return new e({type:`null`,...O(t)})}function Nr(e){return new e({type:`unknown`})}function Pr(e,t){return new e({type:`never`,...O(t)})}function Fr(e,t){return new St({check:`less_than`,...O(t),value:e,inclusive:!1})}function Ir(e,t){return new St({check:`less_than`,...O(t),value:e,inclusive:!0})}function Lr(e,t){return new Ct({check:`greater_than`,...O(t),value:e,inclusive:!1})}function Rr(e,t){return new Ct({check:`greater_than`,...O(t),value:e,inclusive:!0})}function zr(e,t){return new wt({check:`multiple_of`,...O(t),value:e})}function Br(e,t){return new Et({check:`max_length`,...O(t),maximum:e})}function Vr(e,t){return new Dt({check:`min_length`,...O(t),minimum:e})}function Hr(e,t){return new Ot({check:`length_equals`,...O(t),length:e})}function Ur(e,t){return new At({check:`string_format`,format:`regex`,...O(t),pattern:e})}function Wr(e){return new jt({check:`string_format`,format:`lowercase`,...O(e)})}function Gr(e){return new Mt({check:`string_format`,format:`uppercase`,...O(e)})}function Kr(e,t){return new Nt({check:`string_format`,format:`includes`,...O(t),includes:e})}function qr(e,t){return new Pt({check:`string_format`,format:`starts_with`,...O(t),prefix:e})}function Jr(e,t){return new Ft({check:`string_format`,format:`ends_with`,...O(t),suffix:e})}function Yr(e){return new It({check:`overwrite`,tx:e})}function Xr(e){return Yr(t=>t.normalize(e))}function Zr(){return Yr(e=>e.trim())}function Qr(){return Yr(e=>e.toLowerCase())}function $r(){return Yr(e=>e.toUpperCase())}function ei(){return Yr(e=>ee(e))}function ti(e,t,n){return new e({type:`array`,element:t,...O(n)})}function ni(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...O(n)})}function ri(e,t){let n=ii(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Se(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Se(r))}},e(t.value,t)),t);return n}function ii(e,t){let n=new bt({check:`custom`,...O(t)});return n._zod.check=e,n}function ai(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??tr,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function oi(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,oi(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&li(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function si(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
63
|
-
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function ci(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:di(t,`input`,e.processors),output:di(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function li(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return li(r.element,n);if(r.type===`set`)return li(r.valueType,n);if(r.type===`lazy`)return li(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return li(r.innerType,n);if(r.type===`intersection`)return li(r.left,n)||li(r.right,n);if(r.type===`record`||r.type===`map`)return li(r.keyType,n)||li(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:li(r.in,n)||li(r.out,n);if(r.type===`object`){for(let e in r.shape)if(li(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(li(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(li(e,n))return!0;return!!(r.rest&&li(r.rest,n))}return!1}var ui=(e,t={})=>n=>{let r=ai({...n,processors:t});return oi(e,r),si(r,e),ci(r,e)},di=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ai({...i??{},target:a,io:t,processors:n});return oi(e,o),si(o,e),ci(o,e)},fi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},pi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},mi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},hi=(e,t,n,r)=>{n.type=`boolean`},gi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},_i=(e,t,n,r)=>{n.not={}},vi=(e,t,n,r)=>{let i=e._zod.def,a=h(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},yi=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},bi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},xi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Si=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=oi(a.element,t,{...r,path:[...r.path,`items`]})},Ci=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=oi(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=oi(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},wi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>oi(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ti=(e,t,n,r)=>{let i=e._zod.def,a=oi(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=oi(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Ei=(e,t,n,r)=>{let i=e._zod.def,a=oi(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Di=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Oi=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ki=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ai=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},ji=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;oi(o,t,r);let s=t.seen.get(e);s.ref=o},Mi=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ni=(e,t,n,r)=>{let i=e._zod.def;oi(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Pi=u(`ZodISODateTime`,(e,t)=>{Zt.init(e,t),N.init(e,t)});function Fi(e){return Tr(Pi,e)}var Ii=u(`ZodISODate`,(e,t)=>{Qt.init(e,t),N.init(e,t)});function Li(e){return Er(Ii,e)}var Ri=u(`ZodISOTime`,(e,t)=>{$t.init(e,t),N.init(e,t)});function zi(e){return Dr(Ri,e)}var Bi=u(`ZodISODuration`,(e,t)=>{en.init(e,t),N.init(e,t)});function Vi(e){return Or(Bi,e)}var Hi=u(`ZodError`,(e,t)=>{we.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>De(e,t)},flatten:{value:t=>Ee(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,g,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,g,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Ui=Oe(Hi),Wi=ke(Hi),Gi=Ae(Hi),Ki=Me(Hi),qi=Pe(Hi),Ji=Fe(Hi),Yi=Ie(Hi),Xi=Le(Hi),Zi=Re(Hi),Qi=ze(Hi),$i=Be(Hi),ea=Ve(Hi),ta=new WeakMap;function na(e,t,n){let r=Object.getPrototypeOf(e),i=ta.get(r);if(i||(i=new Set,ta.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var j=u(`ZodType`,(e,t)=>(k.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:di(e,`input`),output:di(e,`output`)}}),e.toJSONSchema=ui(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Ui(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Gi(e,t,n),e.parseAsync=async(t,n)=>Wi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ki(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>qi(e,t,n),e.decode=(t,n)=>Ji(e,t,n),e.encodeAsync=async(t,n)=>Yi(e,t,n),e.decodeAsync=async(t,n)=>Xi(e,t,n),e.safeEncode=(t,n)=>Zi(e,t,n),e.safeDecode=(t,n)=>Qi(e,t,n),e.safeEncodeAsync=async(t,n)=>$i(e,t,n),e.safeDecodeAsync=async(t,n)=>ea(e,t,n),na(e,`ZodType`,{check(...e){let t=this.def;return this.clone(w(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return oe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ho(e,t))},superRefine(e,t){return this.check(go(e,t))},overwrite(e){return this.check(Yr(e))},optional(){return Ya(this)},exactOptional(){return Za(this)},nullable(){return $a(this)},nullish(){return Ya($a(this))},nonoptional(e){return ao(this,e)},array(){return F(this)},or(e){return za([this,e])},and(e){return Ua(this,e)},transform(e){return lo(this,qa(e))},default(e){return to(this,e)},prefault(e){return ro(this,e)},catch(e){return so(this,e)},pipe(e){return lo(this,e)},readonly(){return po(this)},describe(e){let t=this.clone();return tr.add(t,{description:e}),t},meta(...e){if(e.length===0)return tr.get(this);let t=this.clone();return tr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return tr.get(e)?.description},configurable:!0}),e)),ra=u(`_ZodString`,(e,t)=>{zt.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,na(e,`_ZodString`,{regex(...e){return this.check(Ur(...e))},includes(...e){return this.check(Kr(...e))},startsWith(...e){return this.check(qr(...e))},endsWith(...e){return this.check(Jr(...e))},min(...e){return this.check(Vr(...e))},max(...e){return this.check(Br(...e))},length(...e){return this.check(Hr(...e))},nonempty(...e){return this.check(Vr(1,...e))},lowercase(e){return this.check(Wr(e))},uppercase(e){return this.check(Gr(e))},trim(){return this.check(Zr())},normalize(...e){return this.check(Xr(...e))},toLowerCase(){return this.check(Qr())},toUpperCase(){return this.check($r())},slugify(){return this.check(ei())}})}),ia=u(`ZodString`,(e,t)=>{zt.init(e,t),ra.init(e,t),e.email=t=>e.check(rr(aa,t)),e.url=t=>e.check(lr(ca,t)),e.jwt=t=>e.check(wr(wa,t)),e.emoji=t=>e.check(ur(ua,t)),e.guid=t=>e.check(ir(oa,t)),e.uuid=t=>e.check(ar(sa,t)),e.uuidv4=t=>e.check(or(sa,t)),e.uuidv6=t=>e.check(sr(sa,t)),e.uuidv7=t=>e.check(cr(sa,t)),e.nanoid=t=>e.check(dr(da,t)),e.guid=t=>e.check(ir(oa,t)),e.cuid=t=>e.check(fr(fa,t)),e.cuid2=t=>e.check(pr(pa,t)),e.ulid=t=>e.check(mr(ma,t)),e.base64=t=>e.check(xr(xa,t)),e.base64url=t=>e.check(Sr(Sa,t)),e.xid=t=>e.check(hr(ha,t)),e.ksuid=t=>e.check(gr(ga,t)),e.ipv4=t=>e.check(_r(_a,t)),e.ipv6=t=>e.check(vr(va,t)),e.cidrv4=t=>e.check(yr(ya,t)),e.cidrv6=t=>e.check(br(ba,t)),e.e164=t=>e.check(Cr(Ca,t)),e.datetime=t=>e.check(Fi(t)),e.date=t=>e.check(Li(t)),e.time=t=>e.check(zi(t)),e.duration=t=>e.check(Vi(t))});function M(e){return nr(ia,e)}var N=u(`ZodStringFormat`,(e,t)=>{A.init(e,t),ra.init(e,t)}),aa=u(`ZodEmail`,(e,t)=>{Ht.init(e,t),N.init(e,t)}),oa=u(`ZodGUID`,(e,t)=>{Bt.init(e,t),N.init(e,t)}),sa=u(`ZodUUID`,(e,t)=>{Vt.init(e,t),N.init(e,t)}),ca=u(`ZodURL`,(e,t)=>{Ut.init(e,t),N.init(e,t)});function la(e){return lr(ca,e)}var ua=u(`ZodEmoji`,(e,t)=>{Wt.init(e,t),N.init(e,t)}),da=u(`ZodNanoID`,(e,t)=>{Gt.init(e,t),N.init(e,t)}),fa=u(`ZodCUID`,(e,t)=>{Kt.init(e,t),N.init(e,t)}),pa=u(`ZodCUID2`,(e,t)=>{qt.init(e,t),N.init(e,t)}),ma=u(`ZodULID`,(e,t)=>{Jt.init(e,t),N.init(e,t)}),ha=u(`ZodXID`,(e,t)=>{Yt.init(e,t),N.init(e,t)}),ga=u(`ZodKSUID`,(e,t)=>{Xt.init(e,t),N.init(e,t)}),_a=u(`ZodIPv4`,(e,t)=>{tn.init(e,t),N.init(e,t)}),va=u(`ZodIPv6`,(e,t)=>{nn.init(e,t),N.init(e,t)}),ya=u(`ZodCIDRv4`,(e,t)=>{rn.init(e,t),N.init(e,t)}),ba=u(`ZodCIDRv6`,(e,t)=>{an.init(e,t),N.init(e,t)}),xa=u(`ZodBase64`,(e,t)=>{sn.init(e,t),N.init(e,t)}),Sa=u(`ZodBase64URL`,(e,t)=>{ln.init(e,t),N.init(e,t)}),Ca=u(`ZodE164`,(e,t)=>{un.init(e,t),N.init(e,t)}),wa=u(`ZodJWT`,(e,t)=>{fn.init(e,t),N.init(e,t)}),Ta=u(`ZodNumber`,(e,t)=>{pn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),na(e,`ZodNumber`,{gt(e,t){return this.check(Lr(e,t))},gte(e,t){return this.check(Rr(e,t))},min(e,t){return this.check(Rr(e,t))},lt(e,t){return this.check(Fr(e,t))},lte(e,t){return this.check(Ir(e,t))},max(e,t){return this.check(Ir(e,t))},int(e){return this.check(Da(e))},safe(e){return this.check(Da(e))},positive(e){return this.check(Lr(0,e))},nonnegative(e){return this.check(Rr(0,e))},negative(e){return this.check(Fr(0,e))},nonpositive(e){return this.check(Ir(0,e))},multipleOf(e,t){return this.check(zr(e,t))},step(e,t){return this.check(zr(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function P(e){return kr(Ta,e)}var Ea=u(`ZodNumberFormat`,(e,t)=>{mn.init(e,t),Ta.init(e,t)});function Da(e){return Ar(Ea,e)}var Oa=u(`ZodBoolean`,(e,t)=>{hn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r)});function ka(e){return jr(Oa,e)}var Aa=u(`ZodNull`,(e,t)=>{gn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r)});function ja(e){return Mr(Aa,e)}var Ma=u(`ZodUnknown`,(e,t)=>{_n.init(e,t),j.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Na(){return Nr(Ma)}var Pa=u(`ZodNever`,(e,t)=>{vn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r)});function Fa(e){return Pr(Pa,e)}var Ia=u(`ZodArray`,(e,t)=>{bn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Si(e,t,n,r),e.element=t.element,na(e,`ZodArray`,{min(e,t){return this.check(Vr(e,t))},nonempty(e){return this.check(Vr(1,e))},max(e,t){return this.check(Br(e,t))},length(e,t){return this.check(Hr(e,t))},unwrap(){return this.element}})});function F(e,t){return ti(Ia,e,t)}var La=u(`ZodObject`,(e,t)=>{Tn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ci(e,t,n,r),S(e,`shape`,()=>t.shape),na(e,`ZodObject`,{keyof(){return L(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Na()})},loose(){return this.clone({...this._zod.def,catchall:Na()})},strict(){return this.clone({...this._zod.def,catchall:Fa()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return de(this,e)},safeExtend(e){return fe(this,e)},merge(e){return pe(this,e)},pick(e){return le(this,e)},omit(e){return ue(this,e)},partial(...e){return me(Ja,this,e[0])},required(...e){return he(io,this,e[0])}})});function I(e,t){return new La({type:`object`,shape:e??{},...O(t)})}var Ra=u(`ZodUnion`,(e,t)=>{Dn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r),e.options=t.options});function za(e,t){return new Ra({type:`union`,options:e,...O(t)})}var Ba=u(`ZodDiscriminatedUnion`,(e,t)=>{Ra.init(e,t),On.init(e,t)});function Va(e,t,n){return new Ba({type:`union`,options:t,discriminator:e,...O(n)})}var Ha=u(`ZodIntersection`,(e,t)=>{kn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r)});function Ua(e,t){return new Ha({type:`intersection`,left:e,right:t})}var Wa=u(`ZodEnum`,(e,t)=>{Mn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Wa({...t,checks:[],...O(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Wa({...t,checks:[],...O(r),entries:i})}});function L(e,t){return new Wa({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...O(t)})}var Ga=u(`ZodLiteral`,(e,t)=>{Nn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yi(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new Ga({type:`literal`,values:Array.isArray(e)?e:[e],...O(t)})}var Ka=u(`ZodTransform`,(e,t)=>{Pn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new f(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Se(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Se(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function qa(e){return new Ka({type:`transform`,transform:e})}var Ja=u(`ZodOptional`,(e,t)=>{In.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ya(e){return new Ja({type:`optional`,innerType:e})}var Xa=u(`ZodExactOptional`,(e,t)=>{Ln.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Za(e){return new Xa({type:`optional`,innerType:e})}var Qa=u(`ZodNullable`,(e,t)=>{Rn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $a(e){return new Qa({type:`nullable`,innerType:e})}var eo=u(`ZodDefault`,(e,t)=>{zn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function to(e,t){return new eo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():re(t)}})}var no=u(`ZodPrefault`,(e,t)=>{Vn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ki(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ro(e,t){return new no({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():re(t)}})}var io=u(`ZodNonOptional`,(e,t)=>{Hn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Di(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ao(e,t){return new io({type:`nonoptional`,innerType:e,...O(t)})}var oo=u(`ZodCatch`,(e,t)=>{Wn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function so(e,t){return new oo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var co=u(`ZodPipe`,(e,t)=>{Gn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r),e.in=t.in,e.out=t.out});function lo(e,t){return new co({type:`pipe`,in:e,out:t})}var uo=u(`ZodPreprocess`,(e,t)=>{co.init(e,t),qn.init(e,t)}),fo=u(`ZodReadonly`,(e,t)=>{Jn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function po(e){return new fo({type:`readonly`,innerType:e})}var mo=u(`ZodCustom`,(e,t)=>{Xn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bi(e,t,n,r)});function ho(e,t={}){return ni(mo,e,t)}function go(e,t){return ri(e,t)}function _o(e,t){return new uo({type:`pipe`,in:qa(e),out:t})}var vo={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},yo;yo||={},m({jitless:!0});var bo={click:{cursorTravels:!0,approach:`nearest`},type:{cursorTravels:!0,approach:`nearest`},moveTo:{cursorTravels:!0,approach:`nearest`},scrollTo:{cursorTravels:!1,approach:`landing`},waitFor:{cursorTravels:!1,approach:`none`},drag:{cursorTravels:!0,approach:`nearest`},press:{cursorTravels:!1,approach:`none`}},xo=I({x:P(),y:P(),width:P().nonnegative(),height:P().nonnegative()}),So=I({sourceTimeMs:P().nonnegative(),ref:M().min(1),width:P().int().positive(),height:P().int().positive(),actionId:M().min(1).nullable(),byteLength:P().int().nonnegative().default(0)}),Co=I({startMs:P().nonnegative(),endMs:P().nonnegative(),ref:M().min(1),width:P().int().positive(),height:P().int().positive(),fps:P().positive(),byteLength:P().int().nonnegative().default(0)}),wo=I({sourceTimeMs:P().nonnegative(),x:P(),y:P()}),To=I({startMs:P().nonnegative(),endMs:P().nonnegative()}),Eo=I({actionId:M().min(1),anchorId:M().min(1),rect:xo,end:xo.optional()}),Do=I({actionId:M().min(1),pressMs:P().nonnegative(),releaseMs:P().nonnegative()}),Oo=I({sourceTimeMs:P().nonnegative(),scale:P().positive(),offsetX:P(),offsetY:P()}),ko=I({actionId:M().min(1),sourceTimeMs:P().nonnegative(),actEndSourceTimeMs:P().nonnegative().optional(),roomMs:P().nonnegative().optional(),roomHeldMs:P().nonnegative().optional()}).superRefine((e,t)=>{e.actEndSourceTimeMs!==void 0&&e.actEndSourceTimeMs<e.sourceTimeMs&&t.addIssue({code:vo.custom,path:[`actEndSourceTimeMs`],message:`act end ${e.actEndSourceTimeMs}ms is before the step's marker at ${e.sourceTimeMs}ms`})}),Ao=I({actionId:M().min(1),kind:M().min(1),anchorId:M().min(1).nullable(),text:M().nullable(),cut:ka().optional()}),jo=I({startMs:P().nonnegative(),endMs:P().nonnegative(),kind:L([`keyframeOnly`,`budgetBreach`,`occlusionPause`,`pageNeverSettled`,`surfaceMismatch`,`encodeRefused`,`stillFailed`,`scrollUnsettled`,`scrollLandingOffscreen`,`clickUnconfirmed`,`textLinesUnmeasured`,`cursorSynthesized`,`motionReclaimed`,`pacingUnplaced`,`notDragged`,`dragPictureMissing`]),note:M()});function Mo(e,t,n,r){for(let i=1;i<e.length;i++)if(e[i]<e[i-1]){n.addIssue({code:`custom`,message:`${t} must be in ascending sourceTimeMs order`,path:r});return}}I({bundleVersion:R(1),sceneId:M().min(1),source:L([`replay`,`capture`]),timing:R(`real`).optional(),pacedGaps:F(I({afterActionId:M().min(1),durationMs:P().nonnegative()})).optional(),dpr:P().positive(),viewport:I({width:P().int().positive(),height:P().int().positive()}),keyframes:F(So),motionSpans:F(Co),cursorSamples:F(wo),cursorGaps:F(To).default([]),anchorRects:F(Eo),heldPresses:F(Do).optional(),viewportTransforms:F(Oo).optional(),markers:F(ko),degradations:F(jo),madeFrom:F(Ao).optional()}).superRefine((e,t)=>{e.source===`capture`&&e.timing!==void 0&&t.addIssue({code:`custom`,message:`a capture bundle is real time by definition and carries no timing field`,path:[`timing`]}),e.pacedGaps!==void 0&&e.timing!==`real`&&t.addIssue({code:`custom`,message:`only a real-time replay waits out gaps live; pacedGaps needs timing: real`,path:[`pacedGaps`]}),e.keyframes.length===0&&t.addIssue({code:`custom`,message:`a bundle needs at least one keyframe`,path:[`keyframes`]}),Mo(e.keyframes.map(e=>e.sourceTimeMs),`keyframes`,t,[`keyframes`]),Mo(e.cursorSamples.map(e=>e.sourceTimeMs),`cursorSamples`,t,[`cursorSamples`]),e.motionSpans.forEach((e,n)=>{e.endMs<e.startMs&&t.addIssue({code:`custom`,message:`endMs must not precede startMs`,path:[`motionSpans`,n,`endMs`]})});let n=[...e.motionSpans].sort((e,t)=>e.startMs-t.startMs);for(let e=1;e<n.length;e++)if(n[e].startMs<n[e-1].endMs){t.addIssue({code:`custom`,message:`motion spans must not overlap`,path:[`motionSpans`]});break}if(e.source===`replay`&&e.cursorSamples.length===0){let n=new Map((e.madeFrom??[]).map(e=>[e.actionId,e.kind]));e.madeFrom!==void 0&&e.markers.length>0&&e.markers.every(e=>{let t=n.get(e.actionId);return t!==void 0&&Object.hasOwn(bo,t)&&!bo[t].cursorTravels})||t.addIssue({code:`custom`,message:`a replay bundle must carry the cursor samples it dispatched`,path:[`cursorSamples`]})}});function No(e){return e.source===`capture`||e.timing===`real`}function Po(e,t,n){return(e.pacedGaps??[]).some(e=>e.afterActionId===t&&(n===void 0||e.durationMs===n))}var Fo=.02;function Io(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width/t.width,r=e.height/t.height;return Math.abs(n/r-1)<=Fo}function Lo(e,t,n){return e.some(e=>e.startMs<n&&e.endMs>t)}function Ro(e,t){let n=e.motionSpans.find(e=>t>=e.startMs&&t<=e.endMs);if(!n||!Io(n,e.viewport))return null;let r=e.keyframes.find(e=>e.sourceTimeMs===t);return r===void 0||n.width>r.width?n:null}function zo(e,t){for(let n=e.keyframes.length-1;n>=0;n--){let r=e.keyframes[n];if(r&&r.sourceTimeMs<=t)return r}return e.keyframes[0]??null}function Bo(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function Vo(e,t,n){return e+(t-e)*n}function Ho(e,t,n){return{x:Vo(e.x,t.x,n),y:Vo(e.y,t.y,n)}}function z(e,t,n){return Math.min(n,Math.max(t,e))}function Uo(e,t){let n=Math.min(t.width/e.width,t.height/e.height),r=e.width*n,i=e.height*n;return{x:t.x+(t.width-r)/2,y:t.y+(t.height-i)/2,width:r,height:i}}function Wo(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}var Go={linear:e=>e,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,easeOutCubic:e=>1-(1-e)**3,easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,easeOutBackDamped:e=>1+1.35*(e-1)**3+.35*(e-1)**2,minimumJerk:e=>e*e*e*(e*(6*e-15)+10)};function Ko(e,t){if(e.length===0)throw Error(`catmullRom needs at least one point`);let n=e[0];if(e.length===1)return{...n};let r=e[e.length-1];if(t<=0)return{...n};if(t>=1)return{...r};if(e.length===2)return Ho(n,r,t);let i=e.length-1,a=t*i,o=Math.min(i-1,Math.floor(a)),s=a-o,c=e[Math.max(0,o-1)],l=e[o],u=e[o+1],d=e[Math.min(e.length-1,o+2)],f=(e,t,n,r)=>{let i=s*s,a=i*s;return .5*(2*t+(-e+n)*s+(2*e-5*t+4*n-r)*i+(-e+3*t-3*n+r)*a)};return{x:f(c.x,l.x,u.x,d.x),y:f(c.y,l.y,u.y,d.y)}}function qo(e,t){if(!(Number.isFinite(t)&&t>0))throw RangeError(`springEase needs a positive stiffness, got ${t}`);let n=e<=0?0:e>=1?1:e;if(n===0)return 0;if(n===1)return 1;let r=e=>1-(1+t*e)*Math.exp(-t*e),i=t*t*Math.exp(-t);return(r(n)-i*n*n*(n-1))/r(1)}var Jo=/^#?([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;function Yo(e){return e.length<=4?e.split(``).map(e=>e+e).join(``):e}var Xo=e=>e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055;function Zo(e){return`#${e.map(e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`)).join(``)}`}function Qo({l:e,c:t,h:n}){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),a=(e+.3963377774*r+.2158037573*i)**3,o=(e-.1055613458*r-.0638541728*i)**3,s=(e-.0894841775*r-1.291485548*i)**3;return[4.0767416621*a-3.3077115913*o+.2309699292*s,-1.2684380046*a+2.6097574011*o-.3413193965*s,-.0041960863*a-.7034186147*o+1.707614701*s]}var $o=e=>e.every(e=>e>=-1e-6&&e<=1+1e-6);function es(e,t=`chroma`){let n=Qo(e),r=!$o(n);if(r&&t===`chroma`){let t=0,r=e.c;for(let n=0;n<24;n++){let n=(t+r)/2;$o(Qo({...e,c:n}))?t=n:r=n}n=Qo({...e,c:t})}return{hex:Zo(n.map(e=>Xo(Math.min(1,Math.max(0,e))))),clipped:r}}var ts={ok:!1,reason:`Backgrounds are opaque — drop the alpha`};function ns(e,t){let n=/^(-?\d*\.?\d+)%$/.exec(e);return n?Number(n[1])/100*t:/^-?\d*\.?\d+$/.test(e)?Number(e):null}function rs(e){let t=/^([a-z]+)\(\s*(.*)\s*\)$/i.exec(e);if(!t)return null;let n=t[1].toLowerCase(),[r,i]=t[2].split(`/`).map(e=>e.trim()),a=r.split(/[\s,]+/).filter(Boolean);return i===void 0?a.length===4?{name:n,parts:a.slice(0,3),alpha:a[3]}:a.length===3?{name:n,parts:a,alpha:null}:null:a.length===3?{name:n,parts:a,alpha:i}:null}function is(e,t,n){let r=t=>(t+e/30)%12,i=t*Math.min(n,1-n),a=e=>n-i*Math.max(-1,Math.min(r(e)-3,Math.min(9-r(e),1)));return[a(0),a(8),a(4)]}function as(e){let t=e.trim(),n={ok:!1,reason:`"${t}" is not a colour`},r=Jo.exec(t);if(r){let e=Yo(r[1]).toLowerCase();return e.length===8?e.slice(6)===`ff`?{ok:!0,hex:`#${e.slice(0,6)}`,note:null}:ts:{ok:!0,hex:`#${e}`,note:null}}let i=rs(t);if(!i)return n;if(i.alpha!==null){let e=ns(i.alpha,1);if(e===null)return n;if(e!==1)return ts}if(i.name===`rgb`||i.name===`rgba`){let e=i.parts.map(e=>ns(e,255));return e.some(e=>e===null)?n:{ok:!0,hex:Zo(e.map(e=>e/255)),note:null}}if(i.name===`hsl`||i.name===`hsla`){let e=ns(i.parts[0].replace(/deg$/,``),360),t=e=>e.endsWith(`%`)?ns(e,1):(e=>e===null?null:e/100)(ns(e,1)),r=t(i.parts[1]),a=t(i.parts[2]);return e===null||r===null||a===null?n:{ok:!0,hex:Zo(is((e%360+360)%360,r,a)),note:null}}if(i.name===`oklch`){let e=ns(i.parts[0],1),t=ns(i.parts[1],.4),r=ns(i.parts[2].replace(/deg$/,``),360);if(e===null||t===null||r===null)return n;let a=es({l:e,c:t,h:r});return{ok:!0,hex:a.hex,note:a.clipped?`Nearest sRGB is ${a.hex}`:null}}return n}var os=L([`phone`,`tablet`]),ss={iphone:`phone`,android:`phone`,ipad:`tablet`},cs=_o(e=>typeof e==`string`&&e in ss?ss[e]:e,os),ls=I({brands:F(I({brand:M(),version:M()})).optional(),platform:M(),platformVersion:M(),architecture:M(),model:M(),mobile:ka()}),us=I({preset:cs,width:P().int().positive(),height:P().int().positive(),mobile:ka(),touch:ka(),userAgent:M().min(1),userAgentMetadata:ls.optional()}),ds=[{id:`muted-1`,family:`muted`,swatch:{from:`#141422`,to:`#26233e`}},{id:`muted-2`,family:`muted`,swatch:{from:`#bfb5aa`,to:`#a19486`}},{id:`muted-3`,family:`muted`,swatch:{from:`#1b1e1d`,to:`#51625d`}},{id:`muted-4`,family:`muted`,swatch:{from:`#a3a299`,to:`#cfcbc3`}},{id:`vivid-1`,family:`vivid`,swatch:{from:`#3527bc`,to:`#ce1676`}},{id:`vivid-2`,family:`vivid`,swatch:{from:`#0769ca`,to:`#1e26b7`}},{id:`vivid-3`,family:`vivid`,swatch:{from:`#c90757`,to:`#ed480d`}},{id:`vivid-4`,family:`vivid`,swatch:{from:`#0ba393`,to:`#0575c7`}},{id:`vivid-5`,family:`vivid`,swatch:{from:`#f28b0a`,to:`#df2d21`}},{id:`vivid-6`,family:`vivid`,swatch:{from:`#3d0dbf`,to:`#133ac7`}},{id:`light-1`,family:`light`,swatch:{from:`#b7bff3`,to:`#eda9c5`}},{id:`light-2`,family:`light`,swatch:{from:`#afe5f0`,to:`#98c5e8`}},{id:`dark-1`,family:`dark`,swatch:{from:`#150217`,to:`#3d044b`}},{id:`dark-2`,family:`dark`,swatch:{from:`#02576e`,to:`#023758`}}],fs=`muted-1`;function ps(e){return ds.find(t=>t.id===e)??null}function ms(e,t){return`${e}-${t}.webp`}var hs=I({x:P(),y:P(),width:P().nonnegative(),height:P().nonnegative()}),gs=I({stableId:M().min(1).nullable(),role:M().min(1).nullable(),accessibleName:M().nullable(),textContent:M().nullable(),treePath:M().min(1).nullable(),boundingRect:hs.nullable(),imagePatchRef:M().min(1).nullable(),dataKey:M().min(1).nullable()}),_s=L([`stableId`,`roleName`,`text`,`treePath`,`imagePatch`,`ambiguous`,`broken`]),vs=L([`notInTree`,`closedShadowRoot`,`frameGone`,`frameUnreachable`,`patchUnavailable`,`ambiguousTie`]),ys=I({url:M(),actionIndex:P().int().nonnegative(),entryState:ka(),strategy:_s,failureReason:vs.nullable(),candidates:P().int().nonnegative()}),bs=I({id:M().min(1),fingerprint:gs,resolution:ys}).superRefine((e,t)=>{let n=e.fingerprint;n.stableId!==null||n.role!==null&&n.accessibleName!==null||n.textContent!==null||n.treePath!==null||n.imagePatchRef!==null||n.dataKey!==null||t.addIssue({code:`custom`,message:`fingerprint must contain at least one usable strategy`,path:[`fingerprint`]})}),xs={id:M().min(1),anchorId:M().min(1),timestamp:P().nonnegative(),marker:M().min(1),rect:hs.optional()},Ss=I({...xs,kind:R(`moveTo`),signal:L([`mutation`,`style`]).optional()}),Cs=[`Enter`,`Tab`,`Escape`,`Backspace`,`Delete`,`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Space`],ws=I({x:P().min(0).max(1),y:P().min(0).max(1)}),Ts=I({...xs,kind:R(`click`),at:ws.optional(),button:L([`left`,`middle`,`right`]).optional(),textLines:F(hs).max(200).optional()}),Es=I({...xs,kind:R(`type`),text:M().nullable(),redacted:ka(),host:R(!0).optional()}).superRefine((e,t)=>{e.redacted&&e.text!==null&&t.addIssue({code:`custom`,message:`redacted type action must not carry text`,path:[`text`]}),!e.redacted&&e.text===null&&t.addIssue({code:`custom`,message:`non-redacted type action requires text`,path:[`text`]})}),Ds=I({...xs,kind:R(`scrollTo`)}),Os=I({...xs,anchorId:M().min(1).nullable(),kind:R(`waitFor`),condition:L([`visible`,`hidden`,`loaded`]).optional()}),ks=I({...xs,anchorId:ja(),kind:R(`press`),key:L(Cs)}),As=Va(`kind`,[Ss,Ts,Es,Ds,Os,I({...xs,kind:R(`drag`),toAnchorId:M().min(1).nullable(),toRect:hs.optional(),fromAt:ws.optional(),pressedAt:ws.optional(),to:za([I({at:ws.optional()}).strict(),I({by:I({x:P(),y:P()})}).strict()])}),ks]),js=I({actionId:M().min(1),offsetMs:P()}),Ms=I({actionId:M().min(1),sourceOffsetMs:P()}),Ns=I({x:P(),y:P()}),Ps=I({id:M().min(1),kind:L([`zoom`,`pan`]),anchorId:M().min(1).optional(),point:Ns.optional(),marker:js,end:js.optional(),scale:P().positive().optional(),note:M().optional(),source:L([`click`,`author`]).optional(),scaleSetBy:L([`script`,`author`]).optional()}),Fs=za([I({actionId:M().min(1),reason:L([`tooClose`,`sameTarget`]),afterActionId:M().min(1),gapMs:P(),askedScale:P().optional()}),I({actionId:M().min(1),reason:R(`off`)}),I({actionId:M().min(1),reason:L([`targetTooWide`,`textTooWide`]),scale:P().nonnegative()})]);function Is(e){let t=[[`actionId`,e.actionId]];return`afterActionId`in e&&t.push([`afterActionId`,e.afterActionId]),t}var Ls=I({id:M().min(1),rect:hs,note:M().optional(),start:Ms.optional(),end:Ms.optional()}),Rs=I({id:M().min(1),marker:I({actionId:M().min(1),offsetMs:P()}),durationMs:P().positive()}),zs=I({id:M().min(1),afterActionId:M().min(1),durationMs:P().nonnegative()}),Bs=I({id:M().min(1),method:L([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),url:M(),classification:L([`read`,`analytics`,`mutation`]),timestamp:P().nonnegative(),reclassified:ka()}),Vs=I({level:L([`log`,`info`,`warn`,`error`,`debug`]),text:M(),timestamp:P().nonnegative()}),Hs=I({url:M(),timestamp:P().nonnegative()}),Us=I({id:M().min(1),name:M(),createdAt:Fi(),toolchain:I({resolverVersion:M().min(1),compositorVersion:M().min(1).nullable(),captureVersion:M().min(1).nullable()}),capture:I({originUrl:la(),originClass:L([`published`,`development`,`preview`]),buildSha:M().min(1).nullable(),buildShaSource:M().min(1).nullable(),viewport:I({width:P().int().positive(),height:P().int().positive()}),dpr:P().positive(),mode:L([`record`,`retro`,`authored`]),device:us.optional(),displayScale:P().positive().optional()}),renderMode:L([`screen`,`demo`]).optional()}),Ws=L([`light`,`dark`,`touch`]),Gs=I({hidden:ka(),style:Ws,scale:P().min(.5).max(2),motionBlur:P().min(0).max(1),hideWhenIdle:ka(),tilt:P().min(0).max(1).optional(),clickBounce:P().min(0).max(2).optional()}),Ks=Object.freeze({hidden:!1,style:`light`,scale:1,motionBlur:1,hideWhenIdle:!1}),qs=Object.freeze({tilt:.5,clickBounce:1}),Js=I({smoothness:P().min(0).max(1),blur:P().min(0).max(1),follow:ka()}),Ys=Object.freeze({smoothness:.5,blur:.5,follow:!0}),Xs=I({aspect:L([`auto`,`16:9`,`9:16`])}),Zs=Object.freeze({aspect:`auto`}),Qs=M().regex(/^#[0-9a-f]{6}$/),$s=P().min(0).max(1).optional(),ec=Va(`kind`,[I({kind:R(`solid`),color:Qs}),I({kind:R(`gradient`),from:Qs,to:Qs,angle:P().int().min(0).max(359)}),I({kind:R(`wallpaper`),id:M().regex(/^[a-z0-9-]+$/),blur:$s}),I({kind:R(`image`),ref:M().min(1),blur:$s})]),tc=[`top-left`,`top-right`,`bottom-left`,`bottom-right`],nc=I({background:ec,logo:I({ref:M().min(1),corner:L(tc),size:P().min(.02).max(.2),opacity:P().min(.2).max(1)}).nullable(),padding:P().min(0).max(.2)}),rc=Object.freeze({kind:`gradient`,from:es({l:.95,c:.005,h:260},`clip`).hex,to:es({l:.86,c:.008,h:260},`clip`).hex,angle:150}),ic=Object.freeze({background:Object.freeze({kind:`wallpaper`,id:fs,blur:0}),logo:null,padding:.12}),ac=Object.freeze({corner:`bottom-right`,size:.06,opacity:.9}),oc=I({schemaVersion:R(15),meta:Us,anchors:F(bs),actions:F(As),camera:F(Ps),zoomsSkipped:F(Fs).optional(),edits:I({masks:F(Ls),holds:F(Rs),gaps:F(zs).default([]),splits:F(I({id:M().min(1),at:Ms})).default([]),removed:F(I({id:M().min(1),start:Ms.nullable(),end:Ms.nullable()})).default([]),trim:I({head:js.optional(),tail:js.optional()}).optional()}),sideChannels:I({network:F(Bs),consoleExcerpt:F(Vs),urlTrace:F(Hs),uncoveredOrigins:F(M())}),flags:I({mutating:ka(),hoverSensitive:ka()}),branding:nc,cursor:Gs,canvas:Xs,motion:Js.optional()}).superRefine((e,t)=>{let n=(e,n,r)=>{let i=new Set;e.forEach((e,a)=>{i.has(e.id)&&t.addIssue({code:`custom`,message:`duplicate ${n} id "${e.id}"`,path:[...r,a,`id`]}),i.add(e.id)})};n(e.anchors,`anchor`,[`anchors`]),n(e.actions,`action`,[`actions`]),n(e.camera,`camera event`,[`camera`]),n(e.edits.holds,`hold`,[`edits`,`holds`]),n(e.edits.gaps,`gap`,[`edits`,`gaps`]),n(e.edits.gaps.map(e=>({id:e.afterActionId})),`gap for an action`,[`edits`,`gaps`]),n(e.edits.splits,`split`,[`edits`,`splits`]),n(e.edits.removed,`removed piece`,[`edits`,`removed`]);let r=new Set(e.anchors.map(e=>e.id)),i=new Set(e.actions.map(e=>e.id));e.actions.forEach((e,n)=>{e.anchorId!==null&&!r.has(e.anchorId)&&t.addIssue({code:`custom`,message:`unknown anchor "${e.anchorId}"`,path:[`actions`,n,`anchorId`]})}),e.camera.forEach((e,n)=>{let a=e.anchorId!==void 0;a===(e.point!==void 0)&&t.addIssue({code:`custom`,message:a?`camera event "${e.id}" names both an anchor and a point; a zoom aims at one thing`:`camera event "${e.id}" aims at nothing: it needs an anchorId or a point`,path:[`camera`,n,`anchorId`]}),e.anchorId!==void 0&&!r.has(e.anchorId)&&t.addIssue({code:`custom`,message:`unknown anchor "${e.anchorId}"`,path:[`camera`,n,`anchorId`]}),i.has(e.marker.actionId)||t.addIssue({code:`custom`,message:`unknown action "${e.marker.actionId}"`,path:[`camera`,n,`marker`,`actionId`]}),e.end!==void 0&&!i.has(e.end.actionId)&&t.addIssue({code:`custom`,message:`unknown action "${e.end.actionId}"`,path:[`camera`,n,`end`,`actionId`]})}),(e.zoomsSkipped??[]).forEach((e,n)=>{for(let[r,a]of Is(e))i.has(a)||t.addIssue({code:`custom`,message:`unknown action "${a}"`,path:[`zoomsSkipped`,n,r]})}),e.edits.masks.forEach((e,n)=>{if(e.start===void 0!=(e.end===void 0)){let r=e.start===void 0?`start`:`end`;t.addIssue({code:`custom`,message:`mask "${e.id}" has ${r===`start`?`an end`:`a start`} but no ${r}; a range needs both, and neither means the whole take`,path:[`edits`,`masks`,n,r]})}for(let r of[`start`,`end`]){let a=e[r];a!==void 0&&!i.has(a.actionId)&&t.addIssue({code:`custom`,message:`unknown action "${a.actionId}"`,path:[`edits`,`masks`,n,r,`actionId`]})}e.start!==void 0&&e.end!==void 0&&e.start.actionId===e.end.actionId&&e.end.sourceOffsetMs<=e.start.sourceOffsetMs&&t.addIssue({code:`custom`,message:`mask "${e.id}" ends before it starts`,path:[`edits`,`masks`,n,`end`]})});for(let n of[`head`,`tail`]){let r=e.edits.trim?.[n];r!==void 0&&!i.has(r.actionId)&&t.addIssue({code:`custom`,message:`unknown action "${r.actionId}"`,path:[`edits`,`trim`,n,`actionId`]})}e.edits.holds.forEach((e,n)=>{i.has(e.marker.actionId)||t.addIssue({code:`custom`,message:`unknown action "${e.marker.actionId}"`,path:[`edits`,`holds`,n,`marker`,`actionId`]})}),(e.edits.splits??[]).forEach((e,n)=>{i.has(e.at.actionId)||t.addIssue({code:`custom`,message:`unknown action "${e.at.actionId}"`,path:[`edits`,`splits`,n,`at`,`actionId`]})}),(e.edits.removed??[]).forEach((e,n)=>{for(let r of[`start`,`end`]){let a=e[r];a!==null&&!i.has(a.actionId)&&t.addIssue({code:`custom`,message:`unknown action "${a.actionId}"`,path:[`edits`,`removed`,n,r,`actionId`]})}}),e.edits.gaps.forEach((e,n)=>{i.has(e.afterActionId)||t.addIssue({code:`custom`,message:`gap ${e.id} follows an action that does not exist`,path:[`edits`,`gaps`,n,`afterActionId`]})})});function sc(e,t){return t===void 0?{x:e.x+e.width/2,y:e.y+e.height/2}:{x:cc(e.x,e.width,t.x),y:cc(e.y,e.height,t.y)}}function cc(e,t,n){let r=Math.min(lc,t/2);return Math.min(Math.max(e+n*t,e+r),e+t-r)}var lc=.5;function uc(e,t,n){return`by`in t?{x:e.x+t.by.x,y:e.y+t.by.y}:n==null?null:sc(n,t.at)}function dc(e,t,n){if(t===void 0)return null;let r=sc(t,e.pressedAt??e.fromAt),i=uc(r,e.to,n);return i===null?null:{start:r,end:i}}function fc(e){let t=new Map(e.actions.map((e,t)=>[e.id,t])),n=new Set;for(let r of e.edits.removed??[]){let i=r.start===null?null:t.get(r.start.actionId),a=r.end===null?null:t.get(r.end.actionId);i!==void 0&&a!==void 0&&e.actions.forEach((e,t)=>{let o=r.start===null||i===null||i<t||t===i&&r.start.sourceOffsetMs<=0,s=r.end===null||a===null||t<a||t===a&&r.end.sourceOffsetMs>0;o&&s&&n.add(e.id)})}return n}var pc=2.5,mc=/^[a-z0-9][a-z0-9_-]{0,63}$/,hc=`lower-case letters, digits, "-" and "_", starting with a letter or digit, at most 64 characters`,gc=za([I({stableId:M().min(1)}).strict(),I({role:M().min(1),name:M().min(1)}).strict(),I({text:M().min(1)}).strict(),I({treePath:M().min(1)}).strict()]),_c=M().min(1).optional(),vc=I({x:P().min(0).max(1),y:P().min(0).max(1)}).strict(),yc=I({on:gc,at:vc.optional()}).strict(),bc=za([yc,I({by:I({x:P().finite(),y:P().finite()}).strict()}).strict()]),xc=za([R(!1),I({scale:P().gt(1,{message:"a zoom scale is over 1; use `zoom: false` for none"}).max(pc,{message:`a zoom scale is at most ${pc}, the camera's limit`})}).strict()]),Sc=Va(`do`,[I({do:R(`click`),on:gc,at:vc.optional(),zoom:xc.optional(),recorded:_c}).strict(),I({do:R(`type`),into:gc,text:M(),recorded:_c}).strict(),I({do:R(`hover`),on:gc,recorded:_c}).strict(),I({do:R(`scrollTo`),on:gc,recorded:_c,landing:I({top:P().finite()}).strict().optional()}).strict(),I({do:R(`waitFor`),on:gc,until:L([`visible`,`hidden`]),recorded:_c}).strict(),I({do:R(`drag`),from:yc,to:bc,zoom:xc.optional(),recorded:_c}).strict(),I({do:R(`press`),key:L(Cs),recorded:_c}).strict(),I({do:R(`waitForLoad`),recorded:_c}).strict(),I({do:R(`pause`),ms:P().positive()}).strict()]),Cc={click:!0,type:!0,hover:!0,scrollTo:!0,waitFor:!0,drag:!0,press:!0,waitForLoad:!0,pause:!1},wc={click:!0,type:!0,hover:!0,scrollTo:!0,waitFor:!1,drag:!0,press:!0,waitForLoad:!1,pause:!1};function Tc(e,t){let n=e.trim?.[t]?.step;if(n!==void 0)return n-1;let r=e.steps.flatMap((e,t)=>wc[e.do]?[t]:[]);return(t===`start`?r[0]:r.at(-1))??null}var Ec=I({start:I({ms:P().finite().nonnegative(),step:P().int().positive().optional()}).strict().optional(),end:I({ms:P().finite().nonnegative(),step:P().int().positive().optional(),after:L([`zoomOut`,`action`]).optional()}).strict().optional()}).strict(),Dc=nc.extend({padding:nc.shape.padding.default(ic.padding)}),Oc=R([1,2,3,4,5,6,7,8]),kc=(e,t)=>t>e?t:e;I({scriptVersion:Oc.optional(),name:M().min(1),target:la(),viewport:I({width:P().int().positive(),height:P().int().positive()}).optional(),device:os.optional(),account:M().regex(mc,{message:`an account name is ${hc}`}).optional(),steps:F(Sc).min(1),trim:Ec.optional(),recordedFrom:M().min(1).optional(),look:I({branding:Dc.optional(),kit:M().trim().min(1).optional(),cursor:Gs.optional(),canvas:Xs.optional(),motion:Js.optional()}).strict().refine(e=>e.branding===void 0||e.kit===void 0,{message:`name a kit or give a branding, not both`}).optional()}).superRefine((e,t)=>{let n=e.look?.branding?.background;n?.kind===`wallpaper`&&!ds.some(e=>e.id===n.id)&&t.addIssue({code:`custom`,message:`unknown wallpaper "${n.id}" — one of ${ds.map(e=>e.id).join(`, `)}`,path:[`look`,`branding`,`background`,`id`]}),e.steps.forEach((e,n)=>{e.do===`drag`&&(`by`in e.to?e.to.by.x===0&&e.to.by.y===0:JSON.stringify(e.to.on)===JSON.stringify(e.from.on)&&(e.to.at?.x??.5)===(e.from.at?.x??.5)&&(e.to.at?.y??.5)===(e.from.at?.y??.5))&&t.addIssue({code:`custom`,message:`step ${n+1} is a drag that starts and ends at the same point: give \`to\` another target, spot or offset, or make it a click`,path:[`steps`,n,`to`]})}),e.steps.forEach((e,n)=>{e.do!==`type`||!/\{secret:/.test(e.text)||t.addIssue({code:`custom`,message:`{secret:…} works only in an account's signIn steps in .demoman/accounts.json, never in a demo script: name the script's account instead, and type demo values here`,path:[`steps`,n,`text`]})}),e.device!==void 0&&e.viewport!==void 0&&t.addIssue({code:`custom`,message:`name a device or a viewport, not both: a device is a viewport`,path:[`device`]}),e.device!==void 0&&e.steps.forEach((n,r)=>{n.do===`hover`&&t.addIssue({code:`custom`,message:`step ${r+1} is a hover, and a ${e.device} has no hover: tap it, or drop the step`,path:[`steps`,r]})}),e.trim&&Ac(e,t),!e.steps.some(e=>Cc[e.do])&&t.addIssue({code:`custom`,message:`a script needs at least one step that acts on the page; every step here is a pause, which is a duration and performs nothing, so this script can never produce a take`,path:[`steps`]})}).transform(e=>({...e,scriptVersion:kc(e.scriptVersion??1,jc(e))}));function Ac(e,t){let{steps:n,trim:r={}}=e,i=!1;for(let e of[`start`,`end`]){let a=r[e]?.step;if(a===void 0)continue;let o=a>n.length?`trim.${e}.step is ${a}, but the script has ${n.length} steps`:n[a-1]?.do===`pause`?`trim.${e}.step is ${a}, a pause: name a step that does something`:void 0;o&&(i=!0,t.addIssue({code:`custom`,message:o,path:[`trim`,e,`step`]}))}let a=Tc(e,`start`),o=Tc(e,`end`);!i&&a!==null&&o!==null&&a>o&&t.addIssue({code:`custom`,message:`trim starts at step ${a+1}, after the step it ends at (${o+1}): the film would be empty`,path:[`trim`,`start`,`step`]})}function jc(e){return[[e.look?.kit!==void 0,2],[e.look?.motion!==void 0,3],[Mc(e.look?.cursor),3],[e.device!==void 0,4],[e.account!==void 0,5],[e.steps.some(e=>e.do===`drag`),6],[e.trim!==void 0||e.steps.some(e=>(e.do===`click`||e.do===`drag`)&&e.zoom!==void 0),8],[e.steps.some(e=>e.do===`press`||e.do===`click`&&e.at),7]].filter(([e])=>e).map(([,e])=>e).reduce(kc,1)}function Mc(e){return e?.tilt!==void 0||e?.clickBounce!==void 0}var Nc=3;function Pc(e,t){let n=new Set;for(let r of t){let t=null,i=null;for(let n=0;n<e.length;n++){let a=e[n]?.sourceTimeMs;if(a!==void 0&&(a<=r&&(t=n),a>=r)){i=n;break}}t!==null&&n.add(t),i!==null&&n.add(i)}return n}function Fc(e,t,n){let r=Array(e.length).fill(0),i=Array(e.length).fill(e.length-1),a=0;for(let o=1;o<=e.length;o++){let s=e[o-1],c=e[o];if(c===void 0||s===void 0||c.sourceTimeMs-s.sourceTimeMs>t||Lo(n,s.sourceTimeMs,c.sourceTimeMs)){for(let e=a;e<o;e++)r[e]=a,i[e]=o-1;a=o}}return{start:r,end:i}}function Ic(e,t,n=[],r=[]){if(t<=0||e.length<3)return e;let i=Pc(e,n),a=Fc(e,50,r),o=Nc*t,s=2*t*t,c=1e-6,l=0,u=0,d=-1,f=0,p=0,m=0;return e.map((t,n)=>{let h=a.start[n],g=a.end[n],_=e[h],v=e[g];if(h!==d){d=h,l=h,u=h;let t=v.sourceTimeMs-_.sourceTimeMs;f=g>h?t/(g-h):0;let n=h>0?e[h-1].sourceTimeMs:0,i=g<e.length-1?e[g+1].sourceTimeMs:0,a=h>0&&!Lo(r,n,_.sourceTimeMs)?_.sourceTimeMs-n:0,s=g<e.length-1&&!Lo(r,v.sourceTimeMs,i)?i-v.sourceTimeMs:0;p=Math.min(o,a),m=Math.min(o,s)}if(n===h||n===g||i.has(n))return t;let y=t.sourceTimeMs,b=Math.min(o,y-_.sourceTimeMs+p,v.sourceTimeMs-y+m);if(b<=0)return t;for(;l<=g&&y-e[l].sourceTimeMs>b+c;)l++;for(u<l&&(u=l);u<=g&&e[u].sourceTimeMs-y<=b+c;)u++;let x=0,S=0,C=0;for(let t=l;t<u;t++){let n=e[t];if(!n)continue;let r=n.sourceTimeMs-y;if(Math.abs(r)>b)continue;let i=Math.exp(-(r*r)/s);x+=n.x*i,S+=n.y*i,C+=i}if(f>0){for(let e=f;e<=p+c;e+=f){let t=_.sourceTimeMs-e-y;if(-t>b+c)break;let n=Math.exp(-(t*t)/s);x+=_.x*n,S+=_.y*n,C+=n}for(let e=f;e<=m+c;e+=f){let t=v.sourceTimeMs+e-y;if(t>b+c)break;let n=Math.exp(-(t*t)/s);x+=v.x*n,S+=v.y*n,C+=n}}return C===0?t:{sourceTimeMs:y,x:x/C,y:S/C}})}function Lc(e){return 2*e}function Rc(e){return 6*e}function zc(e,t){let n=e[0];if(t<=n.sourceTimeMs)return{x:n.x,y:n.y};for(let n=1;n<e.length;n++){let r=e[n];if(r.sourceTimeMs<t)continue;let i=e[n-1],a=r.sourceTimeMs-i.sourceTimeMs,o=a===0?0:(t-i.sourceTimeMs)/a;return{x:i.x+(r.x-i.x)*o,y:i.y+(r.y-i.y)*o}}let r=e[e.length-1];return{x:r.x,y:r.y}}function Bc(e){let t=1;return n=>{let r=e[0];if(n<=r.sourceTimeMs)return{x:r.x,y:r.y};for(;t<e.length&&e[t].sourceTimeMs<n;)t++;let i=e[t];if(!i){let t=e[e.length-1];return{x:t.x,y:t.y}}let a=e[t-1],o=i.sourceTimeMs-a.sourceTimeMs,s=o===0?0:(n-a.sourceTimeMs)/o;return{x:a.x+(i.x-a.x)*s,y:a.y+(i.y-a.y)*s}}}var Vc=8;function Hc(e,t,n,r=[]){if(t<=0||e.length<2)return e;if(r.length===0)return Uc(e,t,n);let i=[],a=0;for(let o=1;o<=e.length;o++){let s=e[o],c=e[o-1];if(!(s===void 0||Lo(r,c.sourceTimeMs,s.sourceTimeMs)))continue;let l=e.slice(a,o),u=l[0],d=l[l.length-1];i.push(...l.length<2?l:Uc(l,t,n.filter(e=>e>=u.sourceTimeMs&&e<=d.sourceTimeMs))),a=o}return i}function Uc(e,t,n){let r=1/t,i=Rc(t),a=e[0],o=[{...a}],s=a.x,c=a.y,l=0,u=0,d=(e,t,n,i)=>{if(e<=0){o.push({sourceTimeMs:i,x:s,y:c});return}let a=Math.exp(-r*e),d=s-t,f=c-n,p=l+r*d,m=u+r*f,h=(d+p*e)*a,g=(f+m*e)*a;l=(p-r*(d+p*e))*a,u=(m-r*(f+m*e))*a,s=t+h,c=n+g,o.push({sourceTimeMs:i,x:s,y:c})},f=Lc(t),p=[];for(let t=1;t<e.length;t++){let n=e[t-1],r=e[t];if(r.sourceTimeMs-n.sourceTimeMs>50){let e=Math.min(r.sourceTimeMs,n.sourceTimeMs+i),t=Math.max(n.sourceTimeMs,r.sourceTimeMs-f-i);for(let i=n.sourceTimeMs+Vc;i<r.sourceTimeMs;i+=Vc)(i<e||i>=t)&&p.push(i)}p.push(r.sourceTimeMs)}let m=Bc(e),h=a.sourceTimeMs;for(let e of p){let t=m((h+e)/2+f);d(e-h,t.x,t.y,e),h=e}let g=e[e.length-1];for(let e=h+Vc;e<=g.sourceTimeMs+i;e+=Vc)d(e-h,g.x,g.y,e),h=e;return Wc(o,e,n,i)}function Wc(e,t,n,r){let i=[...new Set(n)].sort((e,t)=>e-t);if(i.length===0||r<=0)return e;let a=e.map(e=>({...e}));for(let[e,n]of i.entries()){let o=i[e-1],s=i[e+1],c=Math.min(o===void 0?1/0:(n-o)/2,s===void 0?1/0:(s-n)/2),l=Math.min(r,c);if(!Number.isFinite(l)||l<=0)continue;let u=zc(t,n),d=zc(a,n),f=u.x-d.x,p=u.y-d.y;if(f!==0||p!==0)for(let e of a){let t=Math.abs(e.sourceTimeMs-n);if(t>l)continue;let r=.5*(1+Math.cos(Math.PI*t/l));e.x+=f*r,e.y+=p*r}}return a}function Gc(e,t){let n=e[0]??null;for(let r of e){if(r.sourceTimeMs>t)break;n=r}return n}var Kc=(e,t)=>({x:(e.x-t.offsetX)*t.scale,y:(e.y-t.offsetY)*t.scale}),qc=(e,t)=>({...e,...Kc(e,t),width:e.width*t.scale,height:e.height*t.scale}),Jc=e=>e.scale===1&&e.offsetX===0&&e.offsetY===0;function Yc(e,t){let n=e.viewportTransforms??[];if(n.every(Jc))return n.length===0?{bundle:e,scene:t}:{bundle:{...e,viewportTransforms:[]},scene:t};let r=new Map(e.markers.map(e=>[e.actionId,e.sourceTimeMs])),i=e=>Gc(n,e),a=e=>i((e===void 0?void 0:r.get(e))??0),o={...e,viewportTransforms:[],cursorSamples:e.cursorSamples.map(e=>({...e,...Kc(e,i(e.sourceTimeMs))})),anchorRects:e.anchorRects.map(e=>({...e,rect:qc(e.rect,a(e.actionId))}))};if(t===void 0)return{bundle:o,scene:t};let s=new Map;for(let e of t.actions){let t=`anchorId`in e?e.anchorId:void 0;typeof t==`string`&&!s.has(t)&&s.set(t,e.id)}return{bundle:o,scene:{...t,actions:t.actions.map(e=>`rect`in e&&e.rect!==void 0?{...e,rect:qc(e.rect,a(e.id))}:e),anchors:t.anchors.map(e=>{let t=e.fingerprint.boundingRect;return t?{...e,fingerprint:{...e.fingerprint,boundingRect:qc(t,a(s.get(e.id)))}}:e})}}}function Xc(e,t,n){return t.every(Jc)?[...e]:e.map(e=>{let r=Gc(t,n.get(e.toActionId)??0);return{...e,from:Kc(e.from,r),to:Kc(e.to,r),via:e.via.map(e=>Kc(e,r))}})}function Zc(e){let t=[...e].filter(e=>e.endMs>e.startMs).sort((e,t)=>e.startMs-t.startMs),n=[];for(let e of t){let t=n[n.length-1];t&&e.startMs<=t.endMs?t.endMs=Math.max(t.endMs,e.endMs):n.push({startMs:e.startMs,endMs:e.endMs})}return n}function Qc(e){return e.kind===`keyframeOnly`||e.kind===`surfaceMismatch`||e.kind===`encodeRefused`||e.kind===`motionReclaimed`}function $c(e,t=[]){return Zc([...e.motionSpans.map(e=>({startMs:e.startMs,endMs:e.endMs})),...e.degradations.filter(Qc).map(e=>({startMs:e.startMs,endMs:e.endMs})),...t])}function el(e,t,n){let r=new Map(t.markers.map(e=>[e.actionId,e.sourceTimeMs])),i=[],a=[];for(let t of e.removed??[]){let e=[t.id],o=(e,t)=>{if(e===null)return t;let i=r.get(e.actionId);return i===void 0?`these frames carry no marker for "${e.actionId}", so where this piece ${t===0?`starts`:`ends`} is unknown and no frames were removed`:z(i+e.sourceOffsetMs,0,n)},s=o(t.start,0),c=o(t.end,n);if(typeof s==`string`||typeof c==`string`){a.push({ids:e,reason:typeof s==`string`?s:c});continue}if(c<=s){a.push({ids:e,reason:`this piece's two ends land at the same instant (${Math.round(s)}ms) or out of order, so it covers no frames`});continue}i.push({ids:e,srcStartMs:s,srcEndMs:c,trailing:c>=n})}i.sort((e,t)=>e.srcStartMs-t.srcStartMs);let o=[];for(let e of i){let t=o[o.length-1];if(t&&e.srcStartMs<=t.srcEndMs){t.ids.push(...e.ids),t.srcEndMs=Math.max(t.srcEndMs,e.srcEndMs),t.trailing||=e.trailing;continue}o.push(e)}return{cuts:o,unplacedCuts:a}}function tl(e,t){return e.some(e=>t>e.srcStartMs&&t<=e.srcEndMs)}function nl(e,t){return e.some(e=>t>e.srcStartMs&&t<e.srcEndMs)}var rl=1e-6;function il(e,t,n,r){let i=new Map(t.markers.map(e=>[e.actionId,e.sourceTimeMs]));return e.holds.flatMap(e=>{let t=i.get(e.actionId);if(t===void 0)return[];let a=z(t+e.offsetMs,0,n);return nl(r,a)?[]:[{sourceTimeMs:a,durationMs:Math.max(0,e.durationMs)}]}).sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}function al(e,t,n){let r=0;for(let i of e){let e=Math.max(i.startMs,t),a=Math.min(i.endMs,n);a>e&&(r+=a-e)}return r}function ol(e,t){return e.origin===`authored`?e.idleTargetMs:Math.max(0,e.recordedSpanMs-t)}function sl(e,t,n,r){if(e.paces===null||No(t))return{instants:[],unplacedPaces:0};let i=new Map(t.markers.map(e=>[e.actionId,e.sourceTimeMs])),a=[],o=0;for(let t of e.paces){let e=i.get(t.afterActionId),s=i.get(t.beforeActionId);if(e===void 0||s===void 0){o++;continue}if(tl(r,s))continue;let c=al(n,e,s),l=Math.max(0,s-e-c),u=Math.max(0,ol(t,c)-l);u>0&&a.push({sourceTimeMs:s,durationMs:u})}return{instants:a.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs),unplacedPaces:o}}function cl(e,t,n,r,i){let a=new Set([0,r]);for(let e of t.markers)a.add(e.sourceTimeMs);for(let e of n)a.add(e.startMs),a.add(e.endMs);for(let e of i)a.add(e.srcStartMs),a.add(e.srcEndMs);let o=[...a].filter(e=>e>=0&&e<=r).sort((e,t)=>e-t),s=(e,t)=>n.some(n=>n.startMs<=e&&n.endMs>=t&&t>e),c=[];for(let r=1;r<o.length;r++){let a=o[r-1],l=o[r];if(a===void 0||l===void 0)continue;let u=l-a;if(u<=0||tl(i,(a+l)/2))continue;let d=s(a,l)?`motion`:`idle`,f=d===`motion`?u:dl(e,t,n,i,a,l,u);c.push({srcStartMs:a,srcEndMs:l,kind:d,outDurationMs:f})}return c}function ll(e,t,n,r){if(!No(t)||!e.paces)return;let i=new Map(t.markers.map(e=>[e.actionId,e.sourceTimeMs]));return e.paces.find(e=>{if(e.origin!==`authored`||Po(t,e.afterActionId,e.idleTargetMs))return!1;let a=i.get(e.afterActionId),o=i.get(e.beforeActionId);return a===void 0||o===void 0?!1:a<=n&&r<=o})}function ul(e,t,n,r){let i=new Map(e.markers.map(e=>[e.actionId,e.sourceTimeMs])),a=i.get(r.afterActionId),o=i.get(r.beforeActionId);if(a===void 0||o===void 0)return 0;let s=Zc([...t,...n.map(e=>({startMs:e.srcStartMs,endMs:e.srcEndMs}))]);return Math.max(0,o-a-al(s,a,o))}function dl(e,t,n,r,i,a,o){let s=ll(e,t,i,a);if(!s)return o;let c=ul(t,n,r,s);return c<=0?o:s.idleTargetMs*(o/c)}function fl(e,t){let n=e.findIndex(e=>e.srcStartMs+rl<t&&t<e.srcEndMs-rl);if(n===-1)return e;let r=e[n];if(!r)return e;let i=r.srcEndMs-r.srcStartMs,a=(t-r.srcStartMs)/i,o=r.outDurationMs*a,s={srcStartMs:r.srcStartMs,srcEndMs:t,kind:r.kind,outDurationMs:o},c={srcStartMs:t,srcEndMs:r.srcEndMs,kind:r.kind,outDurationMs:r.outDurationMs-o};return[...e.slice(0,n),s,c,...e.slice(n+1)]}function pl(e,t){if(e.timing!==`real`)return[];let n=[];for(let r of e.degradations){if(r.kind!==`occlusionPause`||r.endMs<=r.startMs)continue;let e=[{startMs:r.startMs,endMs:r.endMs}];for(let n of t)e=e.flatMap(e=>e.endMs<=n.srcStartMs||e.startMs>=n.srcEndMs?[e]:[...e.startMs<n.srcStartMs?[{startMs:e.startMs,endMs:n.srcStartMs}]:[],...e.endMs>n.srcEndMs?[{startMs:n.srcEndMs,endMs:e.endMs}]:[]]);n.push(...e)}return Zc(n)}function ml(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n];!r||!i||i.sourceTimeMs<=r.sourceTimeMs||Math.hypot(i.x-r.x,i.y-r.y)<.5||t.push({startMs:r.sourceTimeMs,endMs:i.sourceTimeMs})}return t}function hl(e){let t=e.keyframes[e.keyframes.length-1],n=ml(Yc(e,void 0).bundle.cursorSamples).at(-1),r=e.source===`capture`?Rc(55):0;return Math.max(t?.sourceTimeMs??0,...e.markers.map(e=>e.sourceTimeMs),...$c(e).map(e=>e.endMs),n===void 0?0:n.endMs+r)}function gl(e,t,n=[]){let r=$c(t,n),i=hl(t),{cuts:a,unplacedCuts:o}=el(e,t,i),s=pl(t,a),c=[...a,...s.map(e=>({ids:[],srcStartMs:e.startMs,srcEndMs:e.endMs,trailing:!1}))].sort((e,t)=>e.srcStartMs-t.srcStartMs),l=il(e,t,i,a),{instants:u,unplacedPaces:d}=sl(e,t,r,a),f=(e.paces??[]).filter(e=>e.origin===`recorded`&&e.recordedSpanMs<0).length,p=cl(e,t,r,i,c);for(let e of l)p=fl(p,e.sourceTimeMs);for(let e of u)p=fl(p,e.sourceTimeMs);let m=[],h=0,g=e=>{for(let t of l)Math.abs(t.sourceTimeMs-e)>rl||(m.push({outStartMs:h,outEndMs:h+t.durationMs,srcStartMs:e,srcEndMs:e,kind:`hold`}),h+=t.durationMs)},_=e=>{for(let t of u)Math.abs(t.sourceTimeMs-e)>rl||(m.push({outStartMs:h,outEndMs:h+t.durationMs,srcStartMs:e,srcEndMs:e,kind:`pace`}),h+=t.durationMs)},v=e=>a.some(t=>Math.abs(t.srcStartMs-e)<=rl);for(let e of p)g(e.srcStartMs),_(e.srcStartMs),m.push({outStartMs:h,outEndMs:h+e.outDurationMs,srcStartMs:e.srcStartMs,srcEndMs:e.srcEndMs,kind:e.kind}),h+=e.outDurationMs,v(e.srcEndMs)&&(g(e.srcEndMs),_(e.srcEndMs));return g(i),_(i),{segments:m,outputDurationMs:h,sourceDurationMs:i,cuts:a,unplacedCuts:o,interruptions:s,unplacedPaces:d,nonMonotonicPaces:f}}function _l(e,t){if(e.segments.length===0)return 0;let n=e.segments[0],r=e.segments[e.segments.length-1];if(t<=0)return n?.srcStartMs??0;if(t>=e.outputDurationMs)return r?.srcEndMs??e.sourceDurationMs;for(let n of e.segments)if(t<=n.outEndMs){let e=n.outEndMs-n.outStartMs,r=e===0?0:(t-n.outStartMs)/e;return n.srcStartMs+(n.srcEndMs-n.srcStartMs)*r}return e.sourceDurationMs}function vl(e,t){if(e.segments.length===0||t<=0)return 0;if(t>=e.sourceDurationMs)return e.outputDurationMs;let{segments:n}=e;for(let e=0;e<n.length;e++){let r=n[e];if(t<=r.srcEndMs){let i=e+1;for(;n[i]?.kind===`pace`&&n[i]?.srcStartMs===t;)i++;if(i>e+1)return n[i-1].outEndMs;let a=r.srcEndMs-r.srcStartMs,o=a===0?0:z((t-r.srcStartMs)/a,0,1);return r.outStartMs+(r.outEndMs-r.outStartMs)*o}}return e.outputDurationMs}function yl(e,t,n){let r=n.get(e.actionId);return r===void 0?null:vl(t,r)+e.offsetMs}function bl(e,t,n){let r=1/0,i=-1/0;for(let a of e.segments){let e=Math.max(t,a.srcStartMs),o=Math.min(n,a.srcEndMs);if(e>o)continue;let s=a.srcEndMs-a.srcStartMs,c=(e,t)=>s===0?t:a.outStartMs+(a.outEndMs-a.outStartMs)*(e-a.srcStartMs)/s;r=Math.min(r,c(e,a.outStartMs)),i=Math.max(i,c(o,a.outEndMs))}return r<=i?{startMs:r,endMs:i}:null}function xl(e){let{timeline:t}=e,n=[],r=(t,r,i)=>{let a=e.markerSourceMs.get(t.actionId);return a===void 0?(n.push(r),i):a+t.sourceOffsetMs},i=r(e.start,`start`,0),a=r(e.end,`end`,t.sourceDurationMs),o=bl(t,i,a);if(o!==null&&o.endMs>o.startMs)return{range:o,unplaced:n,clamped:null};let s=o?.startMs??z(vl(t,i),0,t.outputDurationMs),c=a<i?`mask "${e.id}" ends ${Math.round(i-a)}ms before it starts in the recording, so it covers nothing`:`mask "${e.id}" covers no frame of the video: every frame between its ends was removed`;return{range:{startMs:s,endMs:s},unplaced:n,clamped:{id:e.id,kind:`mask`,note:c}}}function Sl(e){let{timeline:t}=e,n=t.outputDurationMs,r=[],i=e.start?yl(e.start,t,e.markerSourceMs):0,a=e.end?yl(e.end,t,e.markerSourceMs):n;e.start&&i===null&&r.push(`start`),e.end&&a===null&&r.push(`end`);let o=z(i??0,0,n),s=z(a??n,0,n),c=e.start!==null||e.end!==null;if(s<=o&&c){let t=s<o?`${e.kind} "${e.id}" ends ${Math.round(o-s)}ms before it starts, so it was cut to nothing — a pause between its two steps was shortened after it was placed`:`${e.kind} "${e.id}" starts and ends at the same instant (${Math.round(o)}ms), so it covers nothing — the pause between its two steps was cut to nothing after it was placed, or both its ends were pushed off the end of a shortened take`;return{range:{startMs:o,endMs:o},unplaced:r,clamped:{id:e.id,kind:e.kind,note:t}}}return{range:{startMs:o,endMs:s},unplaced:r,clamped:null}}function Cl(e){if(!(Number.isFinite(e)&&e>=0&&e<=1))throw RangeError(`motion smoothness must be within 0..1, got ${e}`);return{stiffness:Vo(8,5.5,e),zoomInMs:Vo(1e3,1600,e),zoomOutMs:Vo(700,1150,e),followRatePerS:Vo(13,7,e)}}var wl=Cl(Ys.smoothness),Tl={defaultZoomScale:1.8,verticalMaxScale:1.15,fitMarginPx:24,leadInMs:-350,actSettleMs:400,zoomInMs:wl.zoomInMs,zoomOutMs:wl.zoomOutMs,stiffness:wl.stiffness,maxScale:2.5,neutral:{minPlateauMs:250,zoomHoldMs:1200}};function El(e,t,n){let r=new Map(e.actions.map((e,t)=>[e.id,t])),i=new Map(e.actions.map(e=>[e.id,e])),a=e=>{let t=i.get(e.marker.actionId);if(e.point===void 0||t?.kind!==`drag`)return{};let n=dc(t,t.rect,t.toRect);if(n===null)return{};let r=Math.min(n.start.x,n.end.x),a=Math.min(n.start.y,n.end.y);return{fit:{x:r,y:a,width:Math.max(n.start.x,n.end.x)-r,height:Math.max(n.start.y,n.end.y)-a}}};return e.camera.flatMap(e=>t.has(e.marker.actionId)?(n.push({id:e.id,kind:`zoom`,actionId:e.marker.actionId}),[]):[e]).map(e=>({id:e.id,kind:e.kind,anchorId:e.anchorId??null,point:e.point??null,actionId:e.marker.actionId,offsetMs:e.marker.offsetMs,scale:z(e.scale??1,1,Tl.maxScale),end:e.end??null,...a(e)})).filter(e=>e.scale>1).sort((e,t)=>{let n=(r.get(e.actionId)??0)-(r.get(t.actionId)??0);return n===0?e.offsetMs-t.offsetMs:n})}function Dl(e,t,n,r,i,a=null,o=Ys,s=new Map,c=[]){let l=Cl(o.smoothness),u={x:i.width/2,y:i.height/2},d=[],f=new Map;for(let i of e){let e=i.point?{x:i.point.x,y:i.point.y,width:0,height:0}:i.anchorId?t(i.anchorId,i.actionId):null;if(!e)continue;let o=r.get(i.actionId);if(o===void 0)continue;let c=vl(n,o),u=Math.max(0,c+i.offsetMs),p=i.end?yl(i.end,n,r):null,m=z(i.scale,1,Tl.maxScale),h=Math.max(m,z(i.requestedScale??i.scale,1,Tl.maxScale)),g=a===null?m:z(Ol(i.fit??e,a),1,m),_=-1/0;for(let[e,t]of s){let i=r.get(e);i===void 0||i>=o||(_=Math.max(_,vl(n,t)))}let v={id:i.id,outputTimeMs:u,center:Bo(e),scale:g,transitionMs:l.zoomInMs,stiffness:l.stiffness,zoom:!0,authoredEndMs:p,endUnplaced:i.end!==null&&p===null,fitted:g<h?{from:h,to:g,cap:m<h?m:null}:null,actionMs:c,plannedTransitionMs:l.zoomInMs};d.push(v),f.set(v,_)}d.sort((e,t)=>e.outputTimeMs-t.outputTimeMs);for(let[e,t]of d.entries()){let n=d[e-1],r=n!==void 0&&!Al(kl(n,t.actionMs,c),t.outputTimeMs,l),i=(f.get(t)??-1/0)+(r?0:Tl.actSettleMs);t.outputTimeMs-l.zoomInMs<i&&(t.transitionMs=Math.max(150,Math.min(l.zoomInMs,t.outputTimeMs-i)))}return Ml([{id:``,outputTimeMs:0,center:u,scale:1,transitionMs:0,stiffness:l.stiffness,zoom:!1,authoredEndMs:null,endUnplaced:!1,fitted:null,actionMs:0,plannedTransitionMs:0},...d].sort((e,t)=>e.outputTimeMs-t.outputTimeMs),n.outputDurationMs,l,c)}function Ol(e,t){let n=2*Tl.fitMarginPx,r=Math.min(t.width/(e.width+n),t.height/(e.height+n));return Math.floor(r*100)/100}function kl(e,t,n){let r=Math.min(e.outputTimeMs+Tl.neutral.zoomHoldMs,t);return Math.max(e.outputTimeMs,...n.filter(t=>t.startMs>=e.actionMs&&t.startMs<r).map(e=>e.endMs))}function Al(e,t,n){let{minPlateauMs:r}=Tl.neutral;return t-n.zoomInMs-r>=e+r+n.zoomOutMs}function jl(e,t){return e+Tl.neutral.zoomHoldMs+t.zoomOutMs}function Ml(e,t,n,r=[]){let{neutral:i}=Tl,{zoomOutMs:a}=n,o=[],s=[],c=({outputTimeMs:e,center:t,scale:n,transitionMs:r,stiffness:i})=>({outputTimeMs:e,center:t,scale:n,transitionMs:r,stiffness:i}),l=(e,t)=>({outputTimeMs:e,center:t,scale:1,transitionMs:a,stiffness:n.stiffness});for(let[u,d]of e.entries()){let f=o[o.length-1]?.outputTimeMs??d.outputTimeMs,p=Math.max(f,d.outputTimeMs-d.transitionMs);if(o.push(c(d)),!d.zoom)continue;let m=e[u+1],h=kl(d,m?.actionMs??1/0,r),g=h+i.minPlateauMs+a,_=jl(h,n),v=d.authoredEndMs??_,y=d.authoredEndMs!==null,b=y||d.endUnplaced,x=e=>y&&Math.abs(e-v)>1e-6;if(!m){let e=Math.min(Math.max(v,g),t);if(e<=d.outputTimeMs){s.push({id:d.id,departMs:p,startMs:d.outputTimeMs,endMs:t,endAuthored:b,endClamped:x(t),endUnplaced:d.endUnplaced,fitted:d.fitted});continue}o.push(l(e,d.center)),s.push({id:d.id,departMs:p,startMs:d.outputTimeMs,endMs:e,endAuthored:b,endClamped:x(e),endUnplaced:d.endUnplaced,fitted:d.fitted});continue}let S=m.outputTimeMs-m.plannedTransitionMs-i.minPlateauMs;if(!Al(h,m.outputTimeMs,{zoomInMs:m.plannedTransitionMs,zoomOutMs:a})){let t=Math.max(d.outputTimeMs,d.actionMs,h)+i.minPlateauMs;e[u+1]={...m,transitionMs:Math.max(150,Math.min(m.transitionMs,m.outputTimeMs-t))},s.push({id:d.id,departMs:p,startMs:d.outputTimeMs,endMs:m.outputTimeMs,endAuthored:b,endClamped:x(m.outputTimeMs),endUnplaced:d.endUnplaced,fitted:d.fitted});continue}let C=Math.min(Math.max(v,g),S);o.push(l(C,Ho(d.center,m.center,.5))),s.push({id:d.id,departMs:p,startMs:d.outputTimeMs,endMs:C,endAuthored:b,endClamped:x(C),endUnplaced:d.endUnplaced,fitted:d.fitted})}return{keys:o,segments:s}}function Nl(e,t,n,r){let i=t>0?t:1,a=Math.min(n.width/i,r.width)/2,o=Math.min(n.height/i,r.height)/2;return{x:z(e.x,a,r.width-a),y:z(e.y,o,r.height-o)}}function Pl(e,t,n,r,i){let{scale:a}=e,o=Nl(e.center,t,n,r),s=Bo(n),c={x:s.x+(e.center.x-o.x)*t,y:s.y+(e.center.y-o.y)*t},l=a>0?a:1,u=Math.min(i.width/l,i.width)/2,d=Math.min(i.height/l,i.height)/2,f={x:z(c.x,u,i.width-u),y:z(c.y,d,i.height-d)};return{center:{x:o.x+(f.x-s.x)/t,y:o.y+(f.y-s.y)/t},scale:a,pan:o,focus:f}}function Fl(e,t,n){let r=e.scale*(t.scale/e.scale)**n,i=1/e.scale-1/t.scale,a=Math.abs(i)<1e-9?n:(1/e.scale-1/r)/i;return{center:Ho(e.center,t.center,a),scale:r}}function Il(e,t){let n=e[0];if(!n)return{center:{x:0,y:0},scale:1};if(t<=n.outputTimeMs)return{center:n.center,scale:n.scale};let r=e[e.length-1];if(!r)return{center:{x:0,y:0},scale:1};if(t>=r.outputTimeMs)return{center:r.center,scale:r.scale};for(let n=1;n<e.length;n++){let r=e[n],i=e[n-1];if(!r||!i||t>r.outputTimeMs)continue;let a=r.outputTimeMs-i.outputTimeMs,o=Math.min(r.transitionMs,a);return Fl(i,r,qo(z(o<=0?1:(t-(r.outputTimeMs-o))/o,0,1),r.stiffness))}return{center:r.center,scale:r.scale}}function Ll(e,t){let n=e[t],r=e[t-1];return r?n.outputTimeMs-Math.min(n.transitionMs,n.outputTimeMs-r.outputTimeMs):n.outputTimeMs}function Rl(e){let{keys:t,cursorAt:n,holds:r,outputDurationMs:i}=e,a=e.rate/1e3,o=e=>r.some(t=>t.startMs<=e&&e<t.endMs),s=[];for(let e=1;e<t.length;e++){let r=t[e];if(r.scale<=1||t[e-1].scale>1)continue;let c=e;for(;(t[c+1]?.scale??0)>1;)c++;let l=c+1<t.length?c+1:null,u=l===null?i:t[l].outputTimeMs,d=l===null?i:Ll(t,l),f=t.slice(e+1,c+1).map((n,r)=>({at:Ll(t,e+1+r),center:n.center})),p=-1,m=e=>{for(;p+1<f.length&&(f[p+1]?.at??1/0)<=e;)p++;return f[p]?.center??r.center},h=e=>(n!==null&&!o(e)?n(e):null)??m(e),g=r.center,_={x:0,y:0},v=[g];for(let e=r.outputTimeMs;e<u;e+=8){let t=h(e),n=Math.min(8,u-e),r=Math.exp(-a*n),i=(e,t)=>{let i=t+a*e;return{y:(e+i*n)*r,v:(t-a*i*n)*r}},o=i(g.x-t.x,_.x),s=i(g.y-t.y,_.y);g={x:t.x+o.y,y:t.y+s.y},_={x:o.v,y:s.v},v.push(g)}s.push({startMs:r.outputTimeMs,pullOutDepartMs:d,endMs:u,centers:v}),e=c}return s}function zl(e,t,n=e=>e){let r=e.cameraKeys.map(e=>({...e,center:n(e.center,e.scale)})),i=Il(r,t);if(i.scale<=1)return i;let a=e.cameraFollow.find(e=>e.startMs<=t&&t<=e.endMs);if(!a)return i;let o=a.centers.length-1,s=Math.min(Math.floor((t-a.startMs)/8),o),c=e=>Math.min(a.startMs+e*8,a.endMs),l=a.centers[s],u=a.centers[s+1],d=u===void 0?l:Ho(l,u,(t-c(s))/(c(s+1)-c(s)));if(t<a.pullOutDepartMs)return{center:n(d,i.scale),scale:i.scale};let f=Il(r,a.pullOutDepartMs).scale;if(f<=1)return i;let p=Il(r,a.endMs).center,m=(1/f-1/i.scale)/(1/f-1);return{center:Ho(n(d,f),p,m),scale:i.scale}}function Bl(e,t,n,r,i,a){return Pl(zl(e,t,(e,t)=>Pl({center:e,scale:t},n,r,i,a).center),n,r,i,a)}var Vl={minDurationMs:480,maxDurationMs:1400,baseMs:360,msPerPx:.7,dwellMs:300,hoverDwellMs:450,bowFraction:.08};function Hl(e,t){let n=Wo(e,t);return Math.round(z(Vl.baseMs+Vl.msPerPx*n,Vl.minDurationMs,Vl.maxDurationMs))}function Ul(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i);if(a===0)return{x:e.x,y:e.y};let o=n%2==0?1:-1,s=a*Vl.bowFraction*o;return{x:e.x+r/2-i/a*s,y:e.y+i/2+r/a*s}}function Wl(e,t){return Ko(e.via,z(t,0,1))}function Gl(e,t){return{x:z(e.x-t.width*.25,0,t.width),y:z(e.y+t.height*.3,0,t.height)}}function Kl(e){let{from:t,to:n}=e;return{fromActionId:e.fromActionId,toActionId:e.toActionId,from:t,to:n,via:[t,Ul(t,n,e.index),n],durationMs:Hl(t,n),easing:`minimumJerk`,dwellMs:e.dwellMs??Vl.dwellMs}}function ql(e,t){let n=e.actions.flatMap(e=>{if(e.anchorId===null||!bo[e.kind].cursorTravels)return[];let n=t(e.anchorId,e.id);return n?[{action:e,point:sc(n,e.kind===`click`?e.at:void 0)}]:[]});if(n.length===0)return[];let r=e.flags.hoverSensitive?Vl.hoverDwellMs:Vl.dwellMs,i=n[0],a=Gl(i.point,e.meta.capture.viewport),o=null;return n.map((e,t)=>{let n=e.point,i=Kl({from:a,to:n,index:t,fromActionId:o,toActionId:e.action.id,dwellMs:r});return a=n,o=e.action.id,i})}function Jl(e,t,n){let r=[0];for(let i=t+1;i<=n;i++){let t=e[i-1],n=e[i];r.push(r[r.length-1]+Math.hypot(n.x-t.x,n.y-t.y))}return r}function Yl(e,t,n,r,i){for(let a=t+1;a<=n;a++){let n=e[a];if(n.sourceTimeMs<i)continue;let o=e[a-1],s=n.sourceTimeMs-o.sourceTimeMs,c=s===0?0:(i-o.sourceTimeMs)/s,l=r[a-1-t];return l+(r[a-t]-l)*c}return r[r.length-1]}function Xl(e,t,n,r,i){for(let a=t+1;a<=n;a++){let n=r[a-t];if(n<i)continue;let o=r[a-1-t],s=e[a-1],c=e[a],l=n-o,u=l===0?0:(i-o)/l;return{x:s.x+(c.x-s.x)*u,y:s.y+(c.y-s.y)*u}}let a=e[n];return{x:a.x,y:a.y}}function Zl(e,t){let n=e.length,r=[];for(let i=1;i<n;i++){let n=e[i]-e[i-1];r.push(n===0?0:(t[i]-t[i-1])/n)}let i=Array(n).fill(0);i[0]=r[0]??0,i[n-1]=r[n-2]??0;for(let t=1;t<n-1;t++){let n=r[t-1],a=r[t];if(n<=0||a<=0)continue;let o=e[t]-e[t-1],s=e[t+1]-e[t];i[t]=3*(o+s)/((2*s+o)/n+(s+2*o)/a)}return i}function Ql(e,t,n,r){for(let i=1;i<e.length;i++){let a=e[i];if(a<r)continue;let o=e[i-1],s=a-o;if(s<=0)return t[i];let c=(r-o)/s,l=c*c,u=l*c;return t[i-1]*(2*u-3*l+1)+n[i-1]*s*(u-2*l+c)+t[i]*(-2*u+3*l)+n[i]*s*(u-l)}return t[t.length-1]}var $l=.4;function eu(e,t,n,r,i){let a=t-e,o=+!!n+ +!!r;if(o===0||a<=0)return i;let s=Math.min($l*a,350),c=a/(a-o*s/2),l=e=>e*e*e-e*e*e*e/2,u=i-e;return n&&u<s?e+c*s*l(u/s):r&&u>a-s?t-c*s*l((a-u)/s):e+c*(u-(n?s/2:0))}function tu(e,t,n,r,i,a){if(n-t<2)return;let o=e[t],s=e[n];if(s.sourceTimeMs<=o.sourceTimeMs)return;let c=Jl(e,t,n);if(c[c.length-1]<=0)return;let l=[...new Set(r.filter(e=>e>o.sourceTimeMs&&e<s.sourceTimeMs))].sort((e,t)=>e-t),u=[o.sourceTimeMs,...l,s.sourceTimeMs],d=u.map(r=>Yl(e,t,n,c,r)),f=Zl(u,d),p=u[0],m=u[u.length-1],h=u[1],g=u[u.length-2];for(let r=t+1;r<n;r++){let o=e[r],s=o.sourceTimeMs,l=Xl(e,t,n,c,Ql(u,d,f,s<=h?eu(p,h,i.in,h===m&&i.out,s):s>=g?eu(g,m,!1,i.out,s):s));a[r]={sourceTimeMs:o.sourceTimeMs,x:l.x,y:l.y}}}function nu(e,t,n,r=[],i){if(e.length<3)return e;let a=e=>i===void 0||e.x>=0&&e.x<=i.width&&e.y>=0&&e.y<=i.height,o=[...e],s=0,c=!1;for(let i=1;i<=e.length;i++){let l=e[i],u=e[i-1],d=l!==void 0&&Lo(r,u.sourceTimeMs,l.sourceTimeMs);(l===void 0||d||l.sourceTimeMs-u.sourceTimeMs>n)&&(tu(e,s,i-1,t,{in:!c&&a(e[s]),out:!d&&a(u)},o),s=i,c=d)}return o}var ru=48,iu=.05,au=.5,ou=.25;function su(e,t,n){let r=Math.hypot(t.x,t.y);if(e.x>=0&&e.x<=n.width&&e.y>=0&&e.y<=n.height&&r>=iu){let i={x:t.x/r,y:t.y/r},a=24+r*50;if(cu(e,i,n)<=a)return i}let i=[[e.x,{x:-1,y:0}],[n.width-e.x,{x:1,y:0}],[e.y,{x:0,y:-1}],[n.height-e.y,{x:0,y:1}]],a=i[0];for(let e of i)e[0]<a[0]&&(a=e);return a[0]<=24?a[1]:null}function cu(e,t,n){let r=(e,t,n)=>t>0?(n-e)/t:t<0?-e/t:1/0,i=Math.min(r(e.x,t.x,n.width),r(e.y,t.y,n.height));return e.x>=0&&e.x<=n.width&&e.y>=0&&e.y<=n.height?Math.max(0,i):0}function lu(e,t,n){if(n===`before`){let n=e.length-1;for(;n>=0&&e[n].sourceTimeMs>t;)n--;let r=e[n];if(!r)return null;let i=n;for(;i>0&&r.sourceTimeMs-e[i-1].sourceTimeMs<=ru;)i--;return{at:r,velocity:uu(e[i],r)}}let r=0;for(;r<e.length&&e[r].sourceTimeMs<t;)r++;let i=e[r];if(!i)return null;let a=r;for(;a<e.length-1&&e[a+1].sourceTimeMs-i.sourceTimeMs<=ru;)a++;return{at:i,velocity:uu(i,e[a])}}function uu(e,t){if(!e||!t)return{x:0,y:0};let n=t.sourceTimeMs-e.sourceTimeMs;return n>0?{x:(t.x-e.x)/n,y:(t.y-e.y)/n}:{x:0,y:0}}function du(e,t,n,r){let i=Math.max(n,au);return{speed:i,ms:(cu(e,t,r)+ou*Math.max(r.width,r.height))/i}}function fu(e,t,n,r){return{x:e.x+t.x*n*r,y:e.y+t.y*n*r}}var pu=8;function mu(e,t,n,r){let i=[],a=r-t;for(let o=t+pu;o<r;o+=pu)i.push({sourceTimeMs:o,...Ho(e,n,(o-t)/a)});return i}function hu(e,t,n){if(e.length===0)return{samples:e,gaps:t};let r=[],i=[];for(let a of t){let t=lu(e,a.startMs,`before`),o=t!==null&&a.startMs-t.at.sourceTimeMs>50,s=t===null||o?{x:0,y:0}:t.velocity,c=t?su(t.at,s,n):null;if(!t||!c){i.push(a);continue}let l=t.at,u=du(l,c,gu(s),n),d=t.at.sourceTimeMs;o&&(d=Math.max(d,a.startMs-cu(l,c,n)/u.speed),r.push({sourceTimeMs:d,x:l.x,y:l.y}));let f=lu(e,a.endMs,`after`),p=f?su(f.at,_u(f.velocity),n):null,m=f&&p?du(f.at,p,gu(f.velocity),n):null;if(f&&m&&p){let e=f.at.sourceTimeMs,t=Math.min(1,(e-d-1)/(u.ms+m.ms)),n=u.ms*t,a=fu(l,c,u.speed,n);r.push(...mu(l,d,a,d+n)),r.push({sourceTimeMs:d+n,x:a.x,y:a.y});let o=c.x*p.x+c.y*p.y>.7;if(t<1&&o){r.push(...mu(a,d+n,f.at,e));continue}let s=m.ms*t,h=e-s,g=fu(f.at,p,m.speed,s);r.push({sourceTimeMs:h,x:g.x,y:g.y}),r.push(...mu(g,h,f.at,e)),i.push({startMs:d+n,endMs:h});continue}let h=Math.min(u.ms,Math.max(0,a.endMs-1-d)),g=fu(l,c,u.speed,h);r.push(...mu(l,d,g,d+h)),r.push({sourceTimeMs:d+h,x:g.x,y:g.y}),i.push({startMs:d+h,endMs:a.endMs})}let a=e[0],o=a.sourceTimeMs>0?lu(e,a.sourceTimeMs,`after`):null,s=o?su(o.at,_u(o.velocity),n):null;if(o&&s){let e=du(a,s,gu(o.velocity),n),t=fu(a,s,e.speed,e.ms),i=Math.max(0,a.sourceTimeMs-e.ms);r.push({sourceTimeMs:i,x:t.x,y:t.y}),r.push(...mu(t,i,a,a.sourceTimeMs))}let c=o&&s?i.filter(e=>e.endMs>a.sourceTimeMs):i;return r.length===0?{samples:e,gaps:t}:{samples:[...e,...r].sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs),gaps:c}}var gu=e=>Math.hypot(e.x,e.y),_u=e=>({x:-e.x,y:-e.y}),vu=`1.1.0`;function yu(e){return e.edits.masks.map(e=>({id:e.id,kind:`mask`,rect:e.rect,range:e.start&&e.end?{start:e.start,end:e.end}:null}))}var bu={motionDiffThreshold:.02};function xu(e,t={}){let n=new Map;for(let t of e.anchors){let e=t.fingerprint.boundingRect;e&&n.set(t.id,e)}let r=new Map;for(let t of e.actions)t.rect&&r.set(t.id,t.rect);let i=(e,t)=>r.get(t)??n.get(e)??null,a=e.actions[e.actions.length-1],o=e.edits.removed??[],s=fc(e),c=[],l=new Map((e.edits.gaps??[]).map(e=>[e.afterActionId,e])),u=[];for(let t=0;t+1<e.actions.length;t++){let n=e.actions[t],r=e.actions[t+1];if(!n||!r)continue;let i=l.get(n.id),a={afterActionId:n.id,beforeActionId:r.id};u.push(i?{...a,origin:`authored`,idleTargetMs:i.durationMs}:{...a,origin:`recorded`,recordedSpanMs:r.timestamp-n.timestamp})}return{planVersion:1,compositorVersion:vu,sceneId:e.meta.id,viewport:e.meta.capture.viewport,cursorSegments:ql(e,i),cameraIntents:El(e,s,c),cosmetics:yu(e),holds:(e.edits.holds??[]).flatMap(e=>s.has(e.marker.actionId)?(c.push({id:e.id,kind:`hold`,actionId:e.marker.actionId}),[]):[{id:e.id,actionId:e.marker.actionId,offsetMs:e.marker.offsetMs,durationMs:e.durationMs}]),paces:u,removed:o,removedSteps:[...s],attachedToCuts:c,trim:{head:e.edits.trim?.head??null,tail:e.edits.trim?.tail??null},retiming:{...bu,...t.retiming},hoverSensitive:e.flags.hoverSensitive,durationHintMs:a?.timestamp??0}}function Su(e,t){let n=e[0];if(!n)return null;if(t<=n.sourceTimeMs)return{x:n.x,y:n.y};let r=e[e.length-1];if(!r)return null;if(t>=r.sourceTimeMs)return{x:r.x,y:r.y};let i=0,a=e.length-1;for(;a-i>1;){let n=i+a>>1,r=e[n];if(!r)break;r.sourceTimeMs<t?i=n:a=n}let o=e[i],s=e[a];if(!o||!s)return{x:r.x,y:r.y};let c=s.sourceTimeMs-o.sourceTimeMs,l=c===0?0:(t-o.sourceTimeMs)/c;return Ho({x:o.x,y:o.y},{x:s.x,y:s.y},l)}var Cu=.01;function wu(e,t){if(t.length===0)return e;let n=e[0],r=t.filter(e=>n!==void 0&&e.startMs>=n.sourceTimeMs),i=r.flatMap(t=>{let n=Su(e,t.startMs);return n===null?[]:[{gap:t,before:n}]}),a=e.filter(e=>!r.some(t=>e.sourceTimeMs>t.startMs&&e.sourceTimeMs<t.endMs));for(let{gap:e,before:t}of i)a.push({sourceTimeMs:e.startMs,x:t.x,y:t.y}),a.push({sourceTimeMs:Math.max(e.startMs,e.endMs-Cu),x:t.x,y:t.y});return a.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}function Tu(e,t,n=[]){if(t<=0)return e;let r=[];for(let[i,a]of e.entries()){r.push(a);let o=e[i+1];if(!o||o.sourceTimeMs-a.sourceTimeMs<=t)continue;let s=Math.min(o.sourceTimeMs-1,...n.filter(e=>e.startMs>=a.sourceTimeMs&&e.startMs<o.sourceTimeMs).map(e=>e.startMs));s<=a.sourceTimeMs||r.push({sourceTimeMs:s,x:a.x,y:a.y})}return r}var Eu=120;function Du(e,t){let n=[],r=e.hoverSensitive?Go.easeInOutSine:Go.minimumJerk;for(let i of e.cursorSegments){let e=t.get(i.toActionId);if(e===void 0)continue;let a=(i.fromActionId===null?0:t.get(i.fromActionId))??0,o=Math.max(0,a,e-i.dwellMs-i.durationMs),s=Math.max(0,Math.min(i.durationMs,e-o)),c=Math.max(2,Math.round(s/1e3*Eu));for(let e=0;e<=c;e++){let t=e/c,a=Wl(i,r(t));n.push({sourceTimeMs:o+s*t,x:a.x,y:a.y})}n.push({sourceTimeMs:e,x:i.to.x,y:i.to.y})}return n.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}var Ou=1e3;function ku(e,t,n){if(t.cuts.length===0||e.length===0)return e;let r=[];for(let i of t.cuts){if(i.trailing||i.srcStartMs<=0)continue;let a=Su(e,i.srcStartMs);if(a===null)continue;let o=_l(t,vl(t,i.srcStartMs)+n),s=t.cuts.filter(e=>e.srcStartMs>i.srcEndMs).reduce((e,t)=>Math.min(e,t.srcStartMs),1/0),c=Math.min(o,s);if(c<=i.srcEndMs)continue;let l=Su(e,c);l!==null&&r.push({fromMs:i.srcEndMs,toMs:c,from:a,to:l})}if(r.length===0)return e;let i=e.filter(e=>!r.some(t=>e.sourceTimeMs>=t.fromMs&&e.sourceTimeMs<t.toMs));for(let e of r)i.push({sourceTimeMs:e.fromMs,x:e.from.x,y:e.from.y}),i.push({sourceTimeMs:e.toMs,x:e.to.x,y:e.to.y});return i.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}function Au(e,t,n){let r=[],i=null;for(let t=1;t<e.length;t++){let n=e[t-1],a=e[t];if(!(!n||!a)){if(!(Math.hypot(a.x-n.x,a.y-n.y)>=.5)){i??=n.sourceTimeMs;continue}i!==null&&(r.push({startMs:i,endMs:n.sourceTimeMs}),i=null)}}let a=e[e.length-1];i!==null&&a&&r.push({startMs:i,endMs:a.sourceTimeMs});let o=[...n].sort((e,t)=>e-t),s=[];for(let e of r){let n=vl(t,e.startMs),r=vl(t,e.endMs);if(r-n<1e3)continue;let i=n;for(let e of o)e<=i||e>=r||(s.push({startMs:i,endMs:e}),i=e);s.push({startMs:i,endMs:r})}return s}function ju(e){let t=e-Ou;return t<=0?1:Math.max(0,1-t/250)}function Mu(e,t){for(let n of e){if(t>=n.startMs&&t<n.endMs)return ju(t-n.startMs);let e=t-n.endMs;if(e>=0&&e<250){let t=ju(n.endMs-n.startMs);return t+(1-t)*(e/250)}}return 1}function Nu(e){return String(Number(e.toFixed(2)))}function Pu(e){let{keys:t,plan:n,bundle:r,timeline:i,cursor:a,motion:o}=e,s=new Set(n.cameraIntents.map(e=>e.actionId));return Rl({keys:t,cursorAt:o.follow&&e.drawsPointer?e=>Su(a,_l(i,e)):null,holds:(r.heldPresses??[]).filter(e=>s.has(e.actionId)).map(e=>({startMs:vl(i,e.pressMs),endMs:vl(i,e.releaseMs)})),outputDurationMs:i.outputDurationMs,rate:Cl(o.smoothness).followRatePerS})}function Fu(e,t,n,r=[],i=null){let a=e,{bundle:o,scene:s}=Yc(t,n),c=new Map;for(let e of s?.anchors??[])e.fingerprint.boundingRect&&c.set(e.id,e.fingerprint.boundingRect);let l=new Map;for(let e of o.anchorRects)l.set(e.actionId,e.rect);let u=(e,t)=>l.get(t)??c.get(e)??null,d=new Map(o.markers.map(e=>[e.actionId,e.sourceTimeMs])),f=o.source===`capture`?hu(o.cursorSamples,o.cursorGaps,a.viewport):{samples:o.cursorSamples,gaps:o.cursorGaps},p=o.source===`capture`?Ic(Tu(f.samples,50,f.gaps),30,o.markers.map(e=>e.sourceTimeMs),f.gaps):f.samples,m=f.samples.length>0?wu(p,f.gaps):Du({...a,cursorSegments:Xc(a.cursorSegments,t.viewportTransforms??[],d)},d),h=o.markers.map(e=>e.sourceTimeMs),g=o.source===`capture`&&f.samples.length>0?wu(Hc(nu(p,h,50,f.gaps,a.viewport),55,h,f.gaps),f.gaps):m,_=o.source===`capture`?Rc(55):0,v=o.source===`capture`?Lc(55):0,y=[...r,...ml(m).map(e=>({startMs:Math.max(0,e.startMs-v),endMs:e.endMs+_}))],b=gl(a,o,y),x=new Set(b.unplacedCuts.flatMap(e=>e.ids));if(x.size>0&&n!==void 0){let e=xu({...n,edits:{...n.edits,removed:(n.edits.removed??[]).filter(e=>!x.has(e.id))}},{retiming:a.retiming});a={...a,cameraIntents:e.cameraIntents,cosmetics:e.cosmetics,holds:e.holds,removedSteps:e.removedSteps,attachedToCuts:e.attachedToCuts},b=gl(a,o,y)}let S=ku(g,b,250),C=Sl({id:`trim`,kind:`trim`,start:a.trim.head,end:a.trim.tail,timeline:b,markerSourceMs:d}),w=C.clamped?[C.clamped]:[],T=s?.motion??Ys,ee=new Set(a.removedSteps??[]),te=new Map(o.markers.flatMap(e=>e.actEndSourceTimeMs===void 0||ee.has(e.actionId)?[]:[[e.actionId,e.actEndSourceTimeMs]])),E=(o.heldPresses??[]).map(e=>({startMs:vl(b,e.pressMs),endMs:vl(b,e.releaseMs)})),ne=Dl(a.cameraIntents,u,b,d,a.viewport,i,T,te,E),D=new Map(a.cameraIntents.map(e=>[e.id,e.actionId])),re=[];for(let e of ne.segments){if(e.fitted!==null){let{from:t,to:n,cap:r}=e.fitted,i=r!==null&&n>=r;i||w.push({id:e.id,kind:`zoomFit`,note:n<=1?`zoom "${e.id}" asked for ${Nu(t)}x, but its target is too wide to zoom on in this frame's crop, so the camera pans to it at 1x instead`:`zoom "${e.id}" asked for ${Nu(t)}x, and was narrowed to ${Nu(n)}x so its target fits this frame's crop`});let a=D.get(e.id);a!==void 0&&re.push({id:e.id,actionId:a,asked:Number(t.toFixed(2)),got:Number(n.toFixed(2)),by:i?`cap`:`fit`})}e.endClamped&&w.push({id:e.id,kind:`zoom`,note:`zoom "${e.id}" was asked to end at an instant the camera cannot reach — too close to its own push-in or to the next zoom — so it returns at ${Math.round(e.endMs)}ms instead`})}let ie=new Set(o.source===`replay`?[`click`,`type`,`drag`,`press`]:[`click`]),ae=new Set((s?.actions??[]).filter(e=>ie.has(e.kind)).map(e=>e.id)),oe=o.markers.filter(e=>ae.has(e.actionId)).map(e=>vl(b,e.sourceTimeMs)).sort((e,t)=>e-t),O=s?.meta.capture.device?.touch===!0,se=O?o.markers.filter(e=>ae.has(e.actionId)).flatMap(e=>{let t=Su(S,e.sourceTimeMs);return t===null?[]:[{outputMs:vl(b,e.sourceTimeMs),at:t}]}).sort((e,t)=>e.outputMs-t.outputMs):[],ce=Pu({keys:ne.keys,plan:a,bundle:o,timeline:b,cursor:S,motion:T,drawsPointer:!O&&!(s?.cursor??Ks).hidden}),le=a.cosmetics.map(e=>{let t=null,n=[];if(e.range){let r=xl({id:e.id,start:e.range.start,end:e.range.end,timeline:b,markerSourceMs:d});r.clamped&&w.push(r.clamped),n=r.unplaced,t=r.range}return{id:e.id,kind:`mask`,rect:e.rect,range:t,unplaced:n}});return{plan:a,timeline:b,cameraKeys:ne.keys,cameraFollow:ce,cameraSegments:ne.segments,cursor:S,clickOutputMs:oe,holdOutputMs:E,touch:O,taps:se,cursorLook:s?.cursor??Ks,motion:T,cursorRestOutputMs:Au(S,b,oe),cosmetics:le,range:C.range,trimUnplaced:C.unplaced.map(e=>e===`start`?`head`:`tail`),clampedRanges:w,loweredZooms:re}}var Iu=Object.freeze({press:1,angleRad:0}),Lu=[{x:0,y:0},{x:0,y:.75},{x:.19,y:.58},{x:.31,y:.87},{x:.45,y:.81},{x:.33,y:.53},{x:.56,y:.52}],Ru=.42,zu={light:{height:40,hotspot:{x:0,y:0},ink:Bu(Lu)},dark:{height:40,hotspot:{x:0,y:0},ink:Bu(Lu)},touch:{height:40,hotspot:{x:.5,y:.5},ink:{min:{x:.08000000000000002,y:.08000000000000002},max:{x:.9199999999999999,y:.9199999999999999}}}};function Bu(e){let t=e.map(e=>e.x),n=e.map(e=>e.y);return{min:{x:Math.min(...t),y:Math.min(...n)},max:{x:Math.max(...t),y:Math.max(...n)}}}var Vu={light:{fill:`#ffffff`,stroke:`#111827`},dark:{fill:`#111827`,stroke:`#ffffff`},touch:{fill:`rgba(255, 255, 255, 0.45)`,stroke:`#111827`}};function Hu(e,t,n,r,i=`light`){let a=zu[i].height*n*r.press,o=Vu[i];if(e.save(),e.translate(t.x,t.y),i!==`touch`&&r.angleRad!==0&&e.rotate(r.angleRad),e.beginPath(),i===`touch`)e.arc(0,0,a*Ru,0,Math.PI*2);else{let t=Lu[0];if(t){e.moveTo(t.x*a,t.y*a);for(let t of Lu.slice(1))e.lineTo(t.x*a,t.y*a)}}e.closePath(),e.shadowColor=`rgba(15, 23, 42, 0.35)`,e.shadowBlur=3*n,e.shadowOffsetY=1.5*n,e.fillStyle=o.fill,e.fill(),e.shadowColor=`transparent`,e.lineWidth=Math.max(1,1.4*n),e.lineJoin=`round`,e.strokeStyle=o.stroke,e.stroke(),e.restore()}var Uu=.55;function Wu(e){return e<=0?0:Math.ceil(2+8*z(e,0,1))}function Gu(e,t,n,r){if(t.length===0)return;let i=e.globalAlpha;t.forEach((a,o)=>{let s=(o+1)/(t.length+1);e.globalAlpha=i*s*s*Uu,Hu(e,a,n,{press:1,angleRad:a.angleRad??0},r)}),e.globalAlpha=i}function Ku(e,t,n,r){if(r<0||r>1)return;let i=1-(1-r)**3,a=16*n*(1+2.2*i),o=1-r,s=Math.max(1,2.5*n),c=Math.max(.75,1.25*n),l=(s+c)/2;e.save(),qu(e,t,a-l,c,`rgba(15, 23, 42, ${.75*o})`),qu(e,t,a+l,c,`rgba(15, 23, 42, ${.75*o})`),qu(e,t,a,s,`rgba(255, 255, 255, ${.95*o})`),e.restore()}function qu(e,t,n,r,i){n<=0||(e.beginPath(),e.arc(t.x,t.y,n,0,Math.PI*2),e.lineWidth=r,e.strokeStyle=i,e.stroke())}var Ju=.14,Yu=80,Xu=320,Zu=e=>{let t=z(e,0,1);return t*t*(3-2*t)};function Qu(e,t,n,r=[]){let i=Ju*z(n,0,2);if(i<=0)return 1;if(r.some(t=>e>=t.startMs&&e<t.endMs))return 1-i;let a=-1/0,o=1/0;for(let n of[...t,...r.map(e=>e.endMs)])n<=e?a=Math.max(a,n):o=Math.min(o,n);let s=e=>{let t=e-a;return t>=0&&t<=450?1-i*Math.exp(-t/Yu)*Math.cos(2*Math.PI*t/Xu):1};if(o!==1/0){let t=Math.max(o-110,a);if(e>=t){let n=s(t),r=(e-t)/(o-t);return n+(1-i-n)*Zu(r)}}return s(e)}var $u=15*Math.PI/180,ed=16,td=1.1,nd=.65,rd=8,id=20,ad=60;function od(e,t,n){let r=z(n,0,1),i=e.cursor[0],a=t-ed;if(r<=0||!i||a<0)return 0;let o=_l(e.timeline,a);if(o<i.sourceTimeMs)return 0;let s=Su(e.cursor,o),c=Su(e.cursor,_l(e.timeline,t));if(!s||!c)return 0;let l=(c.x-s.x)*1e3/ed,u=(c.y-s.y)*1e3/ed,d=Math.hypot(l,u);if(d<.001)return 0;let f=z((l+nd*u)/d,-1,1),p=e.plan.viewport.width,m=td*(p>0?p:1);return f*Math.min(1,d/m)*$u*r}function sd(e,t,n){if(!(n>0))return 0;let r=0,i=0;for(let a=0;a<rd;a++){let o=Math.exp(-a*id/ad);r+=o*od(e,t-a*id,n),i+=o}return r/i}function cd(e,t){let n=zo(e,t);if(!n)throw Error(`frame bundle has no keyframes; cannot resolve a frame`);return n}function ld(e,t,n){let r=zo(e,t);return e.keyframes.filter(e=>e===r||e.sourceTimeMs>t&&e.sourceTimeMs<=n)}function ud(e,t){let n=new Map,r=e=>{let r=n.get(e);if(r)return r;let i=t(e).then(t=>{if(t instanceof Uint8Array)throw Error(`keyframe "${e}" must load as an image, not encoded bytes`);return t});return n.set(e,i),i};return{async at(t){let n=cd(e,t);return{...await r(n.ref),sourceTimeMs:n.sourceTimeMs}},warm(t,n){for(let i of ld(e,t,n))r(i.ref).catch(()=>void 0)},describe:()=>({keyframes:e.keyframes,motionSpans:e.motionSpans})}}function B(e){if(!e)throw Error(`Assertion failed.`)}var dd=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},fd=e=>e&&e[e.length-1],V=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},pd=e=>{let t=V(e);return t&1?t+1>>1:-(t>>1)},md=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),H=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),hd=new TextDecoder,gd=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),_d={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},vd=gd(_d),yd={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},bd=gd(yd),xd={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Sd=gd(xd),Cd=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),wd=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Td=/^[0-9a-fA-F]+$/,Ed=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Dd=e=>{B(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},Od=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),kd=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},U=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Ad=(e,t,n)=>{let r=U(e,n(t),n);e.splice(r+1,0,t)},jd=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Md=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},Nd=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},Pd=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},Fd=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},Id=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},Ld=e=>{throw Error(`Unexpected value: ${e}`)},Rd=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},zd=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},Bd=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),Vd=(e,t,n)=>Math.max(t,Math.min(n,e)),Hd=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Ud=(e,t)=>Math.round(e/t)*t,Wd=(e,t)=>Math.round(e*t)/t,Gd=(e,t)=>Math.floor(e/t)*t,Kd=e=>{let t=0;for(;e;)t++,e>>=1;return t},qd=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Jd=/^[a-z]{3}$/,Yd=e=>Jd.test(e),Xd=1e6*(1+2**-52),Zd=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Qd=null,$d=()=>Qd===null?Qd=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):Qd,ef=null,tf=()=>ef===null?ef=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):ef,nf=null,rf=()=>nf===null?nf=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):nf,af=null,of=()=>{if(af!==null)return af;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?af=Number(e[1]):null},sf=e=>globalThis.isSecureContext!==void 0&&!globalThis.isSecureContext?`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${e} is not available in this environment.`,cf=(e,t)=>e===-1?t:e,lf=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},uf=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},df=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},ff=e=>typeof e==`number`&&!Number.isNaN(e),pf=(e,t)=>{if(t.includes(`://`))return t;if(e.includes(`://`)){let t=e.indexOf(`?`);t!==-1&&(e=e.slice(0,t))}let n;if(t.startsWith(`/`)){let r=e.indexOf(`://`);if(r===-1)n=t;else{let i=e.indexOf(`/`,r+3);n=i===-1?e+t:e.slice(0,i)+t}}else{let r=e.lastIndexOf(`/`);n=r===-1?t:e.slice(0,r+1)+t}let r=``,i=n.indexOf(`://`);if(i!==-1){let e=n.indexOf(`/`,i+3);e!==-1&&(r=n.slice(0,e),n=n.slice(e))}let a=n.split(`/`),o=[];for(let e of a)e===`..`?o.pop():e!==`.`&&o.push(e);return r+o.join(`/`)},mf=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},hf=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},gf=e=>{B(Number.isInteger(e.num)),B(Number.isInteger(e.den)),B(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},_f=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},vf=e=>new Promise(t=>setTimeout(t,e)),yf=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},bf;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(bf||={});var W=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==bf.Silent&&t!==bf.Errors&&t!==bf.Warnings&&t!==bf.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new yf}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=bf.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=bf.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=bf.Info&&console.info(...t)}};W._level=bf.Info,W._emitterInstance=null;var xf=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Sf=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},Cf={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},G=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},wf=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Tf=[-1,1,2,3,4,5,6,8],Ef=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new G(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<wf.length&&(i=wf[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=Tf[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},Df=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Of=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],kf=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`,...Of],Af=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],jf=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Mf=`.01.01.01.01.00`,Nf=`.0.110.01.01.01.0`,Pf=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Ff=[`dtsc`,`dtsh`,`dtsl`,`dtse`],If=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s,proresFormat:c}=e;if(t===`avc`){if(B(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Ed(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${Ed(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Od(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=H(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Od(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!o){let t=e.width*e.height,n=fd(jf).level;for(let e of jf)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(Mf)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=fd(jf).level;for(let e of jf)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?_d[r.primaries]:1,u=r?.transfer?yd[r.transfer]:1,d=r?.matrix?xd[r.matrix]:1,f=+!!r?.fullRange,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(Nf)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&Ld(t),TypeError(`Unhandled codec '${t}'.`)},Lf=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r,dtsFormat:i}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?Ef(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t===`dts`)return i??`dtsc`;if(t&&Of.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Rf=48e3,zf=/^pcm-([usf])(\d+)(be)?$/,Bf=e=>{if(B(Of.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=zf.exec(e);B(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?128:0}},Vf=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:Pf.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:Ff.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:zf.test(e)?e:e===`webvtt`?`webvtt`:null;[...Pf];var Hf=[44100,48e3,32e3],Uf=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Wf=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,Gf=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,Kf=(e,t)=>e===3?t===3?21:36:t===3?13:21,qf=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=Uf[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=Hf[d]>>o+s,x=Wf(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:o,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},Jf=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},Yf;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(Yf||={});var Xf=e=>e===3?1:2,Zf=[48e3,44100,32e3],Qf=[24e3,22050,16e3],$f;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})($f||={});var ep;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(ep||={});var tp=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},np=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=Rd(r,n,!1):(B(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},rp=(e,t)=>t.description?np(e,(md(t.description)[4]&3)+1):tp(e),ip=e=>e&31,ap=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},op=new Uint8Array([0,0,0,1]),sp=e=>{let t=e.reduce((e,t)=>e+op.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(op,r),r+=op.byteLength,n.set(t,r),r+=t.byteLength;return n},cp=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:zd(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},lp=(e,t)=>t.description?cp(e,(md(t.description)[4]&3)+1):sp(e),up=e=>{try{let t=[],n=[],r=[];for(let i of tp(e)){let a=e.subarray(i.offset,i.offset+i.length),o=ip(a[0]);o===$f.SPS?t.push(a):o===$f.PPS?n.push(a):o===$f.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=pp(i);B(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return W._error(`Error building AVC Decoder Configuration Record:`,e),null}},dp=e=>{try{let t=H(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return W._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},fp={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},pp=e=>{try{let t=new G(ap(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();V(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=V(t),a===3&&(c=t.readBits(1)),o=V(t),s=V(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=pd(t);i=(r+e+256)%256}r=i===0?r:i}}}V(t);let l=V(t);if(l===0)V(t);else if(l===1){t.skipBits(1),pd(t),pd(t);let e=V(t);for(let n=0;n<e;n++)pd(t)}V(t),t.skipBits(1);let u=V(t),d=V(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=V(t),n=V(t),r=V(t),i=V(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=fp[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(V(t),V(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&mp(t);let n=t.readBits(1);n&&mp(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),V(t),V(t),V(t),V(t),S=V(t),C=V(t))}if(S===null){B(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=Af.find(e=>e.level>=i)??fd(Af),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return B(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return W._error(`Error parsing AVC SPS:`,e),null}},mp=e=>{let t=V(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)V(e),V(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},hp=(e,t)=>t.description?cp(e,(md(t.description)[21]&3)+1):sp(e),gp=(e,t)=>t.description?np(e,(md(t.description)[21]&3)+1):tp(e),_p=e=>e>>1&63,vp=e=>{try{let t=new G(ap(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=bp(t,n);V(t);let u=V(t),d=0;u===3&&(d=t.readBits(1));let f=V(t),p=V(t),m=f,h=p;if(t.readBits(1)){let e=V(t),n=V(t),r=V(t),i=V(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=V(t),_=V(t);V(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)V(t),y=V(t),V(t);if(V(t),V(t),V(t),V(t),V(t),V(t),t.readBits(1)&&t.readBits(1)&&xp(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),V(t),V(t),t.skipBits(1)),Sp(t,V(t)),t.readBits(1)){let e=V(t);for(let n=0;n<e;n++)V(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,w=0,T={num:1,den:1};if(t.readBits(1)){let e=wp(t,n);T=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,w=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:T,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:w}}catch(e){return W._error(`Error parsing HEVC SPS:`,e),null}},yp=e=>{try{let t=[],n=[],r=[],i=[];for(let a of tp(e)){let o=e.subarray(a.offset,a.offset+a.length),s=_p(o[0]);s===ep.VPS_NUT?t.push(o):s===ep.SPS_NUT?n.push(o):s===ep.PPS_NUT?r.push(o):(s===ep.PREFIX_SEI_NUT||s===ep.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=vp(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new G(ap(e));t.skipBits(16),V(t),V(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),V(t),V(t),pd(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&V(t),pd(t),pd(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:ep.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ep.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ep.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:_p(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return W._error(`Error building HEVC Decoder Configuration Record:`,e),null}},bp=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},xp=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))V(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&pd(e);for(let t=0;t<n;t++)pd(e)}},Sp=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Cp(e,r,t,n)},Cp=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(V(e)+1):t-1,e.readBits(1),V(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=V(e),n=V(e);for(let n=0;n<t;n++)V(e),e.readBits(1);for(let t=0;t<n;t++)V(e),e.readBits(1);i=t+n}return i},wp=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=fp[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(V(e),V(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(V(e),V(e),V(e),V(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&V(e),e.readBits(1)&&Tp(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=V(e),V(e),V(e),V(e),V(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},Tp=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?V(e):o=e.readBits(1)===1;let s=1;o||(s=V(e)+1),r&&Ep(e,s,a),i&&Ep(e,s,a)}},Ep=(e,t,n)=>{for(let r=0;r<t;r++)V(e),V(e),n&&(V(e),V(e)),e.readBits(1)},Dp;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(Dp||={});var Op=(e,t)=>{let n=new Set,r=Dp.audAllowed;for(let i of gp(e,t)){if(r===Dp.noMoreDataAllowed){n.add(i.offset);continue}let t=_p(e[i.offset]);if(r===Dp.eoBitstreamAllowed&&t!==37){n.add(i.offset);continue}let a=!1;t===35?r>Dp.audAllowed?a=!0:r=Dp.beforeFirstVcl:t<=31?r>Dp.afterFirstVcl?a=!0:r=Dp.afterFirstVcl:t===36?r===Dp.afterFirstVcl?r=Dp.eoBitstreamAllowed:a=!0:t===37?r<Dp.afterFirstVcl?a=!0:r=Dp.noMoreDataAllowed:t===32||t===33||t===34||t===39||t>=41&&t<=44||t>=48&&t<=55?r>Dp.beforeFirstVcl?a=!0:r=Dp.beforeFirstVcl:(t===38||t===40||t>=45&&t<=47||t>=56&&t<=63)&&r<Dp.afterFirstVcl&&(a=!0),a&&n.add(i.offset)}if(n.size===0)return null;let i=[];for(let r of gp(e,t))n.has(r.offset)||i.push(e.subarray(r.offset,r.offset+r.length));return hp(i,t)},kp=e=>{let t=new G(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7){if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1}else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=fd(jf).level;for(let e of jf)if(u<=e.maxPictureSize){d=e.level;break}return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:a===2?1:a===1?6:2,transferCharacteristics:a===2?1:a===1?6:2,matrixCoefficients:a===7?0:a===2?1:a===1?6:2}},Ap=function*(e){let t=new G(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(r&127)<<n*7,!(r&128))break;if(n===7&&r&128)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);B(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},jp=e=>{for(let{type:t,data:n}of Ap(e)){if(t!==1)continue;let e=new G(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},Mp=e=>{let t=H(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},Np=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Pp=e=>{let t=e[0]>>3,n=e[0]&3,r;return r=n===0?1:n===1||n===2?2:e[1]&63,{durationInSamples:Np[t]*r}},Fp=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new G(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},Ip=(e,t,n)=>{switch(e){case`avc`:for(let e of rp(n,t)){let t=n[e.offset],r=ip(t);if(r>=$f.NON_IDR_SLICE&&r<=$f.SLICE_DPC)return`delta`;if(r===$f.IDR)return`key`;if(r===$f.SEI&&(!rf()||of()>=144)){let t=ap(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new G(t);e.pos=8*r;let n=V(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of gp(n,t)){let t=_p(n[e.offset]);if(t<ep.BLA_W_LP)return`delta`;if(t<=ep.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new G(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of Ap(n))if(t===1){let t=new G(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new G(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:Ld(e),B(!1)}},Lp;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Lp||={});var Rp=(e,t)=>{let n=H(e),r=0,i=n.getUint32(r,!0);r+=4;let a=hd.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=hd.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=lf(c),n=H(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=hd.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}}}},zp=[2,1,2,3,3,4,4,5],Bp=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new G(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Vp=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Hp=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Up=[1,2,3,6],Wp=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new G(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=Up[o],d;return d=i<3?Zf[i]/1e3:Qf[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},Gp=e=>{if(e.length<2)return null;let t=new G(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},Kp=e=>{let t=e.substreams[0];return B(t),t.fscod<3?Zf[t.fscod]:t.fscod2!==null&&t.fscod2<3?Qf[t.fscod2]:null},qp=e=>{let t=e.substreams[0];B(t);let n=zp[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},Jp=4096,Yp=8,Xp=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Zp=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Qp=[16,16,20,20,0,24,24,0],$p=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],em=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],tm=8,nm=44646,rm=[32e3,44100,48e3,0],im=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],am=[512,1024,2048,4096],om=e=>{let t=cm(e),n=H(e),r=t?Math.ceil(t.frameSize/4)*4:0,i=null;for(;r+4<=e.length&&n.getUint32(r)===1683496997;){let t=lm(e.subarray(r));if(!t)break;i??=t,r+=t.frameSize}if(t)return{frameSize:i?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:i!==null};if(!i?.asset)return null;let{asset:a}=i;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},sm=e=>{let t=om(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},cm=e=>{if(e.length<18||e[0]!==127||e[1]!==254||e[2]!==128||e[3]!==1)return null;let t=new G(e);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==31)return null;let n=t.readBits(1),r=t.readBits(7)+1;if(r%Yp!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=$p.length)return null;let o=Xp[t.readBits(4)];if(o===0)return null;let s=Zp[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),n&&t.skipBits(16),t.skipBits(7);let l=Qp[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:$p[a]+ +!!u,sampleCount:r*32,channelLayout:em[a]|(u?tm:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},lm=e=>{if(e.length<10||e[0]!==100||e[1]!==88||e[2]!==32||e[3]!==37)return null;let t=new G(e);t.skipBits(32),t.skipBits(8);let n=t.readBits(2),r=t.readBits(1),i=8+4*r,a=16+4*r;t.skipBits(i);let o=t.readBits(a)+1,s={frameSize:o,asset:null};if(!t.readBits(1))return s;let c=rm[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,f=[];for(let e=0;e<u;e++)f.push(t.readBits(n+1));for(let e of f)t.skipBits(8*qd(e));if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,n=t.readBits(2)+1;t.skipBits(n*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let p=t.readBits(5)+1,m=im[t.readBits(4)],h=t.readBits(8)+1,g=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;g=t.readBits(e)}return c===0||t.getBitsLeft()<0?s:{frameSize:o,asset:{sampleRate:m,numberOfChannels:h,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:p}}},um=e=>{if(e.length<20)return null;let t=H(e),n=t.getUint32(0);if(n===0)return null;let r=new G(e);r.seekToByte(13);let i=r.readBits(2);r.skipBits(5);let a=r.readBits(1),o=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let s=r.readBits(16),c=null;return s===0?o<$p.length&&(c=$p[o]+a):c=dm(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:am[i],channelLayout:s,numberOfChannels:c}},dm=e=>qd(e)+qd(e&nm),fm=class{constructor(e){this.input=e}dispose(){}},pm=new Uint8Array,mm=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===pm&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===pm}get microsecondTimestamp(){return Math.trunc(Xd*this.timestamp)}get microsecondDuration(){return Math.trunc(Xd*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`EncodedVideoChunk is not available in this environment.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`EncodedAudioChunk is not available in this environment.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},hm=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},gm=e=>{let t=H(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=Ed(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(Ed(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},_m=(e,t)=>e.systemId===t.systemId&&uf(e.data,t.data),vm=e=>{let t=Q(e),n=$(e,4),r=8;t===1&&(t=jv(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},ym=e=>Ov(e)/65536,bm=e=>Ov(e)/1073741824,xm=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=X(e);if(t|=n&127,!(n&128))break}return t},Sm=e=>{let t=Z(e);return e.skip(2),t=Math.min(t,e.remainingLength),hd.decode(Y(e,t))},Cm=e=>{let t=vm(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=Q(e);e.skip(4);let r=Y(e,t.contentSize-8);switch(n){case 1:return hd.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new xf(r,`image/jpeg`);case 14:return new xf(r,`image/png`);case 27:return new xf(r,`image/bmp`);default:return r}},wm=new Uint32Array(256),Tm=new Uint32Array(256),Em=new Uint32Array(256),Dm=new Uint32Array(256),Om=new Uint32Array(256),km=new Uint32Array(256),Am=new Uint32Array(10),jm=!1,Mm=()=>{let e=new Uint8Array(256),t=new Uint8Array(256),n=new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);wm[t]=n<<24|n<<16|n<<8|n,km[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;Tm[t]=l,Em[t]=l>>>8|l<<24,Dm[t]=l>>>16|l<<16,Om[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Am[e]=i<<24,i=i<<1^(i&128?283:0);jm=!0},Nm=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(16),this.out=new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){B(e.byteLength===16),B(t.byteLength===16),jm||Mm();let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^wm[t>>>16&255]&4278190080^wm[t>>>8&255]&16711680^wm[t>>>0&255]&65280^wm[t>>>24&255]&255^Am[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=Tm[wm[n>>>24&255]&255]^Em[wm[n>>>16&255]&255]^Dm[wm[n>>>8&255]&255]^Om[wm[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=Tm[e>>>24]^Em[r>>>16&255]^Dm[n>>>8&255]^Om[t&255]^this.roundkey[a],l=Tm[t>>>24]^Em[e>>>16&255]^Dm[r>>>8&255]^Om[n&255]^this.roundkey[a+1],u=Tm[n>>>24]^Em[t>>>16&255]^Dm[e>>>8&255]^Om[r&255]^this.roundkey[a+2],d=Tm[r>>>24]^Em[n>>>16&255]^Dm[t>>>8&255]^Om[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=km[e>>>24&255]&4278190080^km[r>>>16&255]&16711680^km[n>>>8&255]&65280^km[t>>>0&255]&255^this.roundkey[40],p=km[t>>>24&255]&4278190080^km[e>>>16&255]&16711680^km[r>>>8&255]&65280^km[n>>>0&255]&255^this.roundkey[41],m=km[n>>>24&255]&4278190080^km[t>>>16&255]&16711680^km[e>>>8&255]&65280^km[r>>>0&255]&255^this.roundkey[42],h=km[r>>>24&255]&4278190080^km[n>>>16&255]&16711680^km[t>>>8&255]&65280^km[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},Pm=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new Nm;return new ReadableStream({pull:async s=>{r||=(o.init(await t()),!0);let c=a+16,l=e.requestSliceRange(i,0,c);if(l instanceof Promise&&(l=await l),!l||l.length===0)throw Error(`Invalid ciphertext.`);let u=l.length;if(u%16!=0)throw Error(`Invalid ciphertext.`);let d=u===c?u-16:u,f=Y(l,d),p=new Uint8Array(d);for(let e=0;e<d;e+=16)o.in.set(f.subarray(e,e+16)),o.decrypt(),p.set(o.out,e);if(d<u)s.enqueue(p),i+=d;else{let e=p[d-1];if(e===0||e>16)throw Error(`Invalid PKCS#7 padding. Incorrect key or corrupted data.`);let t=p.subarray(0,d-e);s.enqueue(t),s.close(),n()}},cancel:()=>{n()}})},Fm=class e extends fm{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return hm({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,n=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(r instanceof Promise&&(r=await r),!r)break;let i=e,a=vm(r);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=$(r,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(r.filePos,a.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,n=!0;break}else if(a.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,n=!0;break}e=i+a.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){B(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),B(e);let t=Q(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),e){let t=vm(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let n=await t._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};e.trackBacking&&(B(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Lm(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Rm(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;B(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&Of.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){B(e.info?.type===`audio`);let n=Bf(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=U(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=U(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=fd(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),B(t);let n=vm(t);B(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);r instanceof Promise&&(r=await r),B(r),this.traverseBox(r);let i=this.lastReadFragment;B(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)Um(e,r.timestamp);else{let t=U(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Um(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=U(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await qm(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=vm(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=vm(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=X(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=Q(e),this.movieDurationInTimescale=jv(e)):(e.skip(8),this.movieTimescale=Q(e),this.movieDurationInTimescale=Q(e))}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...Cf,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Lm(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Rm(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=X(e),r=!!(wv(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=Q(e),e.skip(4),t.durationInMovieTimescale=Q(e);else if(n===1)e.skip(16),t.id=Q(e),e.skip(4),t.durationInMovieTimescale=jv(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=dd(Ud(Wm([ym(e),ym(e),bm(e),ym(e),ym(e),bm(e),ym(e),ym(e),bm(e)]),90));B(i===0||i===90||i===180||i===270),t.rotation=i}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=X(e);e.skip(3);let r=!1,i=0,a=Q(e);for(let o=0;o<a;o++){let a=n===1?jv(e):Q(e),o=n===1?Mv(e):Ov(e),s=ym(e);if(a!==0){if(r){W._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){W._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=X(e);e.skip(3),n===0?(e.skip(8),t.timescale=Q(e),t.durationInMediaTimescale=Q(e)):n===1&&(e.skip(16),t.timescale=Q(e),t.durationInMediaTimescale=jv(e));let r=Z(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Yd(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=$(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=X(e);e.skip(3);let r=Q(e);for(let i=0;i<r;i++){let r=e.filePos,i=vm(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=Z(e),t.info.height=Z(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:Pf.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?W._warn(`Unknown encrypted video codec due to missing frma box.`):W._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=Z(e);e.skip(6);let s=Z(e),c=Z(e);e.skip(4);let l=Q(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*Q(e),e.skip(8)):o===2&&(e.skip(4),l=Fv(e),s=Q(e),e.skip(4),c=Q(e),u=Q(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`){if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=Rf;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(Ff.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(W._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(W._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(W._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(W._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(W._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(W._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&W._warn(`Unsupported PCM format.`)}else d===null?W._warn(`Unknown encrypted audio codec due to missing frma box.`):W._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=$(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=$(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:W._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=X(e);e.skip(3),e.skip(1);let r=X(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=X(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=X(e),t.encryptionInfo.defaultKid=Ed(Y(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=X(e),r=new Uint8Array(16);r.set(Y(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(B(t.info),n.contentSize===0))break;t.info.codecDescription=Y(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(B(t.info),n.contentSize===0))break;t.info.codecDescription=Y(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`video`),e.skip(4);let n=X(e),r=X(e),i=X(e),a=i>>4,o=i>>1&7,s=i&1,c=X(e),l=X(e),u=X(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`video`),e.skip(1);let n=X(e),r=n>>5,i=n&31,a=X(e),o=a>>7,s=a>>6&1,c=a>>5&1,l=a>>4&1,u=a>>3&1,d=a>>2&1,f=a&3,p=r===2&&s?c?12:10:s?10:8;t.info.av1CodecInfo={profile:r,level:i,tier:o,bitDepth:p,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:f}}break;case`colr`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`video`);let n=$(e,4);if(n!==`nclx`&&n!==`nclc`)break;let r=Z(e),i=Z(e),a=Z(e),o;n===`nclx`&&(o=!!(X(e)&128)),t.info.colorSpace={primaries:vd[r],transfer:bd[i],matrix:Sd[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`video`);let n=Q(e),r=Q(e);n>0&&r>0&&(n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n))}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`),e.skip(4),B(X(e)===3),xm(e),e.skip(2);let n=X(e),r=!!(n&128),i=!!(n&64),a=!!(n&32);if(r&&e.skip(2),i){let t=X(e);e.skip(t)}a&&e.skip(2),B(X(e)===4);let o=xm(e),s=e.filePos,c=X(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:c===169?t.info.codec=`dts`:W._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){B(X(e)===5);let n=xm(e);if(t.info.codecDescription=Y(e,n),t.info.codec===`aac`){let e=Ef(t.info.codecDescription);e.numberOfChannels!==null&&(t.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(t.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(Z(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`),e.skip(4);let n=X(e);t.info.pcmLittleEndian=!!(n&1),t.info.pcmSampleSize=X(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`),e.skip(1);let n=X(e),r=Z(e),i=Q(e),a=Tv(e),o=X(e),s;s=o===0?new Uint8Array:Y(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=X(e),r=wv(e);if((n&127)===Lp.STREAMINFO){e.skip(10);let n=Q(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=Y(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`);let n=new G(Y(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Zf[r]),t.info.numberOfChannels=zp[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`);let r=Gp(Y(e,n.contentSize));if(!r){W._warn(`Invalid dec3 box contents, ignoring.`);break}let i=Kp(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=qp(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`);let r=um(Y(e,Math.min(n.contentSize,20)));if(!r){W._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=r.sampleRate,r.numberOfChannels!==null&&(t.info.numberOfChannels=r.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e),r=0,i=0;for(let a=0;a<n;a++){let n=Q(e),a=Q(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e),r=0;for(let i=0;i<n;i++){let n=Q(e),i=Ov(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e),r=Q(e);if(n===0)for(let n=0;n<r;n++){let n=Q(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=X(e),r=Q(e),i=new G(Y(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=Q(e);for(let r=0;r<n;r++){let n=Q(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e);for(let r=0;r<n;r++){let n=Q(e)-1,r=Q(e),i=Q(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e);for(let r=0;r<n;r++){let n=Q(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Q(e);for(let r=0;r<n;r++){let n=jv(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=X(e);e.skip(3);let n=t===1?jv(e):Q(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=Q(e),n=Q(e),r=Q(e),i=Q(e),a=Q(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=X(e);e.skip(3);let n=Q(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=Q(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[X,Z,wv,Q],l=c[a],u=c[o],d=c[s],f=Q(e);for(let n=0;n<f;n++){let n=t===1?jv(e):Q(e),i=t===1?jv(e):Q(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(B(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],n=e.samples[fd(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;B(r),r.startTimestamp!==null&&(Um(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=gm(Y(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{B(this.currentFragment),e.skip(1);let t=wv(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=Q(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},n?u.currentFragmentState.baseDataOffset=jv(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Q(e)),i&&(u.currentFragmentState.defaultSampleDuration=Q(e)),a&&(u.currentFragmentState.defaultSampleSize=Q(e)),o&&(u.currentFragmentState.defaultSampleFlags=Q(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;B(t.currentFragmentState);let n=X(e);e.skip(3);let r=n===0?Q(e):jv(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;B(this.currentFragment),B(t.currentFragmentState);let n=X(e),r=wv(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=Q(e),d=null;i&&(d=Ov(e));let f=null;a&&(f=Q(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=Q(e):(B(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=Q(e):(B(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=Q(e):(B(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?Q(e):Ov(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),wv(e)&1){let n=$(e,4),r=Q(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=X(e),r=Q(e),i=null;n===0&&r>0&&(i=Y(e,r));let a=Km(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=X(e);if(wv(e)&1){let n=$(e,4),r=Q(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=Q(e);if(r===0)break;r>1&&W._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?Q(e):Number(jv(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Km(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;B(this.currentFragment);let n=this.currentFragment.trackData.get(t.id);if(!n)break;e.skip(1);let r=!!(wv(e)&2),i=Q(e),a=t.encryptionInfo.defaultPerSampleIvSize;B(a!==null);for(let o=0;o<Math.min(i,n.samples.length);o++){let i=new Uint8Array(16);a>0?i.set(Y(e,a),0):i.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(r){let t=Z(e);s=[];for(let n=0;n<t;n++){let t=Z(e),n=Q(e);s.push({clearLen:t,protectedLen:n})}}let c=n.samples[o];c.encryption={iv:i,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=Sm(n):this.metadataTags.raw[e.name]??=Y(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=hd.decode(Y(n,e.contentSize)):this.metadataTags.title??=Sm(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=Sm(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=Sm(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=Sm(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=Sm(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=Sm(n));break;case`©day`:if(!this.currentTrack){let e=new Date(Sm(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=Sm(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=Sm(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=Q(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=Q(e);for(let n=0;n<t;n++){let t=Q(e);e.skip(4);let r=hd.decode(Y(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=Cm(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof xf?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=H(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=H(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=i,!0}},Im=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(B(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Hd(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=zm(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Gm(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=U(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Bm(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Gm(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Pd(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=Hm(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return B(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=Vm(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=pm;else{let t=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(r=Y(t,n.sampleSize),this.internalTrack.encryptionAuxInfo){B(this.internalTrack.encryptionInfo);let t=await qm(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(r=await Jm(this.internalTrack,t[e],r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new mm(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];B(r);let i;if(n.metadataOnly)i=pm;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;i=Y(t,r.byteSize),r.encryption&&(i=await Jm(this.internalTrack,r.encryption,i,e))}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new mm(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=U(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=U(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(e instanceof Promise&&(e=await e),!e)break;let n=m,l=vm(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];B(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},Lm=class extends Im{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&up(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&yp(e.data)}else if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&kp(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&jp(e.data)}let e={codec:If(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Rm=class extends Im{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&sm(e.data)}return{codec:Lf(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},zm=(e,t)=>{if(e.presentationTimestamps){let n=U(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=U(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Bm=(e,t)=>{if(!e.keySampleIndices)return zm(e,t);if(e.presentationTimestamps){let n=U(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(kd(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=zm(e,t),r=U(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Vm=(e,t)=>{let n=U(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=U(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=U(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];B(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];B(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:!e.keySampleIndices||kd(e.keySampleIndices,t,e=>e)!==-1}},Hm=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=U(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Um=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Wm=e=>{let[t,n]=e,r=Math.atan2(n,t);return Number.isFinite(r)?180/Math.PI*r:0},Gm=e=>e.sampleSizes.length===0,Km=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},qm=async(e,t,n)=>{if(n.resolved)return n.resolved;if(n.offset===null||n.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let r=0;if(n.defaultSampleInfoSize>0)r=n.defaultSampleInfoSize*n.sampleCount;else{B(n.sampleSizes);for(let e=0;e<n.sampleCount;e++)r+=n.sampleSizes[e]}let i=e.requestSlice(n.offset,r);if(i instanceof Promise&&(i=await i),!i)throw Error(`Failed to read auxiliary encryption info.`);let a=t.defaultPerSampleIvSize;B(a!==null);let o=[];for(let e=0;e<n.sampleCount;e++){let r=n.defaultSampleInfoSize>0?n.defaultSampleInfoSize:n.sampleSizes[e],s=new Uint8Array(16);a>0?s.set(Y(i,a),0):s.set(t.defaultConstantIv,0);let c=null;if(r>a){let e=Z(i);c=[];for(let t=0;t<e;t++){let e=Z(i),t=Q(i);c.push({clearLen:e,protectedLen:t})}}o.push({iv:s,subsamples:c})}return n.resolved=o,o},Jm=async(e,t,n,r)=>{B(e.encryptionInfo);let i=e.encryptionInfo;B(i.defaultKid!==null);let a=i.defaultKid,o,s=e.demuxer.decryptionKeyCache.get(a);if(s)o=await s;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)_m(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&Td.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:Dd(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?Ym(o,i,t,n):Xm(o,i,t,n)},Ym=async(e,t,n,r)=>{let i=new Uint8Array(16);i.set(n.iv,0);let a=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),o=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:i,length:64},a,e);return new Uint8Array(t)};if(!n.subsamples)return o(r);B(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let s=Zm(n.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of s)for(let t of e.perSubsample)c+=t.length;let l=new Uint8Array(c),u=0;for(let e of s)for(let t of e.perSubsample)l.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let d=await o(l),f=new Uint8Array(r),p=0;for(let e of s)for(let t of e.perSubsample)f.set(d.subarray(p,p+t.length),t.offset),p+=t.length;return f},Xm=(e,t,n,r)=>{let i=new Nm;i.init({key:e,iv:n.iv});let a=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(B(a!==null&&o!==null),!n.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let n=0;n<t;n++){let t=n*16;i.in.set(r.subarray(t,t+16)),i.decrypt(),e.set(i.out,t)}return e}if(a===0&&o===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let s=new Uint8Array(r),c=Zm(n.subsamples,a,o),l=new DataView(n.iv.buffer,n.iv.byteOffset,16);for(let e of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;i.in.set(r.subarray(e,e+16)),i.decrypt(),s.set(i.out,e)}}}return s},Zm=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},K;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(K||={});var Qm=[K.EBML,K.Segment],$m=[K.SeekHead,K.Info,K.Cluster,K.Tracks,K.Cues,K.Attachments,K.Chapters,K.Tags],eh=[...Qm,...$m],th=e=>{if(e.remainingLength<1)return null;let t=X(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},nh=e=>{if(e.remainingLength<1)return null;let t=X(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=X(e);return i},q=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=X(e);return n},rh=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(X(e));return n},ih=e=>{let t=th(e);return t===null||e.remainingLength<t?null:q(e,t)},ah=e=>{if(e.remainingLength<1)return null;if(X(e)===255)return;e.skip(-1);let t=nh(e);if(t===null)return null;if(t!==72057594037927940)return t},oh=e=>{B(e.remainingLength>=2);let t=ih(e);if(t===null)return null;let n=ah(e);return n===null?null:{id:t,size:n}},sh=(e,t)=>{let n=Y(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},ch=(e,t)=>{let n=Y(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return hd.decode(n.subarray(0,r))},lh=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?Pv(e):Fv(e)},uh=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=oh(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};ph(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},dh=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=ih(t);if(e!==null&&a.has(e))return o;o++}}return null},fh={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,prores:`V_PRORES`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,dts:`A_DTS`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function ph(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var mh=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},hh;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(hh||={});var gh;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(gh||={});var _h;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(_h||={});var vh=[{id:K.SeekHead,flag:`seekHeadSeen`},{id:K.Info,flag:`infoSeen`},{id:K.Tracks,flag:`tracksSeen`},{id:K.Cues,flag:`cuesSeen`}],yh=10*2**20,bh=class extends fm{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return mh({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=oh(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===K.EBML){ph(i);let e=this.reader.requestSlice(a,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===K.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===K.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await uh(this.reader,a,eh,this.reader.fileSize)).pos-a);let e=fd(this.segments);e&&(e.elementEndPos=a+i)}ph(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=oh(e);if(!r||!$m.includes(r.id)&&r.id!==K.Void){let e=await dh(this.reader,t,$m,Math.min(this.currentSegment.elementEndPos??1/0,t+yh));if(e){n=e;continue}break}let{id:i,size:a}=r,o=e.filePos,s=vh.findIndex(e=>e.id===i);if(s!==-1){let e=vh[s].flag;this.currentSegment[e]=!0,ph(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===K.Tags||i===K.Attachments){i===K.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ph(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===K.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=vh.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=oh(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;ph(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,2,16);n instanceof Promise&&(n=await n),B(n);let r=e,i=oh(n);B(i);let a=i.id;B(a===K.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await uh(this.reader,s,eh,t.elementEndPos)).pos-s);let c=this.reader.requestSlice(s,o);c instanceof Promise&&(c=await c);let l={segment:t,elementStartPos:r,elementEndPos:s+o,dataStartPos:s,timestamp:-1,trackData:new Map};this.currentCluster=l,c&&(l.elementEndPos=this.readContiguousElements(c,eh));for(let[,e]of l.trackData){let t=e.track;B(e.blocks.length>0);let n=!1;for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t];r.timestamp+=l.timestamp,n||=r.lacing!==hh.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===hh.None&&(i.duration=t.defaultDuration)}n&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=e.blocks[e.presentationTimestamps[0].blockIndex],a=e.blocks[fd(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=a.timestamp+a.duration;let o=U(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(o===-1||t.clusterPositionCache[o].elementStartPos!==r)&&t.clusterPositionCache.splice(o+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.lacing===hh.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=xv.tempFromBytes(r.data),a=[],o=X(i)+1;switch(r.lacing){case hh.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){let n=X(i);if(t+=n,n<255){a.push(t),e+=t;break}}}a.push(i.length-(i.bufferPos+e))}break;case hh.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case hh.Ebml:{let e=nh(i);B(e!==null);let t=e;a.push(t);let n=t;for(let e=1;e<o-1;e++){let e=i.bufferPos,r=nh(i);B(r!==null);let o=r-((1<<(i.bufferPos-e)*7-1)-1);t+=o,a.push(t),n+=t}a.push(i.length-(i.bufferPos+n))}break;default:B(!1)}B(a.length===o),e.splice(n,1);let s=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let c=a[t],l=Y(i,c),u=r.timestamp+s*t/o,d=s/o;e.splice(n+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:hh.None,decoded:!0,postProcessed:!1,mainAdditional:r.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===K.Tags&&!e.tagsSeen)&&!(t.id===K.Attachments&&!e.attachmentsSeen))continue;let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(n instanceof Promise&&(n=await n),!n)continue;let r=oh(n);if(!r||r.id!==t.id)continue;let{size:i}=r;ph(i),B(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,i);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===K.Tags?e.tagsSeen=!0:t.id===K.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=oh(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch(ph(i),r){case K.DocType:this.isWebM=sh(e,i)===`webm`;break;case K.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(a,i)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case K.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=q(e,i)}break;case K.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=q(e,i)}break;case K.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=q(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case K.Duration:if(!this.currentSegment)break;this.currentSegment.duration=lh(e,i);break;case K.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Cf,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:`eng`,hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,i)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==gh.Block||e.data.algorithm!==_h.HeaderStripping)&&(W._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===fh.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===fh.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===fh.vp8)this.currentTrack.info.codec=`vp8`;else if(t===fh.vp9)this.currentTrack.info.codec=`vp9`;else if(t===fh.av1)this.currentTrack.info.codec=`av1`;else if(t===fh.prores){let e=this.currentTrack.codecPrivate?hd.decode(this.currentTrack.codecPrivate):``;Pf.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new Sh(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===fh.aac?(this.currentTrack.info.codec=`aac`,this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes(`MPEG2`),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===fh.mp3?this.currentTrack.info.codec=`mp3`:t===fh.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Rf):t===fh.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===fh.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===fh.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===fh.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===fh.dts?(this.currentTrack.info.codec=`dts`,this.currentTrack.codecId===`A_DTS/EXPRESS`?this.currentTrack.info.dtsFormat=`dtse`:this.currentTrack.codecId===`A_DTS/LOSSLESS`&&(this.currentTrack.info.dtsFormat=`dtsl`)):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack;this.currentTrack.trackBacking=new Ch(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case K.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=q(e,i);break;case K.TrackType:{if(!this.currentTrack)break;let t=q(e,i);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case K.FlagEnabled:if(!this.currentTrack)break;q(e,i)||(this.currentTrack=null);break;case K.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!q(e,i);break;case K.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!q(e,i);break;case K.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!q(e,i);break;case K.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!q(e,i);break;case K.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!q(e,i);break;case K.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!q(e,i);break;case K.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=sh(e,i);break;case K.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Y(e,i);break;case K.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=q(e,i);break;case K.Name:if(!this.currentTrack)break;this.currentTrack.name=ch(e,i);break;case K.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=sh(e,i),Yd(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case K.LanguageBCP47:{if(!this.currentTrack)break;let t=sh(e,i).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case K.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case K.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=q(e,i);break;case K.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=q(e,i);break;case K.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=q(e,i);break;case K.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=q(e,i);break;case K.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=q(e,i);break;case K.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=q(e,i)===1;break;case K.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,i));break;case K.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Sd[q(e,i)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case K.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=q(e,i)===2;break;case K.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=bd[q(e,i)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case K.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=vd[q(e,i)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case K.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case K.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-lh(e,i);try{this.currentTrack.info.rotation=dd(t)}catch{}}break;case K.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(a,i));break;case K.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=lh(e,i);break;case K.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=q(e,i);break;case K.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=q(e,i);break;case K.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,i)),this.currentCueTime=null;break;case K.CueTime:this.currentCueTime=q(e,i);break;case K.CueTrackPositions:{if(this.currentCueTime===null)break;B(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(a,i)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case K.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=q(e,i)}break;case K.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;B(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+q(e,i)}break;case K.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=q(e,i);break;case K.SimpleBlock:{if(!this.currentCluster)break;let t=nh(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Tv(e),o=X(e),s=o>>1&3,c=!!(o&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=Y(e,i-(e.filePos-a)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case K.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,i)),this.currentBlock=null;break;case K.Block:{if(!this.currentCluster)break;let t=nh(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Tv(e),o=X(e)>>1&3,s=Y(e,i-(e.filePos-a)),c=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:o,decoded:!c,postProcessed:!1,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case K.BlockAdditions:this.readContiguousElements(e.slice(a,i));break;case K.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case K.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Y(e,i);break;case K.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=q(e,i);break;case K.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=q(e,i);break;case K.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case K.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,i));break;case K.Targets:this.readContiguousElements(e.slice(a,i));break;case K.TargetTypeValue:q(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case K.TagTrackUID:case K.TagEditionUID:case K.TagChapterUID:case K.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case K.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,i));break;case K.TagName:this.currentSimpleTagName=ch(e,i);break;case K.TagString:{if(!this.currentSimpleTagName)break;let t=ch(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case K.TagBinary:{if(!this.currentSimpleTagName)break;let t=Y(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case K.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Sf(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case K.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=rh(e,i);break;case K.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ch(e,i);break;case K.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=sh(e,i);break;case K.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=Y(e,i);break;case K.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ch(e,i);break;case K.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case K.ContentEncoding:this.currentDecodingInstruction={order:0,scope:gh.Block,data:null},this.readContiguousElements(e.slice(a,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case K.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=q(e,i);break;case K.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=q(e,i);break;case K.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:_h.Zlib,settings:null},this.readContiguousElements(e.slice(a,i));break;case K.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=q(e,i);break;case K.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=Y(e,i);break;case K.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=a+i,!0}decodeBlockData(e,t){B(e.decodingInstructions.length>0);let n=t;for(let t of e.decodingInstructions)if(B(t.data),t.data.type===`decompress`)switch(t.data.algorithm){case _h.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length),n=r}}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}}}},xh=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.segments)for(let e of r.tracks)if(e.trackBacking.getType()===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Hd(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=U(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Pd(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>n.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return B(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];if(B(r),r.decoded||=(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),!0),!r.postProcessed){if(this.internalTrack.info?.codec===`prores`&&!(r.data.length>=8&&r.data[4]===105&&r.data[5]===99&&r.data[6]===112&&r.data[7]===102)){let e=new Uint8Array(r.data.length+8);H(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}r.postProcessed=!0}let i=n.metadataOnly?pm:r.data,a=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,s={};r.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(s.alpha=n.metadataOnly?pm:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new mm(i,r.isKeyFrame?`key`:`delta`,a,o,e.dataStartPos+t,r.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,n,r,i){let{demuxer:a,segment:o}=this.internalTrack,s=null,c=null,l=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,i);n!==-1&&(c=e,l=n)}let u=U(this.internalTrack.cuePoints,n,e=>e.time),d=u===-1?null:this.internalTrack.cuePoints[u],f=U(this.internalTrack.clusterPositionCache,n,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.clusterPositionCache[f],m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(e?m===null||e.elementStartPos>=m?(h=e.elementEndPos,s=e):h=m:h=m??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-2;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;let n=h,u=oh(e);if(!u||!$m.includes(u.id)&&u.id!==K.Void){let e=await dh(a.reader,n,$m,Math.min(o.elementEndPos??1/0,n+yh));if(e){h=e;continue}break}let d=u.id,f=u.size,p=e.filePos;if(d===K.Cluster){s=await a.readCluster(n,o),f=s.elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(s);if(r)return this.fetchPacketInCluster(s,e,i);e!==-1&&(c=s,l=e)}f===void 0&&(B(d!==K.Cluster),f=(await uh(a.reader,p,eh,o.elementEndPos)).pos-p);let m=p+f;if(o.elementEndPos===null){let e=a.reader.requestSliceRange(m,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(ih(e)===K.Segment){o.elementEndPos=m;break}}h=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){let e=this.internalTrack.cuePoints[u-1];B(!e||e.time<d.time);let n=e?.time??-1/0;return this.performClusterLookup(null,t,n,r,i)}return c?this.fetchPacketInCluster(c,l,i):null}},Sh=class extends xh{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`video`}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let t={codec:If({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec===`avc`&&e?up(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?yp(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?kp(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?jp(e.data):null,proresFormat:this.internalTrack.info.proresFormat}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}},Ch=class extends xh{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return`audio`}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&sm(e.data)}return{codec:Lf({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},wh=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===null?i:Math.min(i,n-a),o=e.requestSliceRange(a,4,t);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=qf(Q(o),e.fileSize===null?null:e.fileSize-a);if(n.header&&(!r||n.header.sampleRate===r.sampleRate&&n.header.mpegVersionId===r.mpegVersionId&&n.header.layer===r.layer&&Xf(n.header.channel)===Xf(r.channel)))return{header:n.header,startPos:a};o.filePos=t+n.bytesAdvanced,a=o.filePos}}return null},Th=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new wd,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.trackBackings=[new Eh(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Hv(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await wh(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Kf(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let i=Q(r);if(i===1483304551||i===1231971951){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+n+4,12);if(t instanceof Promise&&(t=await t),t){let e=H(Y(t,12)),n=e.getUint32(0,!1);this.xingData={frameCount:n&Yf.FrameCount?e.getUint32(4,!1):null,fileSize:n&Yf.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Hv(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;Uv(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),B(e),$(e,3)===`TAG`&&Bv(e,this.metadataTags)}return this.metadataTags}finally{e()}}},Eh=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return B(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(B(e.firstFrameHeader!==null),B(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=Gf(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return B(this.demuxer.firstFrameHeader),Xf(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return B(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Cf}}async getDecoderConfig(){return B(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:Xf(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=pm;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=Y(e,n.dataSize)}return new mm(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=kd(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Dh=79764919,Oh=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Dh:t<<1;Oh[e]=t>>>0&4294967295}var kh=e=>{let t=H(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^Oh[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},Ah=(e,t,n)=>{let r=0,i=null;if(e.length>0){if(t.codec===`vorbis`){B(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<Kd(a-1))-1<<1,s=(e[0]&o)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let c=n,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],l===1){let n=(o|1)+1,r=e[0]&n?1:0;c=t.vorbisInfo.blocksizes[r]}r=c===null?0:c+i>>2}else t.codec===`opus`&&(r=Pp(e).durationInSamples)}return{durationInSamples:r,vorbisBlockSize:i}},jh=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Mh=65307,Nh=e=>{let t=e.filePos;if(Dv(e)!==1399285583)return null;e.skip(1);let n=X(e),r=Nv(e),i=Dv(e),a=Dv(e),o=Dv(e),s=X(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=X(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},Ph=(e,t)=>{for(;e.filePos<t-3;){let t=Dv(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(n===79||r===79||i===79||a===79){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},Fh=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=Nh(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.trackBackings.push(new Ih(e,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=H(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:Fp(i.data).modeBlockflags},Rp(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=Mp(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Rf,t.codecInfo.opusInfo={preSkip:i.preSkip},Rp(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){B(t<e.lacingValues.length);let n=0;for(let r=0;r<t;r++)n+=e.lacingValues[r];let r=e,i=n,a=t,o=[];outer:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=await t),B(t);let s=Y(t,r.dataSize);for(;;){if(a===r.lacingValues.length){o.push(s.subarray(n,i));break}let e=r.lacingValues[a];if(i+=e,e<255){o.push(s.subarray(n,i));break outer}a++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=Nh(t);if(!n)return null;if(r=n,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}n=0,i=0,a=0}let s=o.reduce((e,t)=>e+t.length,0);if(s===0)return null;let c=new Uint8Array(s),l=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,l),l+=t.length}return{data:c,endPage:r,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=Nh(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),jh({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ih=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new wd,this.internalSampleRate=e.codecInfo.codec===`opus`?Rf:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return B(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return B(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Cf,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(B(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=Ah(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new mm(n.metadataOnly?pm:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){B(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec===`opus`&&(B(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=Hd(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;B(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=r.startPage,a=this.demuxer.reader.fileSize,o=[i];outer:for(;i.headerStartPos+i.totalSize<a;){let e=i.headerStartPos,t=Math.floor((e+a)/2),r=t;for(;;){let e=Math.min(r+Mh,a-27),s=this.demuxer.reader.requestSlice(r,e-r);if(s instanceof Promise&&(s=await s),B(s),!Ph(s,e)){a=t+27;continue outer}let c=this.demuxer.reader.requestSliceRange(s.filePos,27,282);c instanceof Promise&&(c=await c),B(c);let l=Nh(c);B(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),B(e),u=kh(Y(e,l.totalSize))===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(l.granulePosition===-1){r=l.headerStartPos+l.totalSize;continue}this.granulePositionToTimestampInSamples(l.granulePosition)>n?a=l.headerStartPos:(i=l,o.push(l));continue outer}}let s=r.startPage;for(let e of o){if(e.granulePosition===i.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s,l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==i.granulePosition;){let e=c.headerStartPos+c.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),B(t);let n=Nh(t);B(n),c=n,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}B(c.granulePosition!==-1);let u=null,d,f,p=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{d=0,f=!1;for(let e=c.lacingValues.length-1;e>=0;e--)if(c.lacingValues[e]<255){u=e+1;break}if(u===null)throw Error(`Invalid page with granule position: no packets end on this page.`);m=u-1;let e={data:pm,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=Rh(l,c,u);B(e);let t=Lh(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=Rh(l,c,u);if(!e)break;let t=Lh(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,u=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,m=e.segmentIndex;break}}}let h=null,g=null;for(;c!==null;){B(u!==null);let e=await this.demuxer.readPacket(c,u);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&u<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);B(r);let i=this.encodedPacketToMetadata.get(r);if(B(i),!f&&e.endPage.headerStartPos===p.headerStartPos&&e.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(c.granulePosition),f=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d-i.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),B(r),i=this.encodedPacketToMetadata.get(r),B(i)):d+=i.durationInSamples,h=r,g=i,f&&(Math.max(d,0)>n||Math.max(i.timestampInSamples,0)===n))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;c=i.startPage,u=i.startSegmentIndex}return h}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let n=Hd(e*this.internalSampleRate);e=n/this.internalSampleRate;let r=U(this.sequentialScanCache,n,e=>e.timestampInSamples),i;if(r!==-1){let e=this.sequentialScanCache[r];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let a=0;for(;i&&i.timestamp<e;){let n=await this.getNextPacket(i,t);if(!n||n.timestamp>e)break;if(i=n,a++,a===100){a=0;let e=this.encodedPacketToMetadata.get(i);B(e),this.sequentialScanCache.length>0&&B(fd(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Lh=(e,t,n)=>{let r=t,i=n;outer:for(;;){for(i--;i>=0;i--)if(r.lacingValues[i]<255){i++;break outer}if(B(i===-1),!(r.headerType&1)){i=0;break}let t=Nd(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,i=r.lacingValues.length}if(B(i!==-1),i===r.lacingValues.length){let t=e[e.indexOf(r)+1];B(t),r=t,i=0}return{page:r,segmentIndex:i}},Rh=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=Nd(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},zh;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(zh||={});var Bh=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),B(e);let t=$(e,4),n=t!==`RIFX`,r=t===`RF64`,i=Ev(e,n),a=r?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if($(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let o=0,s=null,c=e.filePos;for(;a===null||c<a;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;let t=$(e,4),i=Ev(e,n),l=e.filePos;if(r&&o===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(l,i,n);else if(t===`data`){if(s??=i,this.dataStart=e.filePos,this.dataSize=Math.min(s,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(l,i);if(e instanceof Promise&&(e=await e),!e)break;let t=Av(e,n);s=Av(e,n),a=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(l,i,n):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(l,i);c=l+i+(i&1),o++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.trackBackings.push(new Hh(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=Cv(r,n),a=Cv(r,n),o=Ev(r,n);r.skip(4);let s=Cv(r,n),c;if(c=t===14?8:Cv(r,n),t>=18&&i!==357){let e=Cv(r,n),a=t-18;if(Math.min(a,e)>=22&&i===zh.EXTENSIBLE){r.skip(6);let e=Y(r,16);i=e[0]|e[1]<<8}}if((i===zh.MULAW||i===zh.ALAW)&&(c=8),i!==zh.PCM&&i!==zh.IEEE_FLOAT&&i!==zh.ALAW&&i!==zh.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===zh.PCM&&![8,16,24,32].includes(c))throw Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(i===zh.IEEE_FLOAT&&![32,64].includes(c))throw Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=$(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=$(r,4),t=Ev(r,n),i=Y(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=Hv(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&Uv(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(B(this.audioInfo),this.audioInfo.format===zh.MULAW)return`ulaw`;if(this.audioInfo.format===zh.ALAW)return`alaw`;if(this.audioInfo.format===zh.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}if(this.audioInfo.format===zh.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return`pcm-f32`;if(this.audioInfo.sampleSizeInBytes===8)return`pcm-f64`}B(!1)}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Vh=2048,Hh=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(B(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return B(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Cf}}async getPacketAtIndex(e,t){B(e>=0),B(this.demuxer.audioInfo);let n=e*Vh*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(Vh*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);if(e instanceof Promise&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=pm;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);e instanceof Promise&&(e=await e),B(e),i=Y(e,r)}let a=e*Vh/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new mm(i,`key`,a,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){B(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Vh,(this.demuxer.dataSize-1)/(Vh*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let r=await this.getPacketAtIndex(n,t);if(r)return r;if(n===0)return null;B(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){B(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Vh);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Uh=e=>{let t=e.filePos,n=new G(Y(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},Wh=1024,Gh=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new wd,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();B(this.firstFrameHeader),this.trackBackings=[new Kh(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Hv(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Uh(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let n=wf[t.samplingFrequencyIndex];B(n!==void 0);let r=Wh/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=Wh,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=Hv(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;Uv(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},Kh=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Wh}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return B(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){B(this.demuxer.firstFrameHeader);let e=Tf[this.demuxer.firstFrameHeader.channelConfiguration];return B(e!==void 0),e}getSampleRate(){B(this.demuxer.firstFrameHeader);let e=wf[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return B(e!==void 0),e}getDisposition(){return{...Cf}}async getDecoderConfig(){return B(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=pm;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=Y(e,n.dataSize)}return new mm(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=kd(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},qh=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,Jh=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},Yh=e=>{let t=0,n=new G(Y(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new G(Y(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},Xh=(e,t)=>{if(t===`uncommon-u16`)return Z(e)+1;if(t===`uncommon-u8`)return X(e)+1;if(typeof t==`number`)return t;Ld(t),B(!1)},Zh=(e,t)=>t===`uncommon-u16`?Z(e):t===`uncommon-u16-10`?Z(e)*10:t===`uncommon-u8`?X(e):typeof t==`number`?t:null,Qh=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},$h=class extends fm{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new wd,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),B(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let n=Hv(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);r instanceof Promise&&(r=await r),B(r),Uv(r,n,this.metadataTags),e=t.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);B(t);let n=X(t),r=wv(t),i=!!(n&128);switch(n&127){case Lp.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(t instanceof Promise&&(t=await t),B(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=Y(t,34),i=new G(n),a=i.readBits(16),o=i.readBits(16),s=i.readBits(24),c=i.readBits(24),l=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);let d=i.readBits(36);i.skipBits(128);let f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.trackBacking=new eg(this);break}case Lp.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),B(t),Rp(Y(t,r),this.metadataTags);break}case Lp.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),B(t);let n=Q(t),i=Q(t),a=hd.decode(Y(t,i)),o=Q(t),s=hd.decode(Y(t,o));t.skip(16);let c=Q(t),l=Y(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:a,kind:n===3?`coverFront`:n===4?`coverBack`:`unknown`,description:s});break}}if(e+=r,i){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error(`Missing STREAMINFO metadata block! Corrupted FLAC file.`)})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){B(this.audioInfo);let n=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,i=(this.audioInfo.maximumFrameSize||n)+16,a=await this.reader.requestSliceRange(e,16,i);if(!a)return null;let o=this.readFlacFrameHeader({slice:a,isFirstPacket:t});if(!o)return null;for(a.filePos=e+r;;){if(a.filePos>a.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:a.end-e,isLastFrame:!0};if(X(a)===255){let t=a.filePos;if(X(a)!==(this.blockingBit===1?249:248)){a.filePos=t;continue}a.skip(-2);let n=a.filePos-e,r=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!r){a.filePos=t;continue}if(this.blockingBit===0){if(r.num-o.num!==1){a.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){a.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,r=new G(Y(e,4));if(r.readBits(15)!==32764)return null;if(this.blockingBit===null){B(t);let e=r.readBits(1);this.blockingBit=e}else if(this.blockingBit===1){if(B(!t),r.readBits(1)!==1)return null}else if(this.blockingBit===0){if(B(!t),r.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let i=qh(r.readBits(4));if(!i)return null;B(this.audioInfo);let a=Jh(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=Yh(e),s=Xh(e,i),c=Zh(e,a);if(c===null||c!==this.audioInfo.sampleRate)return null;let l=e.filePos-n,u=X(e);return e.skip(-l),e.skip(-1),u===Qh(Y(e,l))?{num:o,blockSize:s,sampleRate:c}:null}async advanceReader(){await this.readMetadata(),B(this.lastLoadedPos!==null),B(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}},eg=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return B(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Cf}}async getDecoderConfig(){return B(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(B(this.demuxer.audioInfo),e<0)return null;let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=U(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=pm;else{let e=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=Y(e,n.byteSize)}B(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new mm(r,`key`,i,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},tg=9e4,ng=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},rg=`PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`,ig=5,ag=1212435798,og=1212436562,sg=1146376960,cg=new Set([133,134,162]),lg=new Set,ug=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),B(e);let t=Y(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let n=this.packetOffset,r=null,i=!1,a=!1;for(;;){let e=await this.readPacketHeader(n);if(!e)break;if(e.payloadUnitStartIndicator===0){n+=this.packetStride;continue}if(a&&!this.elementaryStreams.some(t=>t.pid===e.pid)){n+=this.packetStride;continue}let t=await this.readSection(n,!0,!a);if(!t)break;let o=!1;if(!a&&t.pid!==0&&(t.payload[0]!==0||t.payload[1]!==0||t.payload[2]!==1)){let e=new G(t.payload),n=e.readAlignedByte();e.skipBits(8*n),o=e.readBits(8)===2}if(t.pid===0&&!i){let e=new G(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let n=e.readBits(13);if(t!==0){if(r!==null)throw Error(`Only files with a single program are supported.`);r=n}}if(r===null)throw Error(`Program Association Table must link to a Program Map Table.`);i=!0}else if((t.pid===r||o)&&!a){let e=new G(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10),o=e.pos+8*i,s=!1;for(;e.pos<o;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===ig&&n>=4){let t=e.readBits(32);s||=t===ag||t===og}e.pos=r}for(e.pos=o;8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1,c=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===106)a=!0;else if(t===122||t===204)o=!0;else if(t===123)c=!0;else if(t===ig&&n>=4){let t=e.readBits(32);c||=(t&4294967040)===sg}e.pos=r}let l=null,u=s&&cg.has(t)?130:t;switch(u){case 27:case 36:l={type:`video`,codec:t===27?`avc`:`hevc`,decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=u===3||u===4?`mp3`:u===15?`aac`:u===129?`ac3`:u===135?`eac3`:`dts`,l={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?l={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:a?l={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:c&&(l={type:`audio`,codec:`dts`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:lg.has(t)||(W._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),lg.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}a=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);outer:if(e&&!e.initialized){let n=fg(t,!0);if(!n)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=t.randomAccessIndicator===1,this.input._initInput){let n=(await this.input._initInput._getDemuxer()).elementaryStreams.find(n=>n.pid===t.pid&&n.info.codec===e.info.codec);if(n){e.info=n.info,e.initialized=!0;break outer}}let r=new _g(e,n);if(e.info.type===`video`){for(;;){let t=r;if(t.suppliedPacket=null,await r.markNextPacket(),e.info.codec===`avc`){if(!r.suppliedPacket)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.`);if(e.info.avcCodecInfo=up(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];B(t);let n=pp(t);e.info.width=n.displayWidth,e.info.height=n.displayHeight;let i=n.pixelAspectRatio.num,a=n.pixelAspectRatio.den;i>0&&a>0&&(i>a?(e.info.squarePixelWidth=Math.round(e.info.width*i/a),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*a/i))),e.info.colorSpace={primaries:vd[n.colourPrimaries],transfer:bd[n.transferCharacteristics],matrix:Sd[n.matrixCoefficients],fullRange:!!n.fullRangeFlag},e.info.reorderSize=n.maxDecFrameBuffering;break}if(e.info.codec===`hevc`){if(!r.suppliedPacket)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);if(e.info.hevcCodecInfo=yp(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===ep.SPS_NUT).nalUnits[0];B(t);let n=vp(t);e.info.width=n.displayWidth,e.info.height=n.displayHeight,n.pixelAspectRatio.num>n.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*n.pixelAspectRatio.num/n.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n.pixelAspectRatio.den/n.pixelAspectRatio.num)),e.info.colorSpace={primaries:vd[n.colourPrimaries],transfer:bd[n.transferCharacteristics],matrix:Sd[n.matrixCoefficients],fullRange:!!n.fullRangeFlag},e.info.reorderSize=n.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:If({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},(e.info.width!==e.info.squarePixelWidth||e.info.height!==e.info.squarePixelHeight)&&(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if(e.info.codec===`aac`){let t=Uh(xv.tempFromBytes(r.suppliedPacket.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=Tf[t.channelConfiguration],e.info.sampleRate=wf[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=qf(Q(xv.tempFromBytes(r.suppliedPacket.data)),r.suppliedPacket.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=Xf(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=Bp(r.suppliedPacket.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=zp[t.acmod]+t.lfeon,e.info.sampleRate=Zf[t.fscod]}else if(e.info.codec===`eac3`){let t=Wp(r.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=Kp(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=qp(t),e.info.sampleRate=n}else if(e.info.codec===`dts`){let t=om(r.suppliedPacket.data);if(!t)throw Error(`Invalid DTS audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?`dtsh`:`dtsc`)}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:Lf({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}if(a&&this.elementaryStreams.every(e=>e.initialized))break;n+=this.packetStride}if(!a)throw Error(i?`No Program Map Table found in the file.`:`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.initialized&&(e.info.type===`video`?this.trackBackingEntries.push(new mg(e)):this.trackBackingEntries.push(new hg(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),ng(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(kd(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=U(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(X(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=Z(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=X(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=Y(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}},dg=(e,t)=>{if(e.payload.byteLength<3)return null;let n=new G(e.payload);if(n.readBits(24)!==1)return null;let r=n.readBits(8);if(n.skipBits(16),r===188||r===190||r===191||r===240||r===241||r===255||r===242||r===248)return null;n.skipBits(8);let i=n.readBits(2);n.skipBits(14);let a=null;if(i===2||i===3)a=0,n.skipBits(4),a+=n.readBits(3)*(1<<30),n.skipBits(1),a+=n.readBits(15)*32768,n.skipBits(1),a+=n.readBits(15);else if(t)throw Error(rg);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:a,randomAccessIndicator:e.randomAccessIndicator}},fg=(e,t)=>{B(e.endPos!==null);let n=dg(e,t);if(!n)return null;let r=new G(e.payload);r.skipBits(32);let i=r.readBits(16);r.skipBits(16);let a=r.readBits(8),o=r.pos+8*a;r.pos=o;let s=o/8;B(Number.isInteger(s));let c=e.payload.subarray(s,i>0?6+i:e.payload.byteLength);return{...n,data:c}},pg=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,n=this.elementaryStream.info.type,r=0;for(let i of t.trackBackingEntries)if(i.getType()===n&&r++,B(i instanceof e),i.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...Cf,primary:!1}}getTimeResolution(){return tg}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new mm(n.metadataOnly?pm:e.data,r,e.pts/tg,Math.max(t/tg,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;B(t);let n=fg(t,!0);B(n);let r=new _g(this.elementaryStream,n),i=new vg(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let r=await n.readNext();if(!r)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(i,n),this.packetSectionStarts.set(i,r.packet.sectionStartPos),i}let r=this.packetSectionStarts.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);let i=await this.elementaryStream.demuxer.readSection(r,!0);B(i);let a=fg(i,!0);B(a);let o=new _g(this.elementaryStream,a);n=new vg(this,o);let s=e.sequenceNumber;for(;;){let e=await n.readNext();if(!e)return null;if(e.packet.sequenceNumber>s){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,n),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let r=Hd(e*tg),i=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=i,s=this.elementaryStream.pid,c=async(e,t,n)=>{let r=e;for(;r<t;){let e=await i.readPacketHeader(r);if(!e)return null;if(e.pid===s&&e.payloadUnitStartIndicator===1){let e=await i.readSection(r,n);if(!e)return null;let t=dg(e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=i.packetStride}return null},l=this.elementaryStream.firstSection;B(l);let u=dg(l,!0);if(B(u),r<u.pts)return null;let d,f=this.elementaryStream.referencePesPackets,p=U(f,r,e=>e.pts),m=p===-1?null:f[p];if(m&&r-m.pts<45e3)d=m.sectionStartPos;else{let e=0;if(a.fileSize!==null){let t=Math.ceil(a.fileSize/o);if(t>1){let n=0,a=t-1;for(e=n;n<=a;){let t=Math.floor((n+a)/2),s=Gd(t*o,i.packetStride)+u.sectionStartPos,l=await c(s,s+o,!1);if(!l){a=t-1;continue}l.pesPacketHeader.pts<=r?(e=t,n=t+1):a=t-1}}}d=Gd(e*o,i.packetStride)+u.sectionStartPos}let h=(await c(d,a.fileSize??1/0,!1))?.pesPacketHeader??null;h||=u;let g=this.getReorderSize(),_=async(e,t)=>{let a=await i.readSection(e,!0);B(a);let o=fg(a,!0);B(o);let s=new _g(this.elementaryStream,o),c=new vg(this,s);for(;!((fd(c.presentationOrderPackets)?.pts??-1/0)>=r||!await c.readNextPacket()););let l=Pd(c.presentationOrderPackets,t);if(l===-1)return null;let u=c.presentationOrderPackets[l],d=l===0?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;let f=await c.readNext();B(f);let p=this.createEncodedPacket(f.packet,f.duration,n);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=h.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=dg(t,!1);if(e&&e.pts!==null){if(e.pts>r)break outer;h=e,gg(this.elementaryStream,h);break}}}e+=i.packetStride}}outer:for(let e=0;e<g+1;e++){let e=h.sectionStartPos-i.packetStride;for(;e>=i.packetOffset;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=dg(t,!1);if(e&&e.pts!==null){h=e;break}}}e-=i.packetStride}}return _(h.sectionStartPos,e=>e.pts<=r)}{let e=d,t=null,n=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let d=null,f=e<=u.sectionStartPos,p,m=null;if(f)p=u,m=l;else{let t=await c(e,a.fileSize??1/0,n);p=t?.pesPacketHeader??null,m=t?.section??null}let h=!1,v=0;outer:for(;p&&!(t!==null&&p.sectionStartPos>=t);){if(p.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=p.randomAccessIndicator===1;else{B(m);let t=fg(m,!0);B(t);let n=new _g(this.elementaryStream,t);await n.markNextPacket(),e=n.suppliedPacket?.randomAccessIndicator===1}e&&(d=p)}if(p.pts>r&&(h=!0),h&&(v++,v>g))break;let e=p.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,n);if(t){let e=dg(t,!1);if(e&&e.pts!==null){p=e,m=t,gg(this.elementaryStream,p);break}}}e+=i.packetStride}}if(d){let e=d;if(v===0)outer:for(let t=0;t<g;t++){let t=e.sectionStartPos-i.packetStride;for(;t>=i.packetOffset;){let r=await i.readPacketHeader(t);if(!r)break outer;if(r.pid===s&&r.payloadUnitStartIndicator===1){let r=await i.readSection(t,n);if(r){let t=dg(r,!1);if(t&&t.pts!==null){e=t;break}}}t-=i.packetStride}}let t=await _(e.sectionStartPos,e=>e.pts<=r&&e.randomAccessIndicator===1);return B(t),t}if(f)return null;t=e,e=Math.max(Gd(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},mg=class extends pg{getType(){return`video`}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return B(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},hg=class extends pg{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return B(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},gg=(e,t)=>{let n=e.referencePesPackets,r=U(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},_g=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return B(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=fd(this.pesPackets).sectionEndPos;for(B(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=fg(n,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){B(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type===`video`){let t=e.info.codec,n=1024;if(t!==`avc`&&t!==`hevc`)throw Error(`Unhandled.`);let r=t===`avc`?1:2,i=null,a=!1,o=0;for(;;){let e=this.ensureBuffered(n);if(e instanceof Promise&&(e=await e),e===0)break;let s=this.currentPos,c=this.readBytes(e),l=c.byteLength,u=0;for(;u<l;){let e=c.indexOf(0,u);if(e===-1||e>=l)break;u=e;let n=s+u;if(u+3>=l){this.seekTo(n);break}let d=c[u+1],f=c[u+2],p=c[u+3],m=0;if(d===0&&f===0&&p===1?m=4:d===0&&f===1&&(m=3),m===0){u++;continue}let h=n;i??=h;let g=u+m,_=g+r;if(_+(t===`avc`?6:1)>l){this.seekTo(n);break}let v=c[g],y,b,x;if(t===`avc`)y=ip(v),b=y===$f.NON_IDR_SLICE||y===$f.SLICE_DPA||y===$f.IDR,x=y===$f.SEI||y===$f.SPS||y===$f.PPS||y===$f.AUD;else{if(y=_p(v),((v&1)<<5|c[g+1]>>3)>0){u+=m;continue}b=y<=ep.RASL_R||y>=ep.BLA_W_LP&&y<=21,x=y>=ep.VPS_NUT&&y<=37||y===ep.PREFIX_SEI_NUT||y>=41&&y<=44||y>=48&&y<=55}let S=!1;if(b){let e;if(t===`avc`){let t=V(new G(c.subarray(_,_+6)));e=!a||t<=o,o=t}else e=c[_]>>7==1;e&&(a?S=!0:a=!0)}else x&&a&&(S=!0);if(S){let e=h-i;return this.seekTo(i),this.supplyPacket(e,0)}u+=m}if(e<n)break}if(i!==null&&this.endPos>i){let e=this.endPos-i;return this.seekTo(i),this.supplyPacket(e,0)}}else{let t=e.info.codec;for(;;){let n=this.ensureBuffered(128);n instanceof Promise&&(n=await n);let r=this.currentPos;for(;this.currentPos-r<n;){let n=this.readU8();if(t===`aac`){if(n!==255)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(9);if(r instanceof Promise&&(r=await r),r<9)return;let i=this.readBytes(9),a=Uh(xv.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return n instanceof Promise&&(n=await n),this.supplyPacket(n,Math.round(Wh*tg/e.info.sampleRate))}this.seekTo(t+1)}else if(t===`mp3`){if(n!==255)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(4);if(r instanceof Promise&&(r=await r),r<4)return;let i=qf(H(this.readBytes(4)).getUint32(0),null);if(i.header){this.seekTo(t);let n=this.ensureBuffered(i.header.totalSize);n instanceof Promise&&(n=await n);let r=i.header.audioSamplesInFrame*tg/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}this.seekTo(t+1)}else if(t===`ac3`){if(n!==11)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(r instanceof Promise&&(r=await r),r<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=i[4]>>6,o=i[4]&63;if(a===3||o>37){this.seekTo(t+1);continue}let s=Vp[3*o+a];B(s!==void 0),this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=await r);let c=Math.round(Hp*tg/e.info.sampleRate);return this.supplyPacket(r,c)}else if(t===`eac3`){if(n!==11)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(r instanceof Promise&&(r=await r),r<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=(((i[2]&7)<<8|i[3])+1)*2,o=Up[i[4]>>6==3?3:i[4]>>4&3];this.seekTo(t),r=this.ensureBuffered(a),r instanceof Promise&&(r=await r);let s=o*256,c=Math.round(s*tg/e.info.sampleRate);return this.supplyPacket(r,c)}else if(t===`dts`){if(n!==127&&n!==100)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(18);if(r instanceof Promise&&(r=await r),r<18)return;let i=this.readBytes(18),a=cm(i),o=a?null:lm(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,Jp),n=this.ensureBuffered(e);n instanceof Promise&&(n=await n),o=lm(this.readBytes(n))??o}let s=a?a.frameSize:o.frameSize;if(a){let e=Math.ceil(a.frameSize/4)*4;for(;;){this.seekTo(t);let n=e+10,r=this.ensureBuffered(n);if(r instanceof Promise&&(r=await r),r<n)break;this.seekTo(t+e);let i=lm(this.readBytes(10));if(!i)break;e+=i.frameSize,s=e}}let c=a?.sampleCount??o.asset?.sampleCount;if(c===void 0){this.seekTo(t+1);continue}this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=await r);let l=Math.round(c*tg/e.info.sampleRate);return this.supplyPacket(r,l)}else throw Error(`Unhandled.`)}if(n<128)break}}}supplyPacket(e,t){let n=this.getCurrentPesPacket(),r;if(this.lastSuppliedPesPacket===n)B(this.nextPts!==null),r=this.nextPts;else{if(n.pts===null)throw Error(rg);r=n.pts,gg(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=r+t;let i=n.sectionStartPos,a=i+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),s=n.randomAccessIndicator;if(s===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)s=1;else if(this.elementaryStream.info.decoderConfig){let e=Ip(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)===`key`;s=Number(e)}}this.suppliedPacket={pts:r,data:o,sequenceNumber:a,sectionStartPos:i,randomAccessIndicator:s},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},vg=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),B(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);B(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(B(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},yg=`application/vnd.apple.mpegurl`,bg=`#EXT-X-STREAM-INF:`,xg=`#EXT-X-I-FRAME-STREAM-INF:`,Sg=`#EXT-X-MEDIA:`,Cg=`#EXTINF:`,wg=`#EXT-X-MAP:`,Tg=`#EXT-X-KEY:`,Eg=`#EXT-X-MEDIA-SEQUENCE:`,Dg=`#EXT-X-BYTERANGE:`,Og=`#EXT-X-PROGRAM-DATE-TIME:`,kg=`#EXT-X-TARGETDURATION:`,Ag=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`),jg=class{constructor(e){this._attributes={};let t=``,n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];o===`"`?i=!i:o===`=`&&!r&&!i?r=!0:o===`,`&&!i?(t&&(this._attributes[t.trim().toLowerCase()]=n),t=``,n=``,r=!1):r?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}},Mg=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type===`video`){let n=mf(e,e=>e.getType()===`video`)+1;e.push(new Pg(this,t,n))}else if(t.type===`audio`){let n=mf(e,e=>e.getType()===`audio`)+1;e.push(new Fg(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of t)if(n.type===`video`){let t=mf(e,e=>e.getType()===`video`)+1;e.push(new Pg(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=mf(e,e=>e.getType()===`audio`)+1;e.push(new Fg(this,{id:e.length+1,type:`audio`},t))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,r;if(this.firstSegmentFirstTimestamps.has(n))r=this.firstSegmentFirstTimestamps.get(n);else{let e=this.getInputForSegment(n);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(n,r)}if(n===e)return n.timestamp-r;let i=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,o=i-r-a;return Math.abs(o)<=Math.min(.25,a)?n.timestamp-r:e.timestamp-i}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Ng=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error(`Missing first segment, can't retrieve track.`);let e=this.segmentedInput.firstSegment,t=null;for(;e&&(t=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=t,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),B(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){B(e.sequenceNumber>=0),B(this.segmentedInput.firstSegment);let r=await this.segmentedInput.getMediaOffset(t,n.input),i=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Wd(e.timestamp+r,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*i)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),B(this.firstInputTrack),B(this.firstSegment);let t=this.firstInputTrack,n=this.firstSegment;for(;;){if(t){let r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,n,t)}if(n=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait}),!n)break;t=(await this.segmentedInput.getInputForSegment(n).getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let r=this.packetInfos.get(e);if(!r)throw Error(`Packet was not created from this track.`);let i=n?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(i)return this.createAdjustedPacket(i,r.segment,r.track);let a=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!e)return null;let n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){a=e;continue}let i=await n._backing.getFirstPacket(t);return i?this.createAdjustedPacket(i,e,n):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){let i=this.segmentedInput.getInputForSegment(r),a=(await i.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!a){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}let o=e-await this.segmentedInput.getMediaOffset(r,i),s=n?await a._backing.getKeyPacket(o,t):await a._backing.getPacket(o,t);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(s,r,a)}return null}},Pg=class extends Ng{getType(){return`video`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Fg=class extends Ng{getType(){return`audio`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};o(((e,t)=>{t.exports={}}))(),df();var Ig=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var Lg=class extends yf{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<`u`&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new yv;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Ig),e=this._getFileSize(),B(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new yv;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new Wg(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Rg(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Rg=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;B(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},zg=class extends Lg{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof Lg||e instanceof Rg))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Lg?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(n):n(t)}},Bg=(e,t)=>e.path===t.path,Vg=class extends zg{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,r){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof Lg?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),B(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,n,r))}return this._root.source._read(e,t,n,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},Hg=class extends Lg{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=md(e),this._view=H(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Ug=class extends Lg{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError(`stream must be a ReadableStream.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!ff(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=U(this._cache,e,e=>e.start),r=n===-1?null:this._cache[n];if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let i=e,a=new Uint8Array(t-e);if(n!==-1)for(let r=n;r<this._cache.length;r++){let n=this._cache[r];if(n.start>=t)break;let o=Math.max(e,n.start);o>i&&this._throwDueToCacheMiss();let s=Math.min(t,n.end);o<s&&(a.set(n.bytes.subarray(o-n.start,s-n.start),o-e),i=s)}if(i===t)return{bytes:a,view:H(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=jd();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:s,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else throw e})),o}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(n,r);for(let e=0;e<this._pendingSlices.length;e++){let i=this._pendingSlices[e],a=Math.max(n,i.start),o=Math.min(r,i.end);a<o&&(i.bytes.set(t.subarray(a-n,o-n),a-i.start),o===i.end&&(i.resolve({bytes:i.bytes,view:H(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:H(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new yv);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Wg=class extends Lg{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:Vd(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return i instanceof Promise?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},Gg=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Kg=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r}),qg=/^0[xX][0-9a-fA-F]+$/,Jg=/^data:.*;base64,/i,Yg=class extends Mg{constructor(e,t,n,r){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await vf(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let t={stack:[],error:void 0,hasError:!1};try{let n=Gg(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=await new bv(n.source).requestEntireFile();B(r),e=Iv(r,r.length,{ignore:Ag}),n.source instanceof zg&&(this.rootPath=n.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{Kg(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=!1,r=0,i=null,a=null,o=null,s=0,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=fd(this.segments)??null,g=e=>{let t=e.indexOf(`@`),n=Number(t===-1?e:e.slice(0,t));if(!Number.isInteger(n)||n<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(t!==-1&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:n,offset:r}},_=e=>{s=e,h&&(B(h.sequenceNumber!==null),h.sequenceNumber<e&&(r=h.timestamp+h.duration,c=h.firstSegment,l=h.initSegment,f=h.lastProgramDateTimeSeconds,i=h.unixEpochTimestamp===null?null:h.unixEpochTimestamp+h.duration,h=null))};for(let v=0;v<e.length;v++){let y=e[v];if(!n){if(y!==`#EXTM3U`)throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);n=!0;continue}if(!y.startsWith(`#`)){if(!h){if(a===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=o;if(e&&e.method===`AES-128`&&!e.iv){let t=new Uint8Array(16),n=H(t);n.setUint32(8,Math.floor(s/2**32)),n.setUint32(12,s),e={...e,iv:t}}let t={path:pf(this.rootPath,y),offset:d?.offset??0,length:d?.length??null},n={timestamp:r,unixEpochTimestamp:i,firstSegment:c,sequenceNumber:s,location:t,duration:a,encryption:e,initSegment:l,lastProgramDateTimeSeconds:f};c??=n,r+=a,i!==null&&(i+=a),this.segments.push(n)}a=null,d===null?u=null:d=null,_(s+1)}if(y.startsWith(`#EXTINF:`)){if(h){m=!0;continue}m||=(f===null&&s>0&&p!==null&&(r=s*p),!0);let e=y.slice(Cg.length),t=e.indexOf(`,`),n=t===-1?e:e.slice(0,t),i=Number(n);if(!Number.isFinite(i)||i<0)throw Error(`Invalid #EXTINF tag duration '${n}'.`);a=i}else if(y.startsWith(`#EXT-X-MAP:`)){let e=new jg(y.slice(wg.length)),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),s=null;if(n!==null&&(s=g(n)),s&&s.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!h){let e={path:pf(this.rootPath,t),offset:s?.offset??0,length:s?.length??null};if(o?.method===`AES-128`&&!o.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);l={timestamp:r,unixEpochTimestamp:i,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:f}}a=null,d===null?u=null:d=null}else if(y.startsWith(`#EXT-X-KEY:`)){let e=new jg(y.slice(Tg.length)),t=e.get(`method`);if(t===`NONE`)o=null;else if(t===`AES-128`){let t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-KEY: AES-128 requires a URI attribute.`);let n=null,r=e.get(`iv`);if(r){if(!qg.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),n=new Uint8Array(16);for(let t=0;t<16;t++){let r=-32+t;n[t]=parseInt(e.slice(r,r+2),16)}}let i=e.get(`keyformat`)??`identity`;if(i!==`identity`)throw Error(`For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.`);o={method:`AES-128`,keyUri:pf(this.rootPath,t),iv:n,keyFormat:i}}else if(t===`SAMPLE-AES`||t===`SAMPLE-AES-CTR`){let n=e.get(`uri`);if(!n)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if((e.get(`keyformat`)??`identity`)===`identity`)throw Error(`For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.`);let r=null;if(Jg.test(n)){let e=n.indexOf(`,`),t=lf(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=H(t).getUint32(0);r=gm(t.subarray(8,Math.min(e,t.length)))}}o={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(y.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)){let e=y.slice(Eg.length),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);_(t)}else if(y.startsWith(`#EXT-X-BYTERANGE:`)){let e=g(y.slice(Dg.length));if(e.offset===null){if(u===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=u}d=e,u=e.offset+e.length}else if(y.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(h)continue;let e=y.slice(Og.length),n=Date.parse(e);if(!Number.isFinite(n))continue;let a=n/1e3;if(f===a)continue;if(f===null&&this.segments.length>0){let e=fd(this.segments),n=a-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+n,t&&(e.timestamp=e.unixEpochTimestamp)}f=a,i=a,t&&(r=a)}else if(y===`#EXT-X-DISCONTINUITY`)c=null;else if(y.startsWith(`#EXT-X-TARGETDURATION:`)){let e=y.slice(kg.length),t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,p=t}else if(y===`#EXT-X-ENDLIST`){this.streamHasEnded=!0;break}else y.startsWith(`#EXT-X-PLAYLIST-TYPE:`)&&y.slice(21).toLowerCase()===`vod`&&(this.streamHasEnded=!0)}if(!n)throw Error(`Invalid M3U8 file; no #EXTM3U header.`)}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let r=U(this.segments,e,e=>e.timestamp);if(r===-1)return null;if(r<this.segments.length-1||this.streamHasEnded||n)return this.segments[r];let i=this.segments[r];if(e<i.timestamp+i.duration)return i;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let n=this.segments.indexOf(e);B(n!==-1);let r=n+1,i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(r<this.segments.length)return this.segments[r];if(this.streamHasEnded||i)return null;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return B(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,n=this.inputCache.find(e=>e.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));let i={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||t.encryption.method!==`SAMPLE-AES`&&t.encryption.method!==`SAMPLE-AES-CTR`||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let n=e.psshBoxes,{psshBox:r}=t.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!n.some(e=>_m(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},a=new _v({source:new Vg(t.location.path,async e=>{B(e.isRoot);let n={...e,isRoot:!1},r,i=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method===`SAMPLE-AES`||t.encryption.method===`SAMPLE-AES-CTR`){if(r=await this.input._getSourceCached(n),i){let e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}}else if(t.encryption.method===`AES-128`){let e=t.encryption;B(e.iv);let a=await this.input._getSourceCached(n);if(i){let e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}r=new Ug(Pm(new bv(a.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new bv(Gg(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!n)throw Error(`Invalid AES-128 key; expected at least 16 bytes of data.`);return{key:Y(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{Kg(t)}},()=>{a.free()})).ref()}else B(!1);return r}),formats:this.input._formats.filter(e=>!(e instanceof h_)),initInput:r??void 0,formatOptions:i});if(a._onFormatDetermined=e=>{if((t.encryption?.method===`SAMPLE-AES`||t.encryption?.method===`SAMPLE-AES-CTR`)&&!e._isIsobmff)throw Error(`The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.`)},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=hf(this.inputCache,e=>e.age);B(e!==-1),this.inputCache.splice(e,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},Xg=class extends fm{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{B(this.input._rootSource instanceof zg);let e=await this.input._reader.requestEntireFile();B(e);let t=Iv(e,e.length,{ignore:Ag}),{rootPath:n}=this.input._rootSource,r=[],i=[];for(let e=1;e<t.length;e++){let a=t[e];if(a.startsWith(`#EXT-X-STREAM-INF:`)){let i=e,o=t[++e];if(o===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);let s=pf(n,o),c=new jg(a.slice(bg.length));if(c.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);r.push({fullPath:s,attributes:c,lineNumber:i,hasOnlyKeyPackets:!1})}else if(a.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let t=new jg(a.slice(xg.length)),i=t.get(`uri`);if(i===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(t.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);let o=pf(n,i);r.push({fullPath:o,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(a.startsWith(`#EXT-X-MEDIA:`)){let t=new jg(a.slice(Sg.length));if(t.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(t.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let r=null,o=t.get(`uri`);o!==null&&(r=pf(n,o)),i.push({fullPath:r,attributes:t,lineNumber:e})}else if(a!==`#EXT-X-I-FRAMES-ONLY`&&a.startsWith(`#EXTINF:`)){let e=new Yg(this,n,null,t);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}let a=[...new Set(i.filter(e=>e.attributes.get(`type`).toLowerCase()===`video`).map(e=>e.attributes.get(`group-id`)))],o=[...new Set(i.filter(e=>e.attributes.get(`type`).toLowerCase()===`audio`).map(e=>e.attributes.get(`group-id`)))],s=await Promise.all(r.map(async(e,t)=>{let r=[],s=e.attributes.get(`codecs`),c;if(s)c=s.split(`,`).map(e=>e.trim());else{let t=await this.getSegmentedInputForPath(e.fullPath).getTrackBackings(),n=await Promise.all(t.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let l=e.attributes.get(`video`),u=e.attributes.get(`audio`),d=c.some(e=>Df.includes(Vf(e))),f=c.some(e=>kf.includes(Vf(e)));if(l!==null&&!d){if(!a.includes(l))throw Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);let e=i.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===l&&n.toLowerCase()===`video`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let r=pf(n,t),i=(await this.getSegmentedInputForPath(r).getTrackBackings()).find(e=>e.getType()===`video`);if(!i||await i.getCodec()===null)break outer;let a=await i.getDecoderConfig().then(e=>e?.codec??null);B(a!==null),c.push(a)}}if(u!==null&&!f){if(!o.includes(u))throw Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let e=i.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===u&&n.toLowerCase()===`audio`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let r=pf(n,t),i=(await this.getSegmentedInputForPath(r).getTrackBackings()).find(e=>e.getType()===`audio`);if(!i||await i.getCodec()===null)break outer;let a=await i.getDecoderConfig().then(e=>e?.codec??null);B(a!==null),c.push(a)}}c=[...new Set(c)];let p=null,m=null,h=e.attributes.getAsNumber(`bandwidth`);B(h!==null);let g=e.attributes.getAsNumber(`average-bandwidth`),_=e.attributes.get(`name`);for(let n of c){let s=Vf(n);if(s!==null){if(Df.includes(s)){if(p!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);p=n;let o=e.attributes.get(`video`);if(o===null){let n=e.attributes.get(`resolution`),i=null,a=null;if(n){let e=n.match(/^(\d+)x(\d+)$/);e&&(i=Number(e[1]),a=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:h,averageBitrate:g,name:_,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:i,height:a}})}else{if(!a.includes(o))throw Error(`Invalid M3U8 file; variant stream references video group "${o}" which is not defined in any #EXT-X-MEDIA tags.`);for(let n of i){let i=n.attributes.get(`group-id`),a=n.attributes.get(`type`);if(i!==o||a.toLowerCase()!==`video`)continue;let s=n.attributes.get(`resolution`)??e.attributes.get(`resolution`),c=null,l=null;if(s){let e=s.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:e_(n.attributes),autoselect:e_(n.attributes)||t_(n.attributes),languageCode:n_(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}}else if(kf.includes(s)){if(m!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);m=n;let a=e.attributes.get(`audio`);if(a===null){let n=e.attributes.get(`channels`),i=n===null?null:Number(n.split(`/`)[0]);r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:h,averageBitrate:g,name:_,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:i!==null&&Number.isInteger(i)&&i>0?i:null}})}else{if(!o.includes(a))throw Error(`Invalid M3U8 file; variant stream references audio group "${a}" which is not defined in any #EXT-X-MEDIA tags.`);for(let n of i){let i=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(i!==a||o.toLowerCase()!==`audio`)continue;let s=n.attributes.get(`channels`)??e.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);r.push({id:-1,demuxer:this,backingTrack:null,default:e_(n.attributes),autoselect:e_(n.attributes)||t_(n.attributes),languageCode:n_(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}}return r})),c=[],l=e=>{let t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),e.peakBitrate!==null&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),e.averageBitrate!==null&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===`und`&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(let e of s)for(let t of e)l(t);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of c)e.info.type===`video`?this.trackBackings.push(new Qg(e)):this.trackBackings.push(new $g(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),B(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new Yg(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return yg}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Zg=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,n=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(n.length===1)t=n[0];else if(this instanceof Qg){for(let e of n)if(await e.getCodec()===this.getCodec()){t=e;break}}else{B(this instanceof $g);for(let e of n)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...Cf,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){B(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},Qg=class extends Zg{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return Vf(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},$g=class extends Zg{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return Vf(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels===null?this.delegate(()=>this.backingAudioTrack.getNumberOfChannels()):this.internalTrack.info.numberOfChannels}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},e_=e=>{let t=e.get(`default`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},t_=e=>{let t=e.get(`autoselect`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},n_=e=>e===null?`und`:e.split(`-`)[0]||`und`,r_=class{constructor(){this._isIsobmff=!1}},i_=class extends r_{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let n=$(t,4);return n!==`ftyp`&&n!==`styp`?null:$(t,4)}_createDemuxer(e){return new Fm(e)}},a_=class extends i_{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let r=$(n,4);return r===`moof`||r===`sidx`}get name(){return`MP4`}get mimeType(){return`video/mp4`}},o_=class extends i_{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},s_=class extends r_{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=th(n);if(r===null||r<1||r>8||q(n,r)!==K.EBML)return!1;let i=ah(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=oh(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case K.EBMLVersion:if(q(a,r)!==1)return!1;break;case K.EBMLReadVersion:if(q(a,r)!==1)return!1;break;case K.DocType:if(sh(a,r)!==t)return!1;break;case K.DocTypeVersion:if(q(a,r)>4)return!1}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new bh(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},c_=class extends s_{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},l_=class extends r_{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Hv(n);if(!r)break;t=n.filePos+r.size}let n=await wh(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=Kf(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=Q(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await wh(e._reader,t,t+4);if(!s)return!1;let c=s.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Th(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},u_=class extends r_{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=$(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),$(t,4)===`WAVE`)}_createDemuxer(e){return new Bh(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},d_=class extends r_{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?$(t,4)===`OggS`:!1}_createDemuxer(e){return new Fh(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},f_=class extends r_{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Hv(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?$(n,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new $h(e)}},p_=class extends r_{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Hv(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Uh(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=Uh(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new Gh(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},m_=class extends r_{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=Y(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71||n[4]===71&&n[196]===71}_createDemuxer(e){return new ug(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},h_=class extends r_{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||$(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof zg))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Xg(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return yg}},g_=[new h_,new a_,new o_,new s_,new c_,new u_,new d_,new f_,new l_,new p_,new m_],__=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},v_=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},y_=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});df();var b_=-1/0,x_=-1/0,S_=null;typeof FinalizationRegistry<`u`&&(S_=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-b_>=1e3&&(W._error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`),b_=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-x_>=1e3&&(W._error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`),x_=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var C_=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},w_=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],T_=new Set(w_),E_=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Xd*this.timestamp)}get microsecondDuration(){return Math.trunc(Xd*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!T_.has(n.format))throw TypeError(`init.format must be one of: `+w_.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&_f(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0;let e=n.layout??L_(n.format,n.codedWidth,n.codedHeight),r=n.colorSpace??null;r===null&&(r=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth),this._data=n._doNotCopy?md(t):md(t).slice(),this._layout=e,this.colorSpace=new M_(r)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&_f(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6,this.colorSpace=new M_(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.visibleRect!==void 0&&_f(n.visibleRect,`init.visibleRect`),typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*Xd),duration:Math.trunc((n.duration??0)*Xd)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=n.visibleRect??{left:0,top:0,width:r,height:i},o=new OffscreenCanvas(a.width,a.height),s=o.getContext(`2d`,{alpha:tf(),willReadFrequently:!0});if(!s)throw Error(`OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.`);s.drawImage(t,-a.left,-a.top),this._data=o,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new M_({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof C_){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!w_.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=t.getColorSpace()}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=gf({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),S_?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return B(this._data!==null),this._data instanceof C_?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):N_(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(B(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||=(S_?.unregister(this),this._data instanceof C_?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):N_(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(I_(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return N_(this._data)?this._data.allocationSize(e):z_(this,e).allocationSize}async copyTo(t,n={}){if(!Cd(t))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(I_(n),this._closed)throw Error(`VideoSample is closed.`);if((n.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(B(this._data!==null),N_(this._data))return this._data.copyTo(t,n);if(n.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(n.format)){if(this._data instanceof C_){let r={stack:[],error:void 0,hasError:!1};try{let i=v_(r,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},n.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(t,n)}catch(e){r.error=e,r.hasError=!0}finally{y_(r)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame(),r=await e.copyTo(t,n);return e.close(),r}}let r=z_(this,n);B(this.format);let i=md(t);if(i.byteLength<r.allocationSize)throw TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);let a=R_(this.format),o;if(this._data instanceof C_){let e=this._data.getDataPlanes();if(e instanceof Promise&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);o=e}else if(this._data instanceof Uint8Array)B(this._layout),B(this._layout.length===a.length),o=this._layout.map((e,t)=>{let n=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);B(e),o=[{data:md(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}let s=[],c=a.length;for(let e=0;e<c;e++){let t=r.computedLayouts[e],n=o[e].stride,a=o[e].data,c=t.sourceTop*n;c+=t.sourceLeftBytes;let l=t.destinationOffset,u=t.sourceWidthBytes,d={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(c+u>a.byteLength)throw Error(`Source buffer OOB read.`);if(l+u>i.byteLength)throw Error(`Destination buffer OOB write.`);let e=a.subarray(c,c+u);i.set(e,l),c+=n,l+=t.destinationStride}s.push(d)}if(n.format!==void 0){let e=this.format.startsWith(`RGB`)!==n.format.startsWith(`RGB`),t=this.format.includes(`X`)&&n.format.includes(`A`);if(e||t)for(let n=0;n<r.allocationSize;n+=4){if(e){let e=i[n],t=i[n+2];i[n]=t,i[n+2]=e}t&&(i[n+3]=255)}}return s}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(B(this._data!==null),this._data instanceof C_){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(e instanceof Promise)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return N_(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(B(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&F_(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&=P_(s,a,o);let c,l,u,d,{sx:f,sy:p,sWidth:m,sHeight:h}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)c=0,l=0,u=n,d=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],s=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);u=e*s,d=i*s,c=(n-u)/2,l=(r-d)/2}e.save();let g=i%180==0?1:u/d;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/g,g),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),f,p,m,h,c,l,u,d),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}_drawWithFitAndMipmapping(e,t,n){let r=e.width,i=e.height,[a,o]=n.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=n.crop?n.crop.width:a,c=n.crop?n.crop.height:o,l=0;2*r<s&&2*i<c&&(l=Math.floor(Math.log2(Math.min(s/r,c/i))));let u=r*2**l,d=i*2**l,{canvas:f,context:p,isNew:m}=l>0?j_(u,d):{canvas:e,context:t,isNew:n.targetIsFresh};p.imageSmoothingQuality=`high`,n.fillBlack?(p.fillStyle=`black`,p.fillRect(0,0,u,d)):m||p.clearRect(0,0,u,d),this.drawWithFit(p,{fit:n.fit,rotation:n.rotation,crop:n.crop}),p.globalCompositeOperation=`copy`;for(let e=l;e>1;e--){let t=r*2**e,n=i*2**e;p.drawImage(f,0,0,t,n,0,0,t/2,n/2)}p.globalCompositeOperation=`source-over`,l>0&&(t.imageSmoothingQuality=`high`,t.globalCompositeOperation=`copy`,t.drawImage(f,0,0,2*r,2*i,0,0,r,i),t.globalCompositeOperation=`source-over`)}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(B(this._data!==null),this._data instanceof C_||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&F_(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let n=dd(this.rotation+(t.rotate??0)),[r,i]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],a=t.crop;a&&=P_(a,r,i);let o=a?a.width:r,s=a?a.height:i,c=o/s,l,u;t.width!==void 0&&t.height===void 0?(l=t.width,u=l/c):t.width===void 0&&t.height!==void 0?(u=t.height,l=u*c):t.width!==void 0&&t.height!==void 0?(l=t.width,u=t.height):(l=o,u=s),l=Ud(l,t.roundDimensionsTo??1),u=Ud(u,t.roundDimensionsTo??1);let d={width:l,height:u,fit:t.fit??`fill`,rotation:n,crop:a??{left:0,top:0,width:r,height:i},alpha:t.alpha??`keep`};for(let e of D_){let t=e(this,d);if(t instanceof Promise&&(t=await t),t!==null)return t}let{canvas:f,context:p,isNew:m}=j_(d.width,d.height);return this._drawWithFitAndMipmapping(f,p,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:d.alpha===`discard`}),new e(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}setEncodeOptions(e){if(!e||typeof e!=`object`)throw TypeError(`newEncodeOptions must be an object.`);this.encodeOptions=e}[Symbol.dispose](){this.close()}},D_=[],O_=3,k_=[],A_=0,j_=(e,t)=>{for(let n of k_)if(n.canvas.width===e&&n.canvas.height===t)return n.age=A_++,{canvas:n.canvas,context:n.context,isNew:!1};let n;if(typeof OffscreenCanvas<`u`)n=new OffscreenCanvas(e,t);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);n=document.createElement(`canvas`),n.width=e,n.height=t}let r=n.getContext(`2d`,{alpha:!0,willReadFrequently:!1});if(!r)throw Error(`The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.`);return k_.length>=O_&&k_.splice(hf(k_,e=>e.age),1),k_.push({canvas:n,context:r,age:A_++}),{canvas:n,context:r,isNew:!0}},M_=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(_d);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(yd);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(xd);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},N_=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,P_=(e,t,n)=>{let r=Math.min(e.left,t),i=Math.min(e.top,n),a=Math.min(e.width,t-r),o=Math.min(e.height,n-i);return B(a>=0),B(o>=0),{left:r,top:i,width:a,height:o}},F_=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},I_=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},L_=(e,t,n)=>{let r=R_(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},R_=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ld(e),B(!1)}},z_=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=B_(n,r,e.codedWidth,e.codedHeight,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return H_(i,o,a)},B_=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(t.width===0||t.height===0)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!V_(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},V_=(e,t)=>{if(e===null)return!0;let n=R_(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},H_=(e,t,n)=>{let r=R_(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},U_=[],W_=[],G_=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},K_=e=>{if(!ff(e))throw TypeError(`timestamp must be a number.`)},q_=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,J_=class{constructor(e){if(!(e instanceof av))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(G_(e),this._track.input._disposed)throw new yv;return q_(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){G_(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(K_(e),G_(t),this._track.input._disposed)throw new yv;return q_(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof mm))throw TypeError(`packet must be an EncodedPacket.`);if(G_(t),this._track.input._disposed)throw new yv;return q_(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(K_(e),G_(t),this._track.input._disposed)throw new yv;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(B(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof mm))throw TypeError(`packet must be an EncodedPacket.`);if(G_(t),this._track.input._disposed)throw new yv;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(B(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof mm))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof mm))throw TypeError(`endPacket must be an EncodedPacket.`);if(G_(n),this._track.input._disposed)throw new yv;let r=[],{promise:i,resolve:a}=jd(),{promise:o,resolve:s}=jd(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=jd()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=jd(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new yv;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Y_=class{constructor(e,t){this.onSample=e,this.onError=t}},X_=class{mediaSamplesInRange(e=-1/0,t=1/0,n){K_(e),K_(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=jd(),{promise:c,resolve:l}=jd(),u=!1,d=!1,f=!1,p=null,m=null,h=!1,g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(n=>{if(l(),n.timestamp>=t&&(d=!0),d){n.close();return}a&&(n.timestamp>e?(r.push(a),i=!0):a.close()),n.timestamp>=e&&(r.push(n),i=!0),a=i?null:n,r.length>0&&(s(),{promise:o,resolve:s}=jd())},e=>{h||(m=e,h=!0,s())});let n=this._createPacketSink(),_=await n.getKeyPacket(e,g)??await n.getFirstKeyPacket(g),v=_,y=n.packets(_??void 0,void 0,g);for(await y.next();v&&!d&&!this._track.input._disposed;){let e=Z_(r.length);if(r.length+p.getDecodeQueueSize()>e){({promise:c,resolve:l}=jd()),await c;continue}p.decode(v);let t=await y.next();if(t.done)break;v=t.value}await y.return(),!f&&!this._track.input._disposed&&await p.flush(),!i&&a&&r.push(a),u=!0,s()})().catch(e=>{h||(m=e,h=!0,s())}).finally(()=>{p?.close()});let _=this._track,v=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(_.input._disposed)throw v(),new yv;else if(f)return{value:void 0,done:!0};else if(h)throw v(),m;else if(r.length>0){let e=r.shift();return l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return f=!0,d=!0,l(),s(),v(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Id(e);let n=Fd(e),r=[],i=[],{promise:a,resolve:o}=jd(),{promise:s,resolve:c}=jd(),l=!1,u=!1,d=null,f=null,p=!1,m=e=>{i.push(e),o(),{promise:a,resolve:o}=jd()},h={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{d=await this._createDecoder(e=>{if(c(),u){e.close();return}let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let n=0;n<t;n++)m(n<t-1?e.clone():e);else e.close()},e=>{p||(f=e,p=!0,o())});let e=this._createPacketSink(),t=null,a=null,g=-1,_=async()=>{B(a),B(d);let t=a;for(d.decode(t);t.sequenceNumber<g;){let n=Z_(i.length);for(;i.length+d.getDecodeQueueSize()>n&&!u;)({promise:s,resolve:c}=jd()),await s;if(u)break;let r=await e.getNextPacket(t,h);B(r),d.decode(r),t=r}g=-1},v=async()=>{B(d),await d.flush();for(let e=0;e<r.length;e++)m(null);r.length=0};for await(let i of n){if(K_(i),u||this._track.input._disposed)break;let n=await e.getPacket(i,h),o=n&&await e.getKeyPacket(i,h);if(!o){g!==-1&&(await _(),await v()),m(null),t=null;continue}t&&(o.sequenceNumber!==a.sequenceNumber||n.timestamp<t.timestamp)&&(await _(),await v()),r.push(n.timestamp),g=Math.max(n.sequenceNumber,g),t=n,a=o}!u&&!this._track.input._disposed&&(g!==-1&&await _(),await v()),l=!0,o()})().catch(e=>{p||(f=e,p=!0,o())}).finally(()=>{d?.close()});let g=this._track,_=()=>{for(let e of i)e?.close()};return{async next(){for(;;)if(g.input._disposed)throw _(),new yv;else if(u)return{value:void 0,done:!0};else if(p)throw _(),f;else if(i.length>0){let e=i.shift();return B(e!==void 0),c(),{value:e,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}},async return(){return u=!0,c(),o(),_(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Z_=e=>e===0?40:8,Q_=class extends Y_{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Zd,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let o=U_.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof E_))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();B(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(n===`avc`&&this.decoderConfig.description&&rf()){let e=dp(md(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=pp(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let t=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(B(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(B(this.decoder),$d()||Ad(this.inputTimestamps,e.timestamp,e=>e),rf()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[],n=!1;for(let r of rp(e.data,this.decoderConfig)){let i=ip(e.data[r.offset]);if(n||=i>=1&&i<=5,i===$f.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}e=new mm(lp(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=Op(e.data,this.decoderConfig);t&&(e=new mm(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||=new ev,!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let t=this.colorQueue.shift();B(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();B(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=Ip(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of gp(e,this.decoderConfig)){let n=_p(e[t.offset]);if(n===ep.RASL_N||n===ep.RASL_R)return!0}return!1}sampleHandler(e){if($d()){if(this.sampleQueue.length>0&&e.timestamp>=fd(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Ad(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();B(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){let n=jd();this.mergeAlphaPromises.push(n.promise);let r={sample:null};this.finalSamples.push(r);try{for(t?(B(this.merger),r.sample=new E_(await this.merger.merge(e,t))):r.sample=new E_(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){Md(this.finalSamples,r),this.onError(e)}finally{Md(this.mergeAlphaPromises,n.promise),n.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(B(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),$d()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(B(this.decoder),this.decoder.state!==`closed`&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!==`closed`&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},$_=null,ev=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!$_){let e=new Blob([`(${tv.toString()})()`],{type:`application/javascript`});$_=URL.createObjectURL(e)}let e=Vd(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker($_);e.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame))}),e.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let n=this.nextRequestId++,r=jd();this.pendingRequests.set(n,r);let i=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,i.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}},tv=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,n);if(n===`NV12`)return await o(e,t);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,r,i,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:n===`RGBX`||n===`RGBA`?`RGBA`:`BGRA`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=n.includes(`P10`),o=n.includes(`P12`),c=a||o?2:1,l,u;n.startsWith(`I420`)?(l=Math.ceil(r/2),u=Math.ceil(i/2)):n.startsWith(`I422`)?(l=Math.ceil(r/2),u=i):(l=r,u=i);let d=r*i,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,r,i,c),y=p+2*m;_.set(v,y);let b={format:n.slice(0,4)+`A`+n.slice(4),codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();(!t||t.byteLength!==c)&&(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();(!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}return e.subarray(0,n*r*i)}},nv=e=>{if(!e||typeof e!=`object`)throw TypeError(`decoderOptions must be an object.`);if(e.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!=`boolean`)throw TypeError(`decoderOptions.optimizeForLatency, when provided, must be a boolean.`)},rv=class extends X_{constructor(e,t={}){if(!(e instanceof sv))throw TypeError(`videoTrack must be an InputVideoTrack.`);nv(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof VideoDecoder>`u`?sf(`VideoDecoder`):`This video track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let n=await this._track.getCodec(),r=await this._track.getRotation(),i=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return B(n&&i),i={...i,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Q_(e,t,n,i,r,a)}_createPacketSink(){return new J_(this._track)}async getSample(e,t={}){K_(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},iv=class{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof sv))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&F_(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);t.decoderOptions!==void 0&&nv(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new rv(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),i=await t.getSquarePixelHeight(),[a,o]=n%180==0?[r,i]:[i,r],s=e.crop;s&&=P_(s,a,o);let[c,l]=s?[s.width,s.height]:[a,o],u=c/l;e.width!==void 0&&e.height===void 0?(c=e.width,l=Math.round(c/u)):e.width===void 0&&e.height!==void 0?(l=e.height,c=Math.round(l*u)):e.width!==void 0&&e.height!==void 0&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=n,this._crop=s})()}_videoSampleToWrappedCanvas(e){let t=this._width,n=this._height,r=this._canvasPool[this._nextCanvasIndex],i=!1;r||(typeof document<`u`?(r=document.createElement(`canvas`),r.width=t,r.height=n):r=new OffscreenCanvas(t,n),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let a=r.getContext(`2d`,{alpha:this._alpha||tf()});B(a),e._drawWithFitAndMipmapping(r,a,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:i,fillBlack:!this._alpha&&tf()});let o={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){K_(e),await this._ensureInit();let n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*Bd(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Bd(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},av=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof sv}isAudioTrack(){return this instanceof cv}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return J(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return J(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return J(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return J(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return J(this._backing.getDisposition(),`disposition`,`getDisposition`)}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return Wd((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new J_(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(fv({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(fv({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(fv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(fv({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(fv({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=ov(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=ov(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=ov(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},J=(e,t,n)=>{if(e instanceof Promise)throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},ov=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return r instanceof Promise?r.then(n):n(r)}:void 0},sv=class extends av{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return J(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return J(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return J(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getRotation(){return this._backing.getRotation()}get rotation(){return J(this._backing.getRotation(),`rotation`,`getRotation`)}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return J(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return J(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=gf({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=gf({num:J(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*J(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:J(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*J(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=J(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return J(J(this._backing.getRotation(),`displayWidth`,`getDisplayWidth`)%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=J(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return J(J(this._backing.getRotation(),`displayHeight`,`getDisplayHeight`)%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pq`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return B(t!==null),U_.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return W._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof mm))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let n=await this.getDecoderConfig();return B(n),Ip(t,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!Number.isFinite(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new J_(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=mv(l,t),d=u??t,f=u===null?null:t/u,p=new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let w=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?gv(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},cv=class extends av{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return J(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return J(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return J(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return B(t!==null),W_.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return W._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof mm))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},lv=e=>-(e??-1/0),uv=e=>-e,dv=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return r instanceof Promise?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return r instanceof Promise?r.then(n):n(r)}:void 0}},fv=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||i instanceof Promise?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),pv=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>e instanceof Promise)?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)},mv=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=hv(p,m,n),r=hv(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},hv=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return gf({num:n,den:r})}return null},gv=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};df();var _v=class e extends yf{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof r_)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Lg||t.source instanceof Rg))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Lg&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&__(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Lg?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){B(this._rootSource instanceof zg);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let n=this._sourceCache.find(n=>n.cacheGroup===t&&Bg(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Bg(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if(mf(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=hf(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);B(e!==-1);let n=this._sourceCache[e];this._sourceCache.splice(e,1),n.sourceRef.free(),Md(this._sourceRefs,n.sourceRef)}this._sourceRefs.push(n);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return B(r!==-1),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:n,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:i}),i.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new bv(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new vv})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),B(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof vv)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=dv(e),pv((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=dv(e),pv((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=dv(e),pv((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=dv(e);let t=fv(e,{sortBy:async e=>[uv((await e.getDisposition()).default),uv(await e.hasPairableAudioTrack()),uv(!await e.hasOnlyKeyPackets()),lv(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=dv(e);let t=await this.getPrimaryVideoTrack(),n=fv(e,{sortBy:async e=>[uv(!t||e.canBePairedWith(t)),uv((await e.getDisposition()).default),lv(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new sv(this,e):new cv(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},vv=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},yv=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},bv=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw Error(`Reading file size too early; read required first.`);return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new yv;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=new Uint8Array;return new xv(t,H(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Ig);return r instanceof Promise?r.then(t=>t?new xv(t.bytes,t.view,t.offset,e,n):null):r?new xv(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new yv;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Vd(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(B(this.fileSizeNonStrict!==null),this.requestSlice(e,Vd(this.fileSizeNonStrict-e,t,n)));return r instanceof Promise?r.then(i):i(r)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(n instanceof Promise&&(n=await n),!n||n.length===0)break;let r=Y(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new xv(n,H(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},xv=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,H(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},Sv=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Y=(e,t)=>{Sv(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},X=e=>(Sv(e,1),e.view.getUint8(e.bufferPos++)),Cv=(e,t)=>{Sv(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},Z=e=>{Sv(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},wv=e=>{Sv(e,3);let t=Rd(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Tv=e=>{Sv(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Ev=(e,t)=>{Sv(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Q=e=>{Sv(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Dv=e=>{Sv(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Ov=e=>{Sv(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},kv=e=>{Sv(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},Av=(e,t)=>{let n,r;return t?(n=Ev(e,!0),r=Ev(e,!0)):(r=Ev(e,!1),n=Ev(e,!1)),r*4294967296+n},jv=e=>{let t=Q(e),n=Q(e);return t*4294967296+n},Mv=e=>{let t=Ov(e),n=Q(e);return t*4294967296+n},Nv=e=>{let t=Dv(e);return kv(e)*4294967296+t},Pv=e=>{Sv(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Fv=e=>{Sv(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},$=(e,t)=>{Sv(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Iv=(e,t,n)=>hd.decode(Y(e,t)).split(`
|
|
65
|
-
`).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e)),Lv;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Lv||={});var Rv;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(Rv||={});var zv=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),Bv=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=Y(e,125),e.filePos=n;let r=Vv(e,30);r&&(t.title??=r);let i=Vv(e,30);i&&(t.artist??=i);let a=Vv(e,30);a&&(t.album??=a);let o=Vv(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=Y(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Vv(e,28),e.skip(2)}else e.skip(-30),l=Vv(e,30);l&&(t.comment??=l);let u=X(e);u<zv.length&&(t.genre??=zv[u])},Vv=(e,t)=>{let n=Y(e,t),r=cf(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},Hv=e=>{let t=e.filePos,n=$(e,3),r=X(e),i=X(e),a=X(e),o=Q(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=Jf(o);return a&Lv.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},Uv=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){W._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new Wv(t,Y(e,t.flags&Lv.Footer?t.size-10:t.size));if(t.flags&Lv.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&Lv.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&Lv.Unsynchronisation)),o){W._warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){W._warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}if(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=r.readId3V2TextEncoding(),i=r.readId3V2Text(t,a),o=r.readId3V2Text(t,a);e[i]??=o}else e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size);switch(r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(zv[e]!==void 0){n.genre??=zv[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(zv[e]!==void 0){n.genre??=zv[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size}r.pos=a}},Wv=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?Jf(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:Jf(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case Rv.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case Rv.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=cf(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=cf(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{let e=cf(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),hd.decode(r.subarray(0,e))}case Rv.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=cf(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case Rv.UTF_8:{let e=cf(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),hd.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Gv=.5;function Kv(e,t){return e===null||t<e.servedSeconds||t-e.servedSeconds>Gv}async function qv(e){try{let t=await new _v({formats:g_,source:new Hg(e)}).getPrimaryVideoTrack();return t?await t.canDecode()?{sink:new iv(t)}:{reason:`cannot decode ${t.codec??`an unknown codec`}`}:{reason:`no video track in the encoded span`}}catch(e){return{reason:e instanceof Error?e.message:String(e)}}}async function Jv(e,t,n={}){let r=new Map,i=[],a=(e,t)=>{i.push({ref:e,reason:t}),n.onSpanUnavailable?.(e,t)};for(let n of e.motionSpans){let e=await t(n.ref);if(!(e instanceof Uint8Array)){a(n.ref,`loaded as an image, not encoded bytes`);continue}let i=await qv(e);if(`reason`in i){a(n.ref,i.reason);continue}r.set(n.ref,i.sink)}let o=new Map,s=e=>{let n=o.get(e);if(n)return n;let r=t(e).then(t=>{if(t instanceof Uint8Array)throw Error(`keyframe "${e}" must load as an image, not encoded bytes`);return t});return o.set(e,r),r},c=null,l=async e=>{try{await e.iterator.return()}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`[demoman] compositor: a decode walk on span "${e.ref}" would not close (${n}); its decoder is still held`)}},u=async(e,t)=>{let n=r.get(e.ref);if(!n)return null;let i=(t-e.startMs)/1e3;if(Kv(c!==null&&c.ref===e.ref&&c.current!==null?{servedSeconds:c.current.timestamp}:null,i)){let t=c;c={ref:e.ref,iterator:n.canvases(i),current:null,pending:null,exhausted:!1},t&&l(t)}let a=c;for(;;){if(a.pending===null&&!a.exhausted){let e=await a.iterator.next();e.done?a.exhausted=!0:a.pending=e.value}if(a.pending===null||a.current!==null&&a.pending.timestamp>i)break;a.current=a.pending,a.pending=null}let o=a.current;return o?{image:o.canvas,width:o.canvas.width,height:o.canvas.height,sourceTimeMs:e.startMs+o.timestamp*1e3}:null},d=(t,n)=>e.motionSpans.reduce((r,i)=>i.endMs>t||i.endMs<=n||!Io(i,e.viewport)?r:r===null||i.endMs>r.endMs?i:r,null);return{async at(t){let n=Ro(e,t);if(n){let e=await u(n,t);if(e)return e}let r=cd(e,t),i=d(t,r.sourceTimeMs);if(i){let e=await u(i,i.endMs);if(e)return e}return{...await s(r.ref),sourceTimeMs:r.sourceTimeMs}},warm(t,n){for(let r of ld(e,t,n))s(r.ref).catch(()=>void 0)},describe:()=>({keyframes:e.keyframes,motionSpans:e.motionSpans}),unavailable:()=>[...i]}}var Yv=c(o((e=>{var t=Object.defineProperty;(e=>t(e,`__esModule`,{value:!0}))(e),((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})(e,{GIFEncoder:()=>D,applyPalette:()=>S,default:()=>de,nearestColor:()=>ne,nearestColorIndex:()=>te,nearestColorIndexWithDistance:()=>E,prequantize:()=>x,quantize:()=>_,snapColorsToPalette:()=>T});var n={signature:`GIF`,version:`89a`,trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(e=256){let t=0,n=new Uint8Array(e);return{get buffer(){return n.buffer},reset(){t=0},bytesView(){return n.subarray(0,t)},bytes(){return n.slice(0,t)},writeByte(e){r(t+1),n[t]=e,t++},writeBytes(e,i=0,a=e.length){r(t+a);for(let r=0;r<a;r++)n[t++]=e[r+i]},writeBytesView(e,i=0,a=e.byteLength){r(t+a),n.set(e.subarray(i,i+a),t),t+=a}};function r(e){var r=n.length;if(r>=e)return;e=Math.max(e,r*(r<1048576?2:1.125)>>>0),r!=0&&(e=Math.max(e,256));let i=n;n=new Uint8Array(e),t>0&&n.set(i.subarray(0,t),0)}}var i=12,a=5003,o=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function s(e,t,n,s,c=r(512),l=new Uint8Array(256),u=new Int32Array(a),d=new Int32Array(a)){let f=u.length,p=Math.max(2,s);l.fill(0),d.fill(0),u.fill(-1);let m=0,h=0,g=p+1,_=g,v=!1,y=_,b=(1<<y)-1,x=1<<g-1,S=x+1,C=x+2,w=0,T=n[0],ee=0;for(let e=f;e<65536;e*=2)++ee;ee=8-ee,c.writeByte(p),E(x);let te=n.length;for(let e=1;e<te;e++)next_block:{let t=n[e],r=(t<<i)+T,a=t<<ee^T;if(u[a]===r){T=d[a];break next_block}let o=a===0?1:f-a;for(;u[a]>=0;)if(a-=o,a<0&&(a+=f),u[a]===r){T=d[a];break next_block}E(T),T=t,C<1<<i?(d[a]=C++,u[a]=r):(u.fill(-1),C=x+2,v=!0,E(x))}return E(T),E(S),c.writeByte(0),c.bytesView();function E(e){for(m&=o[h],h>0?m|=e<<h:m=e,h+=y;h>=8;)l[w++]=m&255,w>=254&&(c.writeByte(w),c.writeBytesView(l,0,w),w=0),m>>=8,h-=8;if((C>b||v)&&(v?(y=_,b=(1<<y)-1,v=!1):(++y,b=y===i?1<<y:(1<<y)-1)),e==S){for(;h>0;)l[w++]=m&255,w>=254&&(c.writeByte(w),c.writeBytesView(l,0,w),w=0),m>>=8,h-=8;w>0&&(c.writeByte(w),c.writeBytesView(l,0,w),w=0)}}}var c=s;function l(e,t,n){return e<<8&63488|t<<2&992|n>>3}function u(e,t,n,r){return e>>4|t&240|(n&240)<<4|(r&240)<<8}function d(e,t,n){return e>>4<<8|t&240|n>>4}function f(e,t,n){return e<t?t:e>n?n:e}function p(e){return e*e}function m(e,t,n){var r=0,i=1e100;let a=e[t],o=a.cnt,s=a.ac,c=a.rc,l=a.gc,u=a.bc;for(var d=a.fw;d!=0;d=e[d].fw){let t=e[d],a=t.cnt,m=o*a/(o+a);if(!(m>=i)){var f=0;n&&(f+=m*p(t.ac-s),f>=i)||(f+=m*p(t.rc-c),!(f>=i)&&(f+=m*p(t.gc-l),!(f>=i)&&(f+=m*p(t.bc-u),!(f>=i)&&(i=f,r=d))))}}a.err=i,a.nn=r}function h(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function g(e,t){let n=Array(t===`rgb444`?4096:65536),r=e.length;if(t===`rgba4444`)for(let t=0;t<r;++t){let r=e[t],i=r>>24&255,a=r>>16&255,o=r>>8&255,s=r&255,c=u(s,o,a,i),l=c in n?n[c]:n[c]=h();l.rc+=s,l.gc+=o,l.bc+=a,l.ac+=i,l.cnt++}else if(t===`rgb444`)for(let t=0;t<r;++t){let r=e[t],i=r>>16&255,a=r>>8&255,o=r&255,s=d(o,a,i),c=s in n?n[s]:n[s]=h();c.rc+=o,c.gc+=a,c.bc+=i,c.cnt++}else for(let t=0;t<r;++t){let r=e[t],i=r>>16&255,a=r>>8&255,o=r&255,s=l(o,a,i),c=s in n?n[s]:n[s]=h();c.rc+=o,c.gc+=a,c.bc+=i,c.cnt++}return n}function _(e,t,n={}){let{format:r=`rgb565`,clearAlpha:i=!0,clearAlphaColor:a=0,clearAlphaThreshold:o=0,oneBitAlpha:s=!1}=n;if(!e||!e.buffer||!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw Error(`quantize() expected RGBA Uint8Array data`);let c=new Uint32Array(e.buffer),l=n.useSqrt!==!1,u=r===`rgba4444`,d=g(c,r),h=d.length,_=h-1,y=new Uint32Array(h+1);for(var b=0,x=0;x<h;++x){let e=d[x];if(e!=null){var S=1/e.cnt;u&&(e.ac*=S),e.rc*=S,e.gc*=S,e.bc*=S,d[b++]=e}}p(t)/b<.022&&(l=!1);for(var x=0;x<b-1;++x)d[x].fw=x+1,d[x+1].bk=x,l&&(d[x].cnt=Math.sqrt(d[x].cnt));l&&(d[x].cnt=Math.sqrt(d[x].cnt));var C,w,T;for(x=0;x<b;++x){m(d,x,!1);var ee=d[x].err;for(w=++y[0];w>1&&(T=w>>1,!(d[C=y[T]].err<=ee));w=T)y[w]=C;y[w]=x}var te=b-t;for(x=0;x<te;){for(var E;;){var ne=y[1];if(E=d[ne],E.tm>=E.mtm&&d[E.nn].mtm<=E.tm)break;E.mtm==_?ne=y[1]=y[y[0]--]:(m(d,ne,!1),E.tm=x);var ee=d[ne].err;for(w=1;(T=w+w)<=y[0]&&(T<y[0]&&d[y[T]].err>d[y[T+1]].err&&T++,!(ee<=d[C=y[T]].err));w=T)y[w]=C;y[w]=ne}var D=d[E.nn],re=E.cnt,ie=D.cnt,S=1/(re+ie);u&&(E.ac=S*(re*E.ac+ie*D.ac)),E.rc=S*(re*E.rc+ie*D.rc),E.gc=S*(re*E.gc+ie*D.gc),E.bc=S*(re*E.bc+ie*D.bc),E.cnt+=D.cnt,E.mtm=++x,d[D.bk].fw=D.fw,d[D.fw].bk=D.bk,D.mtm=_}let ae=[];var oe=0;for(x=0;;++oe){let e=f(Math.round(d[x].rc),0,255),t=f(Math.round(d[x].gc),0,255),n=f(Math.round(d[x].bc),0,255),r=255;u&&(r=f(Math.round(d[x].ac),0,255),s&&(r=r<=(typeof s==`number`?s:127)?0:255),i&&r<=o&&(e=t=n=a,r=0));let c=u?[e,t,n,r]:[e,t,n];if(v(ae,c)||ae.push(c),(x=d[x].fw)==0)break}return ae}function v(e,t){for(let n=0;n<e.length;n++){let r=e[n],i=r[0]===t[0]&&r[1]===t[1]&&r[2]===t[2],a=r.length>=4&&t.length>=4?r[3]===t[3]:!0;if(i&&a)return!0}return!1}function y(e,t){var n=0,r;for(r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return n}function b(e,t){return t>1?Math.round(e/t)*t:e}function x(e,{roundRGB:t=5,roundAlpha:n=10,oneBitAlpha:r=null}={}){let i=new Uint32Array(e.buffer);for(let e=0;e<i.length;e++){let a=i[e],o=a>>24&255,s=a>>16&255,c=a>>8&255,l=a&255;o=b(o,n),r&&(o=o<=(typeof r==`number`?r:127)?0:255),l=b(l,t),c=b(c,t),s=b(s,t),i[e]=o<<24|s<<16|c<<8|l<<0}}function S(e,t,n=`rgb565`){if(!e||!e.buffer||!(e instanceof Uint8Array)&&!(e instanceof Uint8ClampedArray))throw Error(`quantize() expected RGBA Uint8Array data`);if(t.length>256)throw Error(`applyPalette() only works with 256 colors or less`);let r=new Uint32Array(e.buffer),i=r.length,a=n===`rgb444`?4096:65536,o=new Uint8Array(i),s=Array(a);if(n===`rgba4444`)for(let e=0;e<i;e++){let n=r[e],i=n>>24&255,a=n>>16&255,c=n>>8&255,l=n&255,d=u(l,c,a,i),f=d in s?s[d]:s[d]=C(l,c,a,i,t);o[e]=f}else{let e=n===`rgb444`?d:l;for(let n=0;n<i;n++){let i=r[n],a=i>>16&255,c=i>>8&255,l=i&255,u=e(l,c,a),d=u in s?s[u]:s[u]=w(l,c,a,t);o[n]=d}}return o}function C(e,t,n,r,i){let a=0,o=1e100;for(let s=0;s<i.length;s++){let c=i[s],l=c[3],u=ee(l-r);if(u>o)continue;let d=c[0];if(u+=ee(d-e),u>o)continue;let f=c[1];if(u+=ee(f-t),u>o)continue;let p=c[2];u+=ee(p-n),!(u>o)&&(o=u,a=s)}return a}function w(e,t,n,r){let i=0,a=1e100;for(let o=0;o<r.length;o++){let s=r[o],c=s[0],l=ee(c-e);if(l>a)continue;let u=s[1];if(l+=ee(u-t),l>a)continue;let d=s[2];l+=ee(d-n),!(l>a)&&(a=l,i=o)}return i}function T(e,t,n=5){if(!e.length||!t.length)return;let r=e.map(e=>e.slice(0,3)),i=n*n,a=e[0].length;for(let n=0;n<t.length;n++){let o=t[n];o=o.length<a?[o[0],o[1],o[2],255]:o.length>a?o.slice(0,3):o.slice();let s=E(r,o.slice(0,3),y),c=s[0],l=s[1];l>0&&l<=i&&(e[c]=o)}}function ee(e){return e*e}function te(e,t,n=y){let r=1/0,i=-1;for(let a=0;a<e.length;a++){let o=e[a],s=n(t,o);s<r&&(r=s,i=a)}return i}function E(e,t,n=y){let r=1/0,i=-1;for(let a=0;a<e.length;a++){let o=e[a],s=n(t,o);s<r&&(r=s,i=a)}return[i,r]}function ne(e,t,n=y){return e[te(e,t,n)]}function D(e={}){let{initialCapacity:t=4096,auto:i=!0}=e,a=r(t),o=5003,s=new Uint8Array(256),c=new Int32Array(o),l=new Int32Array(o),u=!1;return{reset(){a.reset(),u=!1},finish(){a.writeByte(n.trailer)},bytes(){return a.bytes()},bytesView(){return a.bytesView()},get buffer(){return a.buffer},get stream(){return a},writeHeader:d,writeFrame(e,t,n,r={}){let{transparent:o=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:h=0,colorDepth:g=8,dispose:_=-1}=r,v=!1;if(i?u||=(v=!0,d(),!0):v=!!r.first,t=Math.max(0,Math.floor(t)),n=Math.max(0,Math.floor(n)),v){if(!m)throw Error(`First frame must include a { palette } option`);ie(a,t,n,m,g),oe(a,m),h>=0&&ae(a,h)}let y=Math.round(p/10);re(a,_,y,o,f);let b=!!m&&!v;O(a,t,n,b?m:null),b&&oe(a,m),se(a,e,t,n,g,s,c,l)}};function d(){le(a,`GIF89a`)}}function re(e,t,n,r,i){e.writeByte(33),e.writeByte(249),e.writeByte(4),i<0&&(i=0,r=!1);var a,o;r?(a=1,o=2):(a=0,o=0),t>=0&&(o=t&7),o<<=2,e.writeByte(o|0|a),ce(e,n),e.writeByte(i||0),e.writeByte(0)}function ie(e,t,n,r,i=8){let a=ue(r.length)-1,o=i-1<<4|128|a;ce(e,t),ce(e,n),e.writeBytes([o,0,0])}function ae(e,t){e.writeByte(33),e.writeByte(255),e.writeByte(11),le(e,`NETSCAPE2.0`),e.writeByte(3),e.writeByte(1),ce(e,t),e.writeByte(0)}function oe(e,t){let n=1<<ue(t.length);for(let r=0;r<n;r++){let n=[0,0,0];r<t.length&&(n=t[r]),e.writeByte(n[0]),e.writeByte(n[1]),e.writeByte(n[2])}}function O(e,t,n,r){if(e.writeByte(44),ce(e,0),ce(e,0),ce(e,t),ce(e,n),r){let t=ue(r.length)-1;e.writeByte(128|t)}else e.writeByte(0)}function se(e,t,n,r,i=8,a,o,s){c(n,r,t,i,e,a,o,s)}function ce(e,t){e.writeByte(t&255),e.writeByte(t>>8&255)}function le(e,t){for(var n=0;n<t.length;n++)e.writeByte(t.charCodeAt(n))}function ue(e){return Math.max(Math.ceil(Math.log2(e)),1)}var de=D}))(),1),{applyPalette:Xv,GIFEncoder:Zv,quantize:Qv}=typeof Yv.GIFEncoder==`function`?Yv:Yv.default??Yv,$v=.012,ey=1.5,ty=2,ny=24;function ry(e){let t=z(e.blur,0,1);if(!(t>0)||!(e.current.scale>0))return[];let{current:n,frameRect:r,canvas:i,outputTimeMs:a}=e,o={x:r.x+r.width/2,y:r.y+r.height/2},s=[{x:0,y:0},{x:i.width,y:0},{x:0,y:i.height},{x:i.width,y:i.height}],c=t=>{let a=Bl(e.camera,t,e.base,r,e.viewport,i),s=a.scale/n.scale;return{scale:s,x:(1-s)*o.x+a.scale*(n.focus.x-a.focus.x),y:(1-s)*o.y+a.scale*(n.focus.y-a.focus.y),outputTimeMs:t}},l=(e,t)=>{let n=0;for(let r of s)n=Math.max(n,Math.hypot(e.scale*r.x+e.x-(t.scale*r.x+t.x),e.scale*r.y+e.y-(t.scale*r.y+t.y)));return n},u={scale:1,x:0,y:0,outputTimeMs:a},d=Math.min(32*t,a);if(!(d>0))return[];let f=l(c(a-d),u),p=$v*Math.hypot(i.width,i.height);if(f>p){let e=0,t=d;for(let n=0;n<20;n++){let n=(e+t)/2;l(c(a-n),u)<=p?e=n:t=n}d=e,f=l(c(a-d),u)}if(f<.75)return[];let m=z(Math.ceil(f/ey),ty,ny),h=[];for(let e=0;e<3;e++){h=[];for(let e=1;e<=m;e++)h.push(c(a-d*e/m));let e=0,t=u;for(let n of h)e=Math.max(e,l(n,t)),t=n;if(e<=1.5||m>=ny)break;m=Math.min(ny,Math.ceil(m*e/ey))}return h}var iy=new WeakMap;function ay(e,t,n){let r=iy.get(n);(!r||r.width!==e||r.height!==t)&&(r=new OffscreenCanvas(e,t),iy.set(n,r));let i=r.getContext(`2d`);if(!i)throw Error(`the camera blur's scratch canvas has no 2D context`);return{scratch:r,ctx:i}}function oy(e,t){if(t.length===0)return;let{width:n,height:r}=e.canvas,{scratch:i,ctx:a}=ay(n,r,e.canvas);a.globalCompositeOperation=`copy`,a.drawImage(e.canvas,0,0),e.save(),e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`medium`,t.forEach((t,n)=>{e.setTransform(t.scale,0,0,t.scale,t.x,t.y),e.globalAlpha=1/(n+2),e.drawImage(i,0,0)}),e.restore()}var sy=`#4b5563`;function cy(e,t){e.save(),e.fillStyle=sy,e.fillRect(t.x,t.y,t.width,t.height),e.restore()}function ly(e,t,n){for(let r of t)cy(e,n(r.rect))}var uy={format:`mp4`,width:3840,height:2160,fps:60,bitrate:4e7,cornerRadius:36,fit:`contain`},dy={format:`mp4`,width:2560,height:1440,fps:60,bitrate:18e6,cornerRadius:24,fit:`contain`},fy={format:`mp4`,width:1920,height:1080,fps:60,bitrate:1e7,cornerRadius:18,fit:`contain`},py={format:`mp4`,width:1080,height:1920,fps:60,bitrate:12e6,cornerRadius:24,fit:`cover`},my={format:`mp4`,width:2560,height:1440,fps:30,bitrate:9e6,cornerRadius:24,fit:`contain`,encoder:{quality:.5}},hy={format:`mp4`,width:720,height:1280,fps:30,bitrate:267e4,cornerRadius:16,fit:`cover`,encoder:{quality:.5}},gy={...dy,bitrate:8e6},_y=1e7,vy={...py,bitrate:gy.bitrate},yy={format:`gif`,width:800,height:450,fps:15,bitrate:0,cornerRadius:10,fit:`contain`},by={format:`png`,width:2560,height:1440,fps:0,bitrate:0,cornerRadius:24,fit:`contain`},xy={format:`gif`,width:450,height:800,fps:15,bitrate:0,cornerRadius:10,fit:`cover`},Sy={format:`png`,width:1080,height:1920,fps:0,bitrate:0,cornerRadius:24,fit:`cover`};function Cy(e){let t=Math.max(...e.keyframes.map(e=>e.width),0);return t>=uy.width?uy:t>=dy.width?dy:fy}function wy(e){let t=Math.max(...e.keyframes.map(e=>Math.max(e.width,e.height)),0);return t>=uy.width?uy:t>=dy.width?dy:fy}function Ty(e,t){return t===`auto`?wy(e):Cy(e)}function Ey(e,t,n,r){return e===`auto`?ky(t,n,r):t}var Dy=36864,Oy=(e,t)=>Math.ceil(e/16)*Math.ceil(t/16);function ky(e,t,n){let r=t.width/t.height,i=1-2*n,a=e=>Math.max(2,2*Math.round(e/2)),o=e=>{if(r>=1){let t=e/(1+2*n/(r*i));return{width:e,height:a(t/r/i)}}let t=e/(1+2*n*r/i);return{width:a(t*r/i),height:e}},s=Math.max(e.width,e.height),{width:c,height:l}=o(s);if(e.format===`mp4`&&Oy(c,l)>Dy)for(s=2*Math.floor(s*Math.sqrt(Dy*256/(c*l))/2);{width:c,height:l}=o(s),!(Oy(c,l)<=Dy);)s-=2;return{...e,width:c,height:l,fit:`contain`,shapedToRecording:!0,bitrate:Math.round(e.bitrate*c*l/(e.width*e.height))}}function Ay(e){return e.map(e=>{let t=z(e.scale,1,Tl.verticalMaxScale);return t<e.scale?{...e,scale:t,requestedScale:e.requestedScale??e.scale}:{...e,scale:t}})}function jy(e,t){return e.fit===`cover`?Ay(t):t}var My=uy.width*Tl.maxScale,Ny=My*3/4;function Py(e,t){let n=Math.max(t.width/e.width,t.height/e.height),r=Math.min(e.width,t.width/n),i=Math.min(e.height,t.height/n);return{sx:(e.width-r)/2,sy:(e.height-i)/2,sw:r,sh:i}}function Fy(e){return e.height>e.width?`portrait`:`landscape`}function Iy(e){return Fy(e)===`portrait`?{width:Ny,height:My}:{width:My,height:Ny}}function Ly(e,t=Iy(e)){let n=Math.max(e.width/t.width,e.height/t.height),r=Math.min(1,n*Tl.maxScale);return{width:Math.ceil(t.width*r),height:Math.ceil(t.height*r)}}function Ry(e,t,n,r){let i=Math.min(n.width,n.height),a=i*.02,o=e.corner.startsWith(`top`),s=e.corner.endsWith(`left`),c=(o?r.y:n.height-(r.y+r.height))-a,l=(s?r.x:n.width-(r.x+r.width))-a,u=Math.min(c,(n.width-2*a)/t),d=Math.max(u,l/t,0),f=e.size*i,p=d>=f-i*1e-9,m=p?f:d,h=m/i<.019999999?0:m/i,g=h*i,_=g*t;return{rect:{x:s?a:n.width-a-_,y:o?a:n.height-a-g,width:_,height:g},effectiveSize:h,capped:h===0||!p}}function zy(e,t){return e.logo===null?0:Math.ceil(e.logo.size*Math.min(t.width,t.height))}function By(e,t,n,r=null,i=null){let a=Math.min(t.width,t.height)*e.padding,o={x:a,y:a,width:t.width-a*2,height:t.height-a*2},s=Math.min(o.width,o.height),c=Math.abs(o.width/o.height/(n.width/n.height)-1),l=t.shapedToRecording===!0&&s>0&&c<=1.5/s,u=t.fit===`cover`||l?o:Uo(n,o),d=e.logo,f=d!==null&&r!==null?Ry(d,r.width/r.height,t,u):null,p=f!==null&&e.padding===0?{rect:{...f.rect,width:0,height:0},effectiveSize:0,capped:!0}:f;return{background:e.background,cornerRadius:e.padding===0?0:t.cornerRadius,frameRect:u,padding:e.padding,logo:d!==null&&r!==null&&p!==null&&p.effectiveSize>0?{image:r,opacity:d.opacity,rect:p.rect}:null,logoPlacement:p,wallpaper:e.background.kind===`wallpaper`||e.background.kind===`image`?i:null}}function Vy(e,t){return Math.max(e.width/t.width,e.height/t.height)}function Hy(e,t,n,r){let i=Vy(n,r)*t.scale;return{x:t.center.x+(e.x-(n.x+n.width/2))/i,y:t.center.y+(e.y-(n.y+n.height/2))/i}}function Uy(e,t,n,r){let i=Hy({x:e.x,y:e.y},t,n,r),a=Vy(n,r)*t.scale;return{x:i.x,y:i.y,width:e.width/a,height:e.height/a}}function Wy(e,t,n){let r=e*Math.PI/180,i=Math.sin(r),a=-Math.cos(r),o=(Math.abs(t*i)+Math.abs(n*a))/2,s=t/2,c=n/2;return{x0:s-i*o,y0:c-a*o,x1:s+i*o,y1:c+a*o}}function Gy(e,t,n){let r=n.background;if(r.kind===`solid`)e.fillStyle=r.color;else{let n=r.kind===`gradient`?r:rc,{x0:i,y0:a,x1:o,y1:s}=Wy(n.angle,t.width,t.height),c=e.createLinearGradient(i,a,o,s);c.addColorStop(0,n.from),c.addColorStop(1,n.to),e.fillStyle=c}e.fillRect(0,0,t.width,t.height);let i=n.wallpaper;if(i===null||r.kind===`solid`||r.kind===`gradient`)return;e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`;let a=e.getTransform();if(a.a===1&&a.d===1&&a.b===0&&a.c===0){e.drawImage(qy(i,t),0,0);return}let{sx:o,sy:s,sw:c,sh:l}=Py(i,t);e.drawImage(i.image,o,s,c,l,0,0,t.width,t.height)}var Ky=new WeakMap;function qy(e,t){let n=Ky.get(e.image);if(n?.width===t.width&&n.height===t.height)return n;let r=new OffscreenCanvas(t.width,t.height),i=r.getContext(`2d`);if(i===null)throw Error(`the wallpaper's copy has no 2D context`);let{sx:a,sy:o,sw:s,sh:c}=Py(e,t);return i.imageSmoothingEnabled=!0,i.imageSmoothingQuality=`high`,i.drawImage(e.image,a,o,s,c,0,0,t.width,t.height),Ky.set(e.image,r),r}function Jy(e,t){let{frameRect:n,cornerRadius:r}=t,i=Math.min(r,n.width/2,n.height/2);e.beginPath(),e.roundRect(n.x,n.y,n.width,n.height,i)}function Yy(e,t,n){if(t.padding===0)return;let r=t.frameRect.height/800*n,i=[{blur:60*r,offset:30*r,alpha:.18},{blur:12*r,offset:4*r,alpha:.12}];for(let n of i)e.save(),e.shadowColor=`rgba(15, 23, 42, ${n.alpha})`,e.shadowBlur=n.blur,e.shadowOffsetY=n.offset,e.fillStyle=`#000000`,Jy(e,t),e.fill(),e.restore()}function Xy(e,t){Jy(e,t),e.clip()}function Zy(e,t,n){let r=n.logo;if(!r)return;let{rect:i}=r;e.save(),e.globalAlpha=r.opacity,e.drawImage(r.image.image,i.x,i.y,i.width,i.height),e.restore()}function Qy(e,t,n,r){let i=e.plan.viewport,{frameRect:a}=t;return Bl(e,r,Vy(a,i),a,i,n)}function $y(e,t,n,r){let i=Vy(n,r)*t.scale;return{x:n.x+n.width/2+(e.x-t.center.x)*i,y:n.y+n.height/2+(e.y-t.center.y)*i}}function eb(e,t,n,r){let i=$y({x:e.x,y:e.y},t,n,r),a=Vy(n,r)*t.scale;return{x:i.x,y:i.y,width:e.width*a,height:e.height*a}}function tb(e,t,n){let r=Wu(n),i=e.cursor[0];if(r===0||!i)return[];let a=32*n,o=[];for(let n=r;n>=1;n--){let s=t-a*n/r;if(s<0)continue;let c=_l(e.timeline,s);if(c<i.sourceTimeMs)continue;let l=Su(e.cursor,c);l&&o.push({x:l.x,y:l.y,outputMs:s})}return o}function nb(e,t,n,r){return tb(e,t,n).map(t=>({x:t.x,y:t.y,angleRad:sd(e,t.outputMs,r)}))}async function rb(e){let{resolved:t,target:n,presentation:r,frames:i,ctx:a,outputTimeMs:o}=e,s=e.onStage?(t,n)=>{let r=performance.now();n(),e.onStage?.(t,performance.now()-r)}:(e,t)=>t(),c=t.plan.viewport,{frameRect:l}=r,u=_l(t.timeline,o),d=Vy(l,c),f=Qy(t,r,n,o),p=e.onStage?performance.now():0,m=await i.at(u);e.onStage?.(`fetch`,performance.now()-p);let h=()=>{a.translate(l.x+l.width/2,l.y+l.height/2),a.scale(f.scale,f.scale),a.translate(-f.focus.x,-f.focus.y)};a.save(),h(),s(`background`,()=>Gy(a,n,r)),s(`chrome`,()=>Yy(a,r,f.scale)),a.restore(),a.save(),h(),Xy(a,r),a.setTransform(1,0,0,1,0,0);let g=$y({x:0,y:0},f,l,c),_=d*f.scale;s(`frame`,()=>{a.imageSmoothingEnabled=!0,a.imageSmoothingQuality=`high`,a.drawImage(m.image,g.x,g.y,c.width*_,c.height*_)}),s(`cosmetics`,()=>ly(a,t.cosmetics.filter(e=>e.range===null||o>=e.range.startMs&&o<e.range.endMs),e=>eb(e,f,l,c))),a.restore(),a.save(),h(),s(`logo`,()=>Zy(a,n,r)),a.restore(),s(`blur`,()=>oy(a,ry({camera:t,outputTimeMs:o,blur:t.motion.blur,current:f,base:d,frameRect:l,viewport:c,canvas:n}))),a.save(),h(),Xy(a,r),a.setTransform(1,0,0,1,0,0);let v=e.onStage?performance.now():0,y=t.cursorLook,b=y.hidden||t.touch?null:Su(t.cursor,u);if(b){let e=$y(b,f,l,c),r=n.height/1080*y.scale*f.scale,i=a.globalAlpha;a.globalAlpha=y.hideWhenIdle?Mu(t.cursorRestOutputMs,o):1;let s=y.style===`touch`?0:y.tilt??qs.tilt,u=sd(t,o,s),d=nb(t,o,y.motionBlur,s).map(e=>({...$y(e,f,l,c),angleRad:e.angleRad})),p=d[0];p&&Math.hypot(e.x-p.x,e.y-p.y)>=1&&Gu(a,d,r,y.style);for(let n of t.clickOutputMs){let t=(o-n)/400;t>=0&&t<=1&&Ku(a,e,r,t)}Hu(a,e,r,{press:Qu(o,t.clickOutputMs,y.clickBounce??qs.clickBounce,t.holdOutputMs),angleRad:u},y.style),a.globalAlpha=i}if(t.touch&&!y.hidden){let e=n.height/1080*y.scale*f.scale,r=a.globalAlpha;for(let n of t.taps){let t=o-n.outputMs;if(t<-110||t>400)continue;let r=$y(n.at,f,l,c);a.globalAlpha=t<0?1+t/110:1-t/400,t>=0&&Ku(a,r,e,t/400),Hu(a,r,e,{press:Qu(o,[n.outputMs],1),angleRad:0},`touch`)}a.globalAlpha=r}e.onStage?.(`cursor`,performance.now()-v),a.restore()}function ib(e,t){let n=Ro(e,t);return n?n.width:zo(e,t)?.width??0}function ab(e){let{keys:t,timeline:n,bundle:r,outputPxPerCssPx:i,viewport:a}=e,o=[],s=t.map(e=>{let t=ib(r,_l(n,e.outputTimeMs));if(t===0)return e;let s=zo(r,_l(n,e.outputTimeMs))?.width,c=(s===void 0||s===0?t:s)/a.width,l=i*e.scale;if(l<=c&&t>=l*a.width)return e;let u=z(c/i,1,e.scale),d=i*u*a.width;return(u<e.scale||t<d)&&o.push({outputTimeMs:e.outputTimeMs,requestedScale:e.scale,grantedScale:u,sourceWidth:t,neededWidth:d}),{...e,scale:u}});return o.push(...ob(s,o,n,r,i,a)),{keys:s,violations:o}}function ob(e,t,n,r,i,a){let o=[];for(let s of r.motionSpans){let c=vl(n,s.startMs),l=vl(n,s.endMs);if(l<=c||!Io(s,r.viewport)||t.some(e=>e.outputTimeMs>=c&&e.outputTimeMs<l&&e.sourceWidth===s.width))continue;let u=1;for(let t of e)if(t.outputTimeMs<=c)u=t.scale;else if(t.outputTimeMs<l)u=Math.max(u,t.scale);else break;if(u<=1)continue;let d=i*u*a.width;s.width<d&&o.push({outputTimeMs:c,requestedScale:u,grantedScale:u,sourceWidth:s.width,neededWidth:d})}return o}function sb(e,t){let n=jy(t,e.cameraIntents);return n===e.cameraIntents?e:{...e,cameraIntents:n}}function cb(e,t,n){if(e.fit!==`cover`)return null;let r=Vy(t,n);return{width:t.width/r,height:t.height/r}}function lb(e){let{plan:t,bundle:n,scene:r,target:i,hints:a,logo:o=null,wallpaper:s=null}=e,c=e.detailTarget??i,l=By(r?.branding??ic,i,t.viewport,o,s),u=c===i?l.frameRect:By(r?.branding??ic,c,t.viewport,o).frameRect,d=Fu(sb(t,i),n,r,a,cb(i,u,t.viewport)),f=ab({keys:d.cameraKeys,timeline:d.timeline,bundle:n,outputPxPerCssPx:Vy(u,t.viewport),viewport:t.viewport});return{resolved:{...d,cameraKeys:f.keys,cameraFollow:Pu({keys:f.keys,plan:d.plan,bundle:n,timeline:d.timeline,cursor:d.cursor,motion:d.motion,drawsPointer:!d.touch&&!d.cursorLook.hidden})},presentation:l,violations:f.violations}}function ub(e){let t=new OffscreenCanvas(64,64).getContext(`2d`);t.drawImage(e,0,0,64,64);let{data:n}=t.getImageData(0,0,64,64),r=new Float32Array(4096);for(let e=0;e<r.length;e++){let t=n[e*4]??0,i=n[e*4+1]??0,a=n[e*4+2]??0;r[e]=(.2126*t+.7152*i+.0722*a)/255}return r}function db(e,t){let n=0;for(let r=0;r<e.length;r++)n+=Math.abs((e[r]??0)-(t[r]??0));return n/e.length}async function fb(e,t,n){let r=(t,n)=>e.motionSpans.some(e=>e.startMs<n&&e.endMs>t)||e.degradations.some(e=>Qc(e)&&e.startMs<n&&e.endMs>t),i=[];for(let a=1;a<e.keyframes.length;a++){let o=e.keyframes[a-1],s=e.keyframes[a];!o||!s||s.sourceTimeMs<=o.sourceTimeMs||r(o.sourceTimeMs,s.sourceTimeMs)||db(ub((await t.at(o.sourceTimeMs)).image),ub((await t.at(s.sourceTimeMs)).image))>n&&i.push({startMs:o.sourceTimeMs,endMs:s.sourceTimeMs})}return i}var pb=.12;function mb(e,t,n){let r=Py(t,e).sw/e.width;return n*pb*Math.min(e.width,e.height)*r}function hb(e,t){if(t<=0)return e;let{width:n,height:r}=e,i=Math.min(Math.ceil(t*3),n,r),a=new OffscreenCanvas(n+2*i,r+2*i),o=a.getContext(`2d`);if(o===null)throw Error(`no 2D context to blur ${n}×${r} on`);for(let t of[-1,0,1])for(let a of[-1,0,1])o.setTransform(t===0?1:-1,0,0,a===0?1:-1,t===1?i+2*n:i,a===1?i+2*r:i),o.drawImage(e.image,0,0,n,r);let s=new OffscreenCanvas(n,r),c=s.getContext(`2d`);if(c===null)throw Error(`no 2D context to blur ${n}×${r} on`);return c.filter=`blur(${t}px)`,c.drawImage(a,-i,-i),{...e,image:s.transferToImageBitmap()}}function gb(e){if(e==null)return{state:`missing`};let t=nc.safeParse(vb(e));return t.success?{state:`ready`,kit:t.data}:{state:`invalid`,reason:t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}}var _b=.08;function vb(e){return typeof e!=`object`||!e||Array.isArray(e)||`padding`in e?e:{...e,padding:_b}}var yb=e=>e.trim().toLocaleLowerCase();function bb(e,t,n=!1){if(e==null)return{state:`ready`,kits:[],defaultId:null,migrationPending:n};if(!Array.isArray(e))return{state:`invalid`,reason:`the kit list is not a list (${typeof e})`};let r=[];for(let[t,n]of e.entries()){let e=n;if(typeof e?.id!=`string`||e.id===``)return{state:`invalid`,reason:`kit ${t+1}: it has no id`};if(typeof e.name!=`string`||e.name.trim()===``)return{state:`invalid`,reason:`kit ${t+1}: it has no name`};let i=gb(e.branding),a=i.state===`missing`?{state:`invalid`,reason:`the kit holds no branding`}:i;r.push({id:e.id,name:e.name,read:a})}return{state:`ready`,kits:r,defaultId:typeof t==`string`&&t!==``?t:r[0]?.id??null,migrationPending:n}}function xb(e){return e.state!==`ready`||e.defaultId===null?null:e.kits.find(t=>t.id===e.defaultId)??null}var Sb=(e,t,n)=>`${e} ${e===1?t:n}`,Cb=e=>{let t=Math.round(e/1e3);return t<1e3?`${e>0?Math.max(1,t):0} KB`:`${Math.round(e/1e5)/10} MB`};function wb(e,t){return e===void 0||e.byteLength<=e.maxBytes?[]:[`it is ${Cb(e.byteLength)}, over the ${Cb(e.maxBytes)} a GIF is kept under even at ${t} px wide; an MP4 of this video is much smaller`]}function Tb(e){let t=e[0];return t===void 0?[]:[`${Sb(e.length,`step got no still`,`steps got no still`)} (${t.actionId}: ${t.reason})`]}function Eb(e){switch(e.what){case`text`:return`${e.actionId}: "${e.was??``}" → "${e.now??``}"; the video still shows the old text`;case`kind`:return`${e.actionId}: its step changed from ${e.was??``} to ${e.now??``}; the video shows the step as recorded — derive this take, check the step, and run the draft`;case`target`:return`${e.actionId}: its target changed; the video shows the step as recorded`;case`added`:return`${e.actionId}: added after recording; it is not in the video`;case`removed`:return`${e.actionId}: removed after recording; the video still shows it`}}function Db(e,t,n){let r=e[0];if(r===void 0)return[];let i=e.find(e=>e.what===`kind`),a=i===void 0?typeof t==`string`?` — run({ flow: { id: "${t}" } }) re-films it`:` — re-film it with run's flow: { id }`:i===r?``:` — ${i.actionId}'s step changed from ${i.was??``} to ${i.now??``}, so derive this video, check the step, and run the draft`;return[`${Sb(e.length,`step was`,`steps were`)} edited after filming (${Eb(r)})${a}`,...n>0?[`a re-recording leaves its ${Sb(n,`mask`,`masks`)} behind`]:[]]}function Ob(e){let{logo:t,wallpaperWarning:n,unavailableSpans:r,migration:i,editedSinceRecorded:a,masks:o,unplacedStills:s,gifSize:c,videoSize:l}=e.warnings;return[...l?.settingUnreadable===void 0?[]:[`it is ${l.quality} quality, not your Export quality setting, which could not be read (${l.settingUnreadable.replace(/\.$/,``)})`],...t===null?[]:[`the logo is missing (${t})`],...n===void 0?[]:[`${n.sentence.charAt(0).toLowerCase()}${n.sentence.slice(1).replace(/\.$/,``)}`],...r.length===0?[]:[`${Sb(r.length,`stretch of motion is a still`,`stretches of motion are stills`)}`],...Tb(s??[]),...(i??[]).map(e=>e.replace(/\.$/,``)),...Db(a??[],e.warnings.videoId,o??0),...wb(c,e.width)]}var kb=[`share`,`high`,`full`],Ab={share:`Sharing`,high:`High`,full:`Full`},jb=`high`;function Mb(e){return{padding:e.branding.padding,viewport:e.meta.capture.viewport}}function Nb(e,t){return e?.viewport??t.viewport}function Pb(e,t,n,r){switch(e){case`mp4`:{let e=t?Ty(t,n):fy;return r!==void 0&&r.width<e.width?r:e}case`gif`:return yy;case`stills`:return by}}function Fb(e){return e.width>=my.width?my:{...my,width:e.width,height:e.height,cornerRadius:e.cornerRadius,bitrate:Math.round(my.bitrate*e.width*e.height/(my.width*my.height))}}function Ib(e){return e.width>=gy.width?gy:{...e,bitrate:Math.min(e.bitrate,gy.bitrate)}}function Lb(e,t,n,r,i={}){let a=e===`mp4`?i.quality??`full`:`full`;if(t!==`9:16`){let o=Pb(e,n,t,i.maxTier),s=Ey(t,a===`share`?Fb(o):a===`high`?Ib(o):o,Nb(n,r),r.padding);return a===`high`&&s.bitrate>1e7?{...s,bitrate:_y}:s}switch(e){case`mp4`:return a===`share`?hy:a===`high`?vy:py;case`gif`:return xy;case`stills`:return Sy}}var Rb=new Set([`image/svg+xml`,`image/png`,`image/webp`,`image/jpeg`]);function zb(e){return e.type===``?{ok:!1,reason:`The logo "${e.name}" has no file type — use SVG, PNG, WebP or JPEG`}:Rb.has(e.type)?e.size>2097152?{ok:!1,reason:`The logo "${e.name}" is ${(e.size/1024/1024).toFixed(1)} MB — logos are limited to 2 MB`}:{ok:!0,note:e.type===`image/jpeg`?`JPEG has no transparency — the logo shows as a box on the background`:null}:{ok:!1,reason:`The logo "${e.name}" is a ${e.type} file — use SVG, PNG, WebP or JPEG`}}function Bb(e){return e.type===``?{ok:!1,reason:`The image "${e.name}" has no file type — use PNG, JPEG, WebP or SVG`}:Rb.has(e.type)?{ok:!0}:{ok:!1,reason:`The image "${e.name}" is a ${e.type} file — use PNG, JPEG, WebP or SVG`}}var Vb=e=>({image:e,width:e.width,height:e.height,sourceTimeMs:0});function Hb(e){let t=new DOMParser().parseFromString(e,`image/svg+xml`),n=t.documentElement;if(t.querySelector(`parsererror`)!==null||n.nodeName.toLowerCase()!==`svg`)throw Error(`the file is not an SVG`);return n}var Ub=e=>{if(e===null)return null;let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0&&!e.trim().endsWith(`%`)?t:null};function Wb(e){let t=Hb(e),n=Ub(t.getAttribute(`width`)),r=Ub(t.getAttribute(`height`));if(n!==null&&r!==null)return n/r;let i=t.getAttribute(`viewBox`)?.trim().split(/[\s,]+/).map(Number);if(i&&i.length===4&&i[2]>0&&i[3]>0)return i[2]/i[3];throw Error(`the SVG has no width, height or viewBox, so there is no size to draw it at`)}async function Gb(e){let t=Wb(new TextDecoder().decode(e)),n=new Map,r=async n=>{let r=Math.max(1,Math.round(n*t)),i=Math.max(1,Math.round(n)),a=URL.createObjectURL(new Blob([e.slice()],{type:`image/svg+xml`}));try{let e=new Image;e.src=a,await e.decode().catch(e=>{throw Error(`the SVG could not be decoded: ${e instanceof Error?e.message:String(e)}`)});let t=new OffscreenCanvas(r,i);return t.getContext(`2d`).drawImage(e,0,0,r,i),Vb(await createImageBitmap(t))}finally{URL.revokeObjectURL(a)}};return{contentType:`image/svg+xml`,aspect:t,naturalHeight:null,rasterAt(e){let t=Math.max(1,Math.round(e)),i=n.get(t);if(i===void 0){let e=r(t);i=e,e.catch(()=>{n.get(t)===e&&n.delete(t)})}else n.delete(t);for(n.set(t,i);n.size>4;)n.delete(n.keys().next().value);return i}}}async function Kb(e,t){if(t===`image/svg+xml`){let t=await Gb(e);return await t.rasterAt(64),t}let n;try{n=await createImageBitmap(new Blob([e.slice()],{type:t}))}catch(e){throw Error(`the ${t} could not be decoded: ${e instanceof Error?e.message:String(e)}`)}let r=Vb(n);return{contentType:t,aspect:n.width/n.height,naturalHeight:n.height,rasterAt:async()=>r}}async function qb(e,t,n){let r=new Blob([e.slice()],{type:t}),i;try{i=await(n===void 0?createImageBitmap(r):createImageBitmap(r,{resizeWidth:n.width,resizeHeight:n.height,resizeQuality:`high`}))}catch(e){throw Error(`the ${t} could not be decoded: ${e instanceof Error?e.message:String(e)}`)}return{image:i,width:i.width,height:i.height,sourceTimeMs:0}}var Jb=`image/webp`,Yb=.97;async function Xb(e){let t=e instanceof File?e.name:`(unnamed)`,n,r,i;try{if(e.type===`image/svg+xml`){let t=await Kb(new Uint8Array(await e.arrayBuffer()),e.type),a=await t.rasterAt(t.aspect>=1?My/t.aspect:My);({image:n,width:r,height:i}=a)}else{let t=await createImageBitmap(e),a=Math.min(1,My/Math.max(t.width,t.height));r=Math.max(1,Math.round(t.width*a)),i=Math.max(1,Math.round(t.height*a)),n=a===1?t:await createImageBitmap(t,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`}),n!==t&&t.close()}}catch(e){throw Error(`The image "${t}" could not be opened as an image`,{cause:e})}let a=new OffscreenCanvas(r,i);a.getContext(`2d`).drawImage(n,0,0),`close`in n&&n.close();let o;try{o=await a.convertToBlob({type:Jb,quality:Yb})}catch(e){throw Error(`The image "${t}" opened but could not be saved as WebP: ${e instanceof Error?e.message:String(e)}`)}if(o.type!==Jb)throw Error(`The image "${t}" opened but this browser saved it as ${o.type||`nothing`}, not WebP`);return{blob:o,width:r,height:i}}var Zb=`X-Demoman-Studio`,Qb={ping:{method:`GET`,path:`/api/ping`},takes:{method:`GET`,path:`/api/takes`},sceneGet:{method:`GET`,path:`/api/takes/:id/scene`},scenePut:{method:`PUT`,path:`/api/takes/:id/scene`},takeDelete:{method:`DELETE`,path:`/api/takes/:id`},videoRename:{method:`PUT`,path:`/api/videos/:id/name`},videoDelete:{method:`DELETE`,path:`/api/videos/:id`},repoAddable:{method:`GET`,path:`/api/videos/:id/repo`},repoAdd:{method:`POST`,path:`/api/videos/:id/repo`},repoRemove:{method:`DELETE`,path:`/api/videos/:id/repo`},repoCiState:{method:`GET`,path:`/api/repo/ci`},repoCiPlan:{method:`POST`,path:`/api/repo/ci/plan`},repoCiApply:{method:`POST`,path:`/api/repo/ci/apply`},repoPr:{method:`POST`,path:`/api/repo/pr`},repoFolders:{method:`GET`,path:`/api/repo/folders`},bundle:{method:`GET`,path:`/api/takes/:id/bundle`},frame:{method:`GET`,path:`/api/takes/:id/frames/:ref`},thumb:{method:`GET`,path:`/api/takes/:id/thumbs/:ref`},outputs:{method:`GET`,path:`/api/takes/:id/outputs`},exportStart:{method:`POST`,path:`/api/takes/:id/exports`},kitsGet:{method:`GET`,path:`/api/kits`},kitsPut:{method:`PUT`,path:`/api/kits`},kitsReset:{method:`POST`,path:`/api/kits/reset`},assetPut:{method:`POST`,path:`/api/assets`},logo:{method:`GET`,path:`/api/logo`},wallpaperPut:{method:`POST`,path:`/api/wallpapers`},wallpaper:{method:`GET`,path:`/api/wallpaper`},pullRequestsGet:{method:`GET`,path:`/api/settings/pull-requests`},pullRequestsPut:{method:`PUT`,path:`/api/settings/pull-requests`},exportQualityGet:{method:`GET`,path:`/api/settings/export-quality`},exportQualityPut:{method:`PUT`,path:`/api/settings/export-quality`},libraryViewGet:{method:`GET`,path:`/api/settings/library-view`},libraryViewPut:{method:`PUT`,path:`/api/settings/library-view`},reveal:{method:`POST`,path:`/api/reveal`},window:{method:`POST`,path:`/api/window`},events:{method:`GET`,path:`/api/events`}};function $b(e,t={}){return Qb[e].path.split(`/`).map(n=>{if(!n.startsWith(`:`))return n;let r=n.slice(1),i=t[r];if(i===void 0)throw Error(`pathFor("${e}") needs the param "${r}"`);return encodeURIComponent(i)}).join(`/`)}var ex=`X-File-Name`,tx=Object.freeze({layout:`list`,sort:Object.freeze({column:`recorded`,descending:!0}),project:null}),nx=[`all`,`none`,`unreadable`];function rx(e){let t=new URLSearchParams(e).get(`project`);return t===null||t===``?null:nx.includes(t)?t:{project:t}}function ix(e){return`?project=${encodeURIComponent(typeof e==`string`?e:e.project)}`}var ax=`brandKit`,ox=`brandKits`,sx=`defaultKitId`;function cx(e,t,n){let r=e.trim();if(r===``)return{ok:!1,reason:`a kit needs a name`};if(r.length>40)return{ok:!1,reason:`a kit's name is at most 40 characters`};let i=t.find(e=>e.id!==n&&yb(e.name)===yb(r));return i===void 0?{ok:!0,name:r}:{ok:!1,reason:`a kit is already named "${i.name}"`}}function lx(e,t){let n=new Set(t.map(e=>yb(e.name)));if(!n.has(yb(e)))return e;for(let t=2;;t+=1){let r=`${e} ${t}`;if(!n.has(yb(r)))return r}}var ux=()=>`kit-${crypto.randomUUID()}`,dx=`demoman-brand-kits`,fx=Promise.resolve(),px=e=>{let t=fx.then(e);return fx=t.catch(()=>void 0),t},mx=e=>typeof navigator<`u`&&navigator.locks!==void 0?navigator.locks.request(dx,e):px(e),hx=e=>e instanceof Error?e.message:String(e),gx=`kit-migrated`,_x=class extends Error{};function vx(e,t=mx){async function n(){let t=await e().get([ox,sx,ax]),n=t[ox],r=t[sx],i=t[ax];if(i===void 0)return{list:n,def:r,pending:!1};if(n===void 0){let t=gx;n=[{id:t,name:`Brand kit`,branding:i}],r=t;try{await e().set({[ox]:n,[sx]:r})}catch(e){throw new _x(hx(e))}}try{return await e().remove(ax),{list:n,def:r,pending:!1}}catch(e){return console.info(`demoman: could not remove the old brand kit key; the next read retries`,e),{list:n,def:r,pending:!0}}}async function r(){try{let{list:e,def:r,pending:i}=await t(n);return bb(e,r,i)}catch(e){return{state:`invalid`,storageRefused:!0,reason:e instanceof _x?`storage refused moving your brand kit into the kit list: ${e.message}`:`storage refused the read: ${hx(e)}`}}}async function i(){try{let{list:e,def:t}=await n(),r=bb(e,t);return r.state===`invalid`?`your brand kits could not be read (${r.reason}), so nothing was changed`:{kits:e??[],defaultId:r.defaultId}}catch(e){return`your brand kits could not be read (${hx(e)}), so nothing was changed`}}return{read:r,readStored:()=>t(i),update:n=>t(async()=>{let t=await i();if(typeof t==`string`)return t;let r=await n(t);return typeof r==`string`?r:(await e().set({[ox]:r.kits,[sx]:r.defaultId}),null)}),reset:()=>t(()=>e().set({[ox]:[],[sx]:null}))}}async function yx(e,t){if(e.startsWith(`span:`))return t;let n=new Blob([t.slice()],{type:`image/jpeg`}),r=await createImageBitmap(n);return{image:r,width:r.width,height:r.height,sourceTimeMs:0}}var bx=/`([^`]*)`/g;function xx(e,t=document){let n=[],r=0;for(let i of e.matchAll(bx)){let a=i.index??0;a>r&&n.push(e.slice(r,a));let o=t.createElement(`code`);o.textContent=i[1]??``,n.push(o),r=a+i[0].length}return r<e.length&&n.push(e.slice(r)),n}var Sx=e=>e.replace(bx,`$1`);function Cx(e,t){e.replaceChildren(...xx(t,e.ownerDocument))}var wx={expired:"This Studio link has expired; run `npx demoman studio`.",stopped:"The Studio stopped — run `npx demoman studio`.",updated:`The Studio was updated; reopen it.`},Tx=e=>Sx(wx[e]);function Ex(e,t=document){let n=t.body;if(n===null||n.querySelector(`[data-studio-gone]`)!==null)return;for(let e of Array.from(n.children))e instanceof HTMLElement&&(e.inert=!0);let r=t.createElement(`main`);r.className=`gone`,r.dataset.studioGone=e,r.setAttribute(`role`,`alert`);let i=t.createElement(`p`);i.append(...xx(wx[e],t)),r.append(i),n.append(r)}var Dx=class extends Error{reason;status;constructor(e,t,n){super(t),this.name=`StudioError`,this.reason=e,this.status=n}},Ox=new Set([`hostRefused`,`tokenMissing`,`tokenWrong`,`headerMissing`]),kx=`Your brand kits kept changing in another window, so this change was not saved.`,Ax=`Ask your agent for a demo video. Each flow shows up here, grouped by the day it was last recorded.`,jx=e=>`Ask your agent to record it again: \`run({ flow: { id: "${e}" } })\``,Mx=`Ask your agent to record this again.`,Nx=e=>`Couldn't read which flow this video is in: ${e}`,Px=e=>e instanceof Error?e.message:String(e),Fx=e=>e.slice(e.lastIndexOf(`/`)+1)||e;function Ix(e){let t=`message`,n=[];for(let r of e.split(`
|
|
66
|
-
`)){if(r===``||r.startsWith(`:`))continue;let e=r.indexOf(`:`),i=e<0?r:r.slice(0,e),a=e<0?``:r.slice(e+1);a.startsWith(` `)&&(a=a.slice(1)),i===`event`?t=a:i===`data`&&n.push(a)}return n.length===0?null:{type:t,data:n.join(`
|
|
67
|
-
`)}}function Lx(e){return e.fileType===`stills`?{kind:`saved`,names:e.folder.files.map(e=>e.name),byteLength:e.folder.files.reduce((e,t)=>e+t.byteLength,0),reveal:{kind:`path`,path:e.folder.path},summary:e.summary,outputRefs:[]}:{kind:`saved`,names:[Fx(e.file.path)],byteLength:e.file.byteLength,reveal:{kind:`path`,path:e.file.path},summary:e.summary,outputRefs:[]}}function Rx(e){try{return Ob(e)}catch(e){return[`its warnings could not be read: ${e instanceof Error?e.message:String(e)}`]}}function zx(e){let{report:t}=e,n=t.outcome===`saved`?t:null,r=n===null?null:n.fileType===`stills`?`${n.width}×${n.height}`:`${n.width}×${n.height} · ${n.fps} fps`;return{kind:`file`,key:`${e.path}@${e.renderedAt}`,name:Fx(e.path),byteLength:e.byteLength,path:e.path,exists:e.exists,sceneDigest:e.sceneDigest,renderedAt:e.renderedAt,detail:r,caveats:n===null?[]:Rx(n)}}function Bx(e={}){let t=!1,n=null,r=new Map,i=new Map,a=new Map,o=new Map,s=(e,t)=>{let n=e.get(t.jobId)??[];n.push(t),n.length>50&&n.shift(),e.set(t.jobId,n),e.size>20&&e.delete(e.keys().next().value)},c=e=>{if(!t){n??=e,Ex(e);for(let[t,n]of[...r])n({type:`repo`,videoId:``,jobId:t,phase:`failed`,reason:`studioGone`,detail:Tx(e)});for(let[t,n]of[...a])n({type:`ci`,jobId:t,phase:`done`,step:`plan`,answer:{reason:`studioGone`,detail:Tx(e)}})}};async function l(e,t={}){let n=Qb[e];n.method!==`GET`&&await f;let r=$b(e,t.params);t.query!==void 0&&(r+=`?${new URLSearchParams(t.query).toString()}`);let i={[Zb]:`1`,...t.headers},a;t.json===void 0?t.raw!==void 0&&(a=t.raw):(i[`Content-Type`]=`application/json`,a=JSON.stringify(t.json));let o;try{o=await fetch(r,{method:n.method,headers:i,body:a,credentials:`same-origin`,signal:t.signal})}catch(e){throw t.retried!==!0&&c(`stopped`),new Dx(`studioGone`,`The Studio did not answer ${n.method} ${r} (${Px(e)}).`,0)}if(o.ok)return o;let s=null;try{s=await o.json()}catch{}let l=typeof s?.reason==`string`?s.reason:`noReason`,u=typeof s?.detail==`string`?s.detail:`The Studio answered ${o.status} to ${n.method} ${r} without saying why.`;throw o.status===403&&(l===`noReason`||Ox.has(l))&&c(`expired`),new Dx(l,u,o.status)}async function u(e){try{return await e.json()}catch(t){throw new Dx(`internalError`,`The Studio's answer was not JSON (${Px(t)}).`,e.status)}}let d=`0.9.2`,f=(async()=>{let e=await u(await l(`ping`));if(e.version!==d)throw c(`updated`),new Dx(`versionSkew`,`${wx.updated} (this page is ${d}, the Studio ${e.version})`,0)})();f.catch(e=>{console.info(`demoman studio: no edits will be sent:`,Px(e))});let p=new Set,m=new Set,h=new Set,g=new Set,_=(e,t,n)=>{for(let r of[...e])try{r(t)}catch(e){console.error(`demoman studio: a ${n} listener failed`,e)}},v=e=>_(p,e,`export`),y=new Set,b=0,x=[];function S(e){if(!y.has(e.jobId)){if(b>0){x.push(e);return}e.phase===`saved`&&v({kind:`outputsChanged`});return}switch(e.phase){case`queued`:v({kind:`queued`,jobId:e.jobId,position:e.position});return;case`rendering`:v({kind:`rendering`,jobId:e.jobId,done:e.done,total:e.total});return;case`saving`:v({kind:`saving`,jobId:e.jobId});return;case`saved`:{y.delete(e.jobId);let t=e.report;t.outcome===`saved`?v({kind:`saved`,jobId:e.jobId,save:Lx(t),summary:t.summary}):v({kind:`failed`,jobId:e.jobId,detail:t.summary}),v({kind:`outputsChanged`});return}case`failed`:y.delete(e.jobId),v({kind:`failed`,jobId:e.jobId,detail:e.detail}),v({kind:`outputsChanged`});return}}function C(e,t){let n;try{n=JSON.parse(t)}catch(t){console.error(`demoman studio: the "${e}" event was not JSON, so it was dropped`,t);return}switch(n.type){case`export`:S(n);return;case`kits`:_(m,void 0,`kits`);return;case`takes`:_(h,void 0,`takes`);return;case`repo`:{let e=r.get(n.jobId);if(e!==void 0){try{e(n)}catch(e){console.error(`demoman studio: a repo listener failed`,e)}return}s(i,n);return}case`ci`:{let e=a.get(n.jobId);if(e!==void 0){try{e(n)}catch(e){console.error(`demoman studio: a ci listener failed`,e)}return}s(o,n);return}case`watchFailed`:switch(n.feed){case`takes`:_(h,void 0,`takes`);return;case`kits`:_(m,void 0,`kits`);return;default:{let e=n.feed;console.info(`demoman studio: a watchFailed for a feed this page does not know: ${String(e)}`);return}}case`open`:_(g,n.path,`open`);return;case`server:stopping`:c(`stopped`);return;default:console.info(`demoman studio: an event this page does not know: ${e}`)}}let w=new AbortController;globalThis.addEventListener?.(`pagehide`,()=>{t=!0,w.abort()});let T=e.reload??(()=>location.reload());globalThis.addEventListener?.(`pageshow`,e=>{e.persisted&&T()});async function ee(){let e=0;for(;;){if(t||n!==null)return;let r;try{let t=(await l(`events`,{signal:w.signal,retried:!0})).body;if(t===null)throw Error(`the event stream has no body`);let n=t.getReader(),i=new TextDecoder,a=``;for(;;){let{done:t,value:r}=await n.read();if(t)break;e=0,a+=i.decode(r,{stream:!0}).replace(/\r\n?/g,`
|
|
68
|
-
`);let o=a.indexOf(`
|
|
69
|
-
|
|
70
|
-
`);for(;o>=0;){let e=Ix(a.slice(0,o));a=a.slice(o+2),e!==null&&C(e.type,e.data),o=a.indexOf(`
|
|
71
|
-
|
|
72
|
-
`)}}r=`the Studio closed the event stream`}catch(e){if(e instanceof Dx&&e.status===403)return;r=Px(e)}if(t||n!==null)return;if(e+=1,e>=2){console.info(`demoman studio: the event stream is gone (${r})`),c(`stopped`);return}console.info(`demoman studio: reconnecting the event stream (${r})`)}}ee();let te=new Map,E=null,ne=null,D={async get(){let e=await u(await l(`kitsGet`));if(E=e.revision,ne=e.unwatched,`invalid`in e)throw Error(e.invalid.reason);return{[ox]:e.stored.kits,[sx]:e.stored.default}},async set(e){if(E===null)throw Error(`the brand kits were written before they were read`);E=(await u(await l(`kitsPut`,{json:{kits:e.brandKits??[],default:e.defaultKitId??null},headers:{"If-Match":E}}))).revision},async remove(){throw Error(`the Studio keeps no old brand kit key to remove`)}},re=vx(()=>D,e.kitLock),ie={async read(){let e;try{e=await u(await l(`kitsGet`)),ne=e.unwatched}catch(e){return{state:`invalid`,storageRefused:!0,reason:`the Studio did not answer the kits read: ${Px(e)}`}}return`invalid`in e?{state:`invalid`,reason:e.invalid.reason,...e.invalid.storageRefused===!0?{storageRefused:!0}:{}}:bb(e.stored.kits,e.stored.default)},readStored:()=>re.readStored(),async update(e){for(let t=1;;t+=1)try{return await re.update(e)}catch(e){if(!(e instanceof Dx&&e.status===409))throw e;if(t>=3)throw new Dx(`kitsBusy`,kx,409)}},async reset(){return{backup:(await u(await l(`kitsReset`))).backup}},onChange(e){return m.add(e),()=>m.delete(e)},unwatched:()=>ne};async function ae(e){try{let t=await u(await e);return{ok:!0,...t.note===null?{}:{note:t.note},...t.partly===void 0?{}:{partly:t.partly}}}catch(e){if(!(e instanceof Dx)||e.status===0)throw e;return{ok:!1,error:e.reason,detail:e.message.replace(/\.$/,``)}}}let oe=new Map,O=new Map;async function se(){let e=await u(await l(`takes`));for(let[t,n]of Object.entries(e.videoOf))oe.set(t,n.videoId);return{videos:e.videos,videoOf:e.videoOf,scenes:e.scenes,sizes:e.sizes,unreadable:e.unreadable,unwatched:e.unwatched,addable:e.addable}}return{scenes:{async get(e){try{let t=await u(await l(`sceneGet`,{params:{id:e}}));return t.videoId===null?oe.delete(e):oe.set(e,t.videoId),t.videoError===null?O.delete(e):O.set(e,t.videoError),{scene:t.scene,revision:t.revision,notes:t.notes}}catch(e){if(e instanceof Dx&&e.reason===`takeNotFound`)return null;throw e}},async put(e,t){return{revision:(await u(await l(`scenePut`,{params:{id:e.meta.id},json:e,headers:t===null?{}:{"If-Match":t}}))).revision}},async list(){return(await se()).scenes},remove:e=>ae(l(`takeDelete`,{params:{id:e}}))},videos:{async rename(e,t){await u(await l(`videoRename`,{params:{id:e},json:{name:t}}))},remove:e=>ae(l(`videoDelete`,{params:{id:e}})),repo:{async addable(e){return u(await l(`repoAddable`,{params:{id:e}}))},async folders(e){return u(await l(`repoFolders`,{query:{root:e}}))},async add(e,t){return u(await l(`repoAdd`,{params:{id:e},json:t}))},async remove(e){return u(await l(`repoRemove`,{params:{id:e}}))},onRepo(e,t){for(let n of i.get(e)??[])t(n);return i.delete(e),r.set(e,t),()=>r.delete(e)}}},repoCi:{async state(e){return u(await l(`repoCiState`,{query:{root:e}}))},async plan(e){return u(await l(`repoCiPlan`,{json:e}))},async apply(e){return u(await l(`repoCiApply`,{json:e}))},async openPr(e){return u(await l(`repoPr`,{json:e}))},onCi(e,t){for(let n of o.get(e)??[])t(n);return o.delete(e),a.set(e,t),()=>a.delete(e)}},folder:{read:se,onChange(e){return h.add(e),()=>h.delete(e)},async thumb(e){let t=te.get(e);if(t===void 0)throw Error(`the frame "${e}" is in no video this page has read a bundle for, so its preview cannot be asked for`);let n=await l(`thumb`,{params:{id:t,ref:e}});return createImageBitmap(await n.blob())}},bundles:{async active(e){let t=await u(await l(`bundle`,{params:{id:e}}));for(let n of t.bundle?.keyframes??[])te.set(n.ref,e);for(let n of t.bundle?.motionSpans??[])te.set(n.ref,e);return{bundle:t.bundle,replay:t.replay??null,capture:null}},async load(e){let t=te.get(e);if(t===void 0)throw Error(`the frame "${e}" is in no video this page has read a bundle for`);let n=await l(`frame`,{params:{id:t,ref:e}});return yx(e,new Uint8Array(await n.arrayBuffer()))}},outputs:{async list(e){return[...(await u(await l(`outputs`,{params:{id:e}}))).outputs].sort((e,t)=>t.renderedAt.localeCompare(e.renderedAt)).map(zx)}},logos:{async put(e){return{ref:(await u(await l(`assetPut`,{raw:e,headers:{[ex]:encodeURIComponent(e.name),"Content-Type":e.type}}))).ref}},async load(e){let t;try{t=await l(`logo`,{query:{ref:e}})}catch(e){return{ok:!1,error:Px(e)}}try{let e=new Uint8Array(await t.arrayBuffer()),n=(t.headers.get(`Content-Type`)??``).split(`;`)[0];return{ok:!0,source:await Kb(e,n?.trim()??``)}}catch(e){return{ok:!1,error:Px(e)}}}},wallpapers:{async put(e){let t=Bb(e);if(!t.ok)throw new Dx(`wallpaperRefused`,t.reason,400);let n;try{n=await Xb(e)}catch(e){throw new Dx(`wallpaperRefused`,Px(e),400)}return{ref:(await u(await l(`wallpaperPut`,{raw:n.blob,headers:{[ex]:encodeURIComponent(e.name),"Content-Type":n.blob.type}}))).ref}},async load(e){try{return{ok:!0,blob:await(await l(`wallpaper`,{query:{ref:e}})).blob()}}catch(e){return{ok:!1,error:Px(e)}}}},kits:ie,pullRequests:{async read(){return u(await l(`pullRequestsGet`))},async write(e){let t=await u(await l(`pullRequestsPut`,{json:{value:e}}));return t.replaced===void 0?{}:{replaced:t.replaced}}},exportQuality:{async read(){let e=await u(await l(`exportQualityGet`));return{quality:e.exportQuality,...e.unreadable===void 0?{}:{unreadable:e.unreadable}}},async write(e){let t=await u(await l(`exportQualityPut`,{json:{exportQuality:e}}));return t.replaced===void 0?{}:{replaced:t.replaced}}},libraryView:{async read(){let e=await u(await l(`libraryViewGet`));return{view:e.view,...e.unreadable===void 0?{}:{unreadable:e.unreadable}}},async write(e){let t=await u(await l(`libraryViewPut`,{json:{view:e}}));return t.replaced===void 0?{}:{replaced:t.replaced}}},exports:{async start(e,{fileType:t,revision:n,quality:r}){if(n===null)throw new Dx(`sceneNotSaved`,`The export was not started: this page has no saved revision of the video to name.`,0);let i={fileType:t,revision:n,...r===void 0?{}:{quality:r}};b+=1;let a=null;try{a=await u(await l(`exportStart`,{params:{id:e},json:i})),y.add(a.jobId)}finally{--b;let e=a?.jobId,t=x.filter(t=>t.jobId===e||b===0);x=x.filter(e=>!t.includes(e));for(let e of t)S(e)}return{jobId:a.jobId}},onEvent(e){return p.add(e),()=>p.delete(e)}},files:{async reveal(e){if(e.kind!==`path`)throw Error(`the Studio shows a file by its path, not a download`);await l(`reveal`,{json:{path:e.path}})}},nav:{editor:e=>`/editor.html?scene=${encodeURIComponent(e)}`,library:()=>`/`,kits:()=>`/settings.html`,firstTakeHint:()=>Ax,rerun:e=>{let t=oe.get(e),n=O.get(e);return{kind:`line`,text:t===void 0?n===void 0?Mx:Nx(n):jx(t)}},onOpen(e){g.add(e)}}}}async function Vx(e,t,n){let r=[],i=async e=>{let t=await n(e);return t instanceof Uint8Array||r.push(t),t};try{let n=xu(e),r=Fu(n,t,e,(e.edits.gaps??[]).length>0?await fb(t,ud(t,i),n.retiming.motionDiffThreshold):[]);if(r.timeline.outputDurationMs===0&&r.timeline.cuts.length>0)return{kind:`nothing`,reason:`its removed pieces leave no frames`};let{startMs:a,endMs:o}=r.range;return r.timeline.outputDurationMs>0&&o<=a?{kind:`nothing`,reason:`its trim leaves no frames`}:{kind:`measured`,ms:o-a}}finally{for(let e of r)e.image.close?.()}}function Hx(e){let t=Math.max(1,Math.round(e/1e3)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=String(t%60).padStart(2,`0`);return n>0?`${n}:${String(r).padStart(2,`0`)}:${i}`:`${r}:${i}`}var Ux={clapperboard:[`m12.296 3.464 3.02 3.956`,`M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z`,`M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,`m6.18 5.276 3.1 3.899`],monitorPlay:[`M15.033 9.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56V7.648a.645.645 0 0 1 .967-.56z`,`M12 17v4`,`M8 21h8`,`M4 3h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`],monitor:[`M4 3h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,`M8 21h8`,`M12 17v4`],smartphone:[`M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z`,`M12 18h.01`],tablet:[`M6 2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z`,`M12 18h.01`],video:[`m22 8-6 4 6 4V8Z`,`M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z`],settings:[`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,`M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z`],folder:[`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`],circleCheck:[`M21.801 10A10 10 0 1 1 17 3.335`,`m9 11 3 3L22 4`],gitBranchPlus:[`M6 3v12`,`M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z`,`M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z`,`M15 6a9 9 0 0 0-9 9`,`M18 15v6`,`M21 18h-6`],gitBranchMinus:[`M15 6a9 9 0 0 0-9 9V3`,`M21 18h-6`,`M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z`,`M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z`],trash:[`M3 6h18`,`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`],file:[`M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z`,`M14 2v6h6`],cloud:[`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`],restore:[`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,`M3 3v5h5`,`M12 7v5l4 2`],image:[`M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,`M9 11a2 2 0 1 0 0-4 2 2 0 0 0 0 4z`,`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`],download:[`M12 15V3`,`m7 10 5 5 5-5`,`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`],refresh:[`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,`M21 3v5h-5`,`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,`M8 16H3v5`],close:[`M18 6 6 18`,`m6 6 12 12`],plus:[`M5 12h14`,`M12 5v14`],chevronLeft:[`m15 18-6-6 6-6`],chevronDown:[`m6 9 6 6 6-6`],shieldCheck:[`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,`m9 12 2 2 4-4`],check:[`M20 6 9 17l-5-5`],undo:[`M9 14 4 9l5-5`,`M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5 5.5 5.5 0 0 1-5.5 5.5H11`],redo:[`m15 14 5-5-5-5`,`M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13`],play:[`M6 3 20 12 6 21Z`],pause:[`M7 4h2a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z`,`M15 4h2a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z`],skipBack:[`M6 5h2v14H6Z`,`M21 19l-11-7 11-7Z`],rewind:[`M11 19 2 12l9-7Z`,`M22 19l-9-7 9-7Z`],fastForward:[`M13 19l9-7-9-7Z`,`M2 19l9-7-9-7Z`],repeat:[`m17 2 4 4-4 4`,`M3 11v-1a4 4 0 0 1 4-4h14`,`m7 22-4-4 4-4`,`M21 13v1a4 4 0 0 1-4 4H3`],circleQuestionMark:[`M22 12a10 10 0 1 1-20 0 10 10 0 1 1 20 0z`,`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,`M12 17h.01`],circleAlert:[`M22 12a10 10 0 1 1-20 0 10 10 0 1 1 20 0z`,`M12 8v4`,`M12 16h.01`],mousePointer2:[`M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z`],bot:[`M12 8V4H8`,`M6 8h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2z`,`M2 14h2`,`M20 14h2`,`M15 13v2`,`M9 13v2`],globe:[`M22 12a10 10 0 1 1-20 0 10 10 0 1 1 20 0z`,`M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20`,`M2 12h20`],type:[`M12 4v16`,`M4 7V4h16v3`,`M9 20h6`],moveVertical:[`M12 2v20`,`m8 18 4 4 4-4`,`m8 6 4-4 4 4`],handGrab:[`M18 11.5V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4`,`M14 10V8a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2`,`M10 9.9V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5`,`M6 14a2 2 0 0 0-2-2a2 2 0 0 0-2 2`,`M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-4a8 8 0 0 1-8-8 2 2 0 1 1 4 0`],hourglass:[`M5 22h14`,`M5 2h14`,`M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22`,`M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2`],mousePointerClick:[`M14 4.1 12 6`,`m5.1 8-2.9-.8`,`m6 12-1.9 2`,`M7.2 2.2 8 5.1`,`M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z`],film:[`M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,`M7 3v18`,`M3 7.5h4`,`M3 12h18`,`M3 16.5h4`,`M17 3v18`,`M17 7.5h4`,`M17 16.5h4`],search:[`m21 21-4.34-4.34`,`M19 11a8 8 0 1 1-16 0 8 8 0 1 1 16 0z`],zoomIn:[`M19 11a8 8 0 1 1-16 0 8 8 0 1 1 16 0z`,`M21 21 16.65 16.65`,`M11 8v6`,`M8 11h6`],eyeOff:[`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,`M14.084 14.158a3 3 0 0 1-4.242-4.242`,`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,`m2 2 20 20`],zoomOut:[`M19 11a8 8 0 1 1-16 0 8 8 0 1 1 16 0z`,`M21 21 16.65 16.65`,`M8 11h6`],magnet:[`m12 15 4 4`,`M2.352 10.648a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.029-6.029a1 1 0 1 1 3 3l-6.029 6.029a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.365-6.367A1 1 0 0 0 8.716 4.282z`,`m5 8 4 4`],moveHorizontal:[`m18 8 4 4-4 4`,`M2 12h20`,`m6 8-4 4 4 4`],scissors:[`M9 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z`,`M8.12 8.12 12 12`,`M20 4 8.12 15.88`,`M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0z`,`M14.8 14.8 20 20`],maximize:[`M8 3H5a2 2 0 0 0-2 2v3`,`M21 8V5a2 2 0 0 0-2-2h-3`,`M3 16v3a2 2 0 0 0 2 2h3`,`M16 21h3a2 2 0 0 0 2-2v-3`],minimize:[`M8 3v3a2 2 0 0 1-2 2H3`,`M21 8h-3a2 2 0 0 1-2-2V3`,`M3 16h3a2 2 0 0 1 2 2v3`,`M16 21v-3a2 2 0 0 1 2-2h3`],server:[`M4 2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z`,`M4 14h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2z`,`M6 6h.01`,`M6 18h.01`],chartColumn:[`M3 3v16a2 2 0 0 0 2 2h16`,`M18 17V9`,`M13 17V5`,`M8 17v-3`],chevronRight:[`m9 18 6-6-6-6`],palette:[`M13.5 6.5h.01`,`M17.5 10.5h.01`,`M8.5 7.5h.01`,`M6.5 12.5h.01`,`M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z`],activity:[`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`],star:[`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`],upload:[`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,`m17 8-5-5-5 5`,`M12 3v12`],list:[`M3 5h.01`,`M3 12h.01`,`M3 19h.01`,`M8 5h13`,`M8 12h13`,`M8 19h13`],layoutGrid:[`M4 3h5a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z`,`M15 3h5a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z`,`M15 14h5a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1v-5a1 1 0 0 1 1-1z`,`M4 14h5a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-5a1 1 0 0 1 1-1z`],ellipsis:[`M6 12a1 1 0 1 1-2 0 1 1 0 1 1 2 0z`,`M13 12a1 1 0 1 1-2 0 1 1 0 1 1 2 0z`,`M20 12a1 1 0 1 1-2 0 1 1 0 1 1 2 0z`],pencilLine:[`M13 21h8`,`m15 5 4 4`,`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`],copy:[`M10 8h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2V10a2 2 0 0 1 2-2Z`,`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`],bookmark:[`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`]},Wx=`http://www.w3.org/2000/svg`,Gx=new Set([`play`,`pause`,`rewind`,`fastForward`,`skipBack`]);function Kx(e){let t=document.createElementNS(Wx,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,Gx.has(e)?`currentColor`:`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`2`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`data-icon`,e);for(let n of Ux[e]){let e=document.createElementNS(Wx,`path`);e.setAttribute(`d`,n),t.append(e)}return t}var qx={glyph:`trash`,title:`Delete video`,body:`This permanently removes the video. It can’t be undone.`,confirmLabel:`Delete`,danger:!0,focus:`cancel`},Jx=(e,t)=>({...qx,title:`Delete video`,body:`This permanently removes ${e===void 0?`this video`:`Video ${e}`} of ${t}. It can’t be undone.`}),Yx=e=>({...qx,title:`Delete flow`,body:`This permanently removes the flow and ${e===1?`its video`:`its ${e} videos`}. It can’t be undone.`}),Xx=(e,t)=>{let n=`${e} ${e===1?`flow`:`flows`}`;return{...qx,title:`Delete ${n}`,body:`This permanently removes ${n} and ${e===1?`its`:`their`} ${t} ${t===1?`video`:`videos`}. It can’t be undone.`}},Zx={...qx,title:`Delete flow record`,body:`This removes the unreadable record. Its videos stay.`},Qx=0;function $x(e){Qx+=1;let t=`confirm-${Qx}`,n=document.createElement(`dialog`);n.className=`confirm-dialog`,n.setAttribute(`data-confirm`,``),n.setAttribute(`aria-labelledby`,`${t}-title`),n.setAttribute(`aria-describedby`,`${t}-body`);let r=document.createElement(`form`);r.method=`dialog`;let i=document.createElement(`h2`);i.className=`confirm-title`,i.id=`${t}-title`,i.textContent=e.title;let a=document.createElement(`p`);a.className=`confirm-body`,a.id=`${t}-body`,a.textContent=e.body;let o=document.createElement(`button`);o.className=`btn btn-quiet`,o.value=`cancel`,o.setAttribute(`data-confirm-cancel`,``),o.append(Kx(`close`),`Cancel`);let s=document.createElement(`button`);s.className=e.danger?`btn btn-quiet confirm-go-danger`:`btn btn-quiet`,s.value=`confirm`,s.setAttribute(`data-confirm-go`,``),s.append(Kx(e.glyph),e.confirmLabel),(e.focus===`cancel`?o:s).autofocus=!0;let c=document.createElement(`div`);c.className=`confirm-actions`,c.append(o,s),r.append(i,a,c),n.append(r);let l=!1;return n.addEventListener(`pointerdown`,e=>{l=e.target===n}),n.addEventListener(`click`,e=>{l&&e.target===n&&n.close(`cancel`),l=!1}),new Promise((e,t)=>{n.addEventListener(`close`,()=>{n.remove(),e(n.returnValue===`confirm`)},{once:!0}),document.body.append(n);try{n.showModal()}catch(e){n.remove(),t(e)}})}var eS=4e3,tS;function nS(e){let t=document.querySelector(`[data-toast]`);t===null&&(t=document.createElement(`div`),t.className=`toast`,t.setAttribute(`data-toast`,``),document.body.append(t));let n=document.createElement(`span`);n.setAttribute(`data-toast-text`,``),n.textContent=e.replace(/\.$/,``),rS(n.textContent),t.replaceChildren(Kx(`check`),n),clearTimeout(tS);let r=t;tS=setTimeout(()=>r.remove(),eS)}function rS(e){let t=document.querySelector(`[data-toast-said]`);t===null&&(t=document.createElement(`div`),t.className=`toast-said`,t.setAttribute(`data-toast-said`,``),t.setAttribute(`role`,`status`),document.body.append(t)),t.textContent=``;let n=t;setTimeout(()=>{n.textContent=e},50)}export{xu as $,xb as A,Zy as B,jb as C,Nb as D,Mb as E,eb as F,fy as G,Uy as H,rb as I,ud as J,ky as K,Vy as L,mb as M,fb as N,Lb as O,lb as P,Su as Q,By as R,zb as S,No as St,kb as T,Ly as U,zy as V,Fy as W,Iu as X,zu as Y,Hu as Z,tx as _,ds as _t,Yx as a,Yc as at,qb as b,as as bt,Kx as c,nc as ct,Bx as d,tc as dt,Bl as et,Cx as f,ac as ft,lx as g,fs as gt,ux as h,oc as ht,$x as i,_l as it,hb as j,gb as k,Vx as l,Zs as lt,cx as m,rc as mt,qx as n,Cl as nt,Xx as o,fc as ot,Sx as p,Ys as pt,Jv as q,Zx as r,vl as rt,Jx as s,ic as st,nS as t,Tl as tt,Hx as u,qs as ut,rx as v,ms as vt,Ab as w,Kb as x,Po as xt,ix as y,ps as yt,Gy as z};
|