demoman 0.8.1 → 0.9.0
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/THIRD_PARTY_NOTICES +2 -1
- package/dist/demoman.mjs +24069 -16815
- package/dist/page/decode-probe-entry.js +44 -0
- package/dist/page/executor-entry.js +102 -17
- package/dist/page/mux-entry.js +184 -59
- package/dist/page/render-entry.js +941 -635
- package/dist/recipe.md +221 -255
- package/dist/skills/record-demo/SKILL.md +5 -4
- package/dist/studio/assets/editor-DNMFFNBB.js +4 -0
- package/dist/studio/assets/{editor-inline-7e387eed.css → editor-inline-07bcb316.css} +13 -0
- package/dist/studio/assets/library-Doev8wa8.js +1 -0
- package/dist/studio/assets/library-inline-1ca82571.css +1430 -0
- package/dist/studio/assets/settings-BRA8xkpS.js +1 -0
- package/dist/studio/assets/{settings-inline-7bb8bf61.css → settings-inline-2f59fbb0.css} +4 -0
- package/dist/studio/assets/state-B_PivD_k.js +2 -0
- package/dist/studio/assets/toast-Dg-G_N89.css +1 -0
- package/dist/studio/assets/toast-vpo2H1vK.js +72 -0
- package/dist/studio/assets/topbar-DW2VlQMA.js +1 -0
- package/dist/studio/assets/view-Oa5Fj9vk.js +1 -0
- package/dist/studio/editor.html +11 -10
- package/dist/studio/library.html +9 -8
- package/dist/studio/settings.html +8 -7
- package/dist/studio/studio-build.json +3 -3
- package/package.json +2 -1
- package/dist/studio/assets/confirm-dialog-B20ZVWlP.css +0 -1
- package/dist/studio/assets/confirm-dialog-DgJ946Hc.js +0 -72
- package/dist/studio/assets/editor-BC4sLdWT.js +0 -4
- package/dist/studio/assets/library-DVubUJtn.js +0 -1
- package/dist/studio/assets/library-inline-ff1b0c15.css +0 -635
- package/dist/studio/assets/settings-DLH9VoT0.js +0 -1
- package/dist/studio/assets/state-DyL2jOOv.js +0 -1
- package/dist/studio/assets/topbar-sSUyITjl.js +0 -1
- package/dist/studio/assets/view-Df6XUnyO.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=/^[^A-Z]*$/,vt=/^[^a-z]*$/,yt=u(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),bt={number:`number`,bigint:`bigint`,object:`date`},xt=u(`$ZodCheckLessThan`,(e,t)=>{yt.init(e,t);let n=bt[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})}}),St=u(`$ZodCheckGreaterThan`,(e,t)=>{yt.init(e,t);let n=bt[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})}}),Ct=u(`$ZodCheckMultipleOf`,(e,t)=>{yt.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})}}),wt=u(`$ZodCheckNumberFormat`,(e,t)=>{yt.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})}}),Tt=u(`$ZodCheckMaxLength`,(e,t)=>{var n;yt.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})}}),Et=u(`$ZodCheckMinLength`,(e,t)=>{var n;yt.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})}}),Dt=u(`$ZodCheckLengthEquals`,(e,t)=>{var n;yt.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})}}),Ot=u(`$ZodCheckStringFormat`,(e,t)=>{var n,r;yt.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=()=>{})}),kt=u(`$ZodCheckRegex`,(e,t)=>{Ot.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})}}),At=u(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=_t,Ot.init(e,t)}),jt=u(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=vt,Ot.init(e,t)}),Mt=u(`$ZodCheckIncludes`,(e,t)=>{yt.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})}}),Nt=u(`$ZodCheckStartsWith`,(e,t)=>{yt.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})}}),Pt=u(`$ZodCheckEndsWith`,(e,t)=>{yt.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})}}),Ft=u(`$ZodCheckOverwrite`,(e,t)=>{yt.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),It=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
|
-
`))}},Lt={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=Lt;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}))}),Rt=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)=>{Ot.init(e,t),Rt.init(e,t)}),zt=u(`$ZodGUID`,(e,t)=>{t.pattern??=Ye,A.init(e,t)}),Bt=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)}),Vt=u(`$ZodEmail`,(e,t)=>{t.pattern??=Ze,A.init(e,t)}),Ht=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})}}}),Ut=u(`$ZodEmoji`,(e,t)=>{t.pattern??=$e(),A.init(e,t)}),Wt=u(`$ZodNanoID`,(e,t)=>{t.pattern??=qe,A.init(e,t)}),Gt=u(`$ZodCUID`,(e,t)=>{t.pattern??=He,A.init(e,t)}),Kt=u(`$ZodCUID2`,(e,t)=>{t.pattern??=Ue,A.init(e,t)}),qt=u(`$ZodULID`,(e,t)=>{t.pattern??=We,A.init(e,t)}),Jt=u(`$ZodXID`,(e,t)=>{t.pattern??=Ge,A.init(e,t)}),Yt=u(`$ZodKSUID`,(e,t)=>{t.pattern??=Ke,A.init(e,t)}),Xt=u(`$ZodISODateTime`,(e,t)=>{t.pattern??=ft(t),A.init(e,t)}),Zt=u(`$ZodISODate`,(e,t)=>{t.pattern??=lt,A.init(e,t)}),Qt=u(`$ZodISOTime`,(e,t)=>{t.pattern??=dt(t),A.init(e,t)}),$t=u(`$ZodISODuration`,(e,t)=>{t.pattern??=Je,A.init(e,t)}),en=u(`$ZodIPv4`,(e,t)=>{t.pattern??=et,A.init(e,t),e._zod.bag.format=`ipv4`}),tn=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})}}}),nn=u(`$ZodCIDRv4`,(e,t)=>{t.pattern??=nt,A.init(e,t)}),rn=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 an(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var on=u(`$ZodBase64`,(e,t)=>{t.pattern??=it,A.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{an(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function sn(e){if(!at.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return an(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var cn=u(`$ZodBase64URL`,(e,t)=>{t.pattern??=at,A.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{sn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),ln=u(`$ZodE164`,(e,t)=>{t.pattern??=st,A.init(e,t)});function un(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 dn=u(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{un(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),fn=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}}),pn=u(`$ZodNumberFormat`,(e,t)=>{wt.init(e,t),fn.init(e,t)}),mn=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}}),hn=u(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),gn=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 _n(e,t,n){e.issues.length&&t.issues.push(...ve(n,e.issues)),t.value[n]=e.value}var vn=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=>_n(t,n,e))):_n(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function yn(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 bn(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 xn(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=>yn(e,n,i,t,u,d))):yn(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 Sn=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=_(()=>bn(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=>yn(n,t,e,s,r,i))):yn(a,t,e,s,r,i)}return i?xn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Cn=u(`$ZodObjectJIT`,(e,t)=>{Sn.init(e,t);let n=e._zod.parse,r=_(()=>bn(t)),i=e=>{let t=new It([`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?xn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function wn(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 Tn=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=>wn(t,r,e,i)):wn(o,r,e,i)}}),En=u(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Tn.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)}}),Dn=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])=>kn(e,t,n)):kn(e,i,a)}});function On(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=On(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=On(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 kn(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=On(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var An=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}}),jn=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}}),Mn=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 Nn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Pn=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=>Nn(e,r)):Nn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Fn=u(`$ZodExactOptional`,(e,t)=>{Pn.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)}),In=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)}),Ln=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=>Rn(e,t)):Rn(r,t)}});function Rn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var zn=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))}),Bn=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=>Vn(t,e)):Vn(i,e)}});function Vn(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 Hn=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)}}),Un=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=>Wn(e,t.in,n)):Wn(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Wn(e,t.out,n)):Wn(r,t.out,n)}});function Wn(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 Gn=u(`$ZodPreprocess`,(e,t)=>{Un.init(e,t)}),Kn=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(qn):qn(r)}});function qn(e){return e.value=Object.freeze(e.value),e}var Jn=u(`$ZodCustom`,(e,t)=>{yt.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=>Yn(t,n,r,e));Yn(i,n,r,e)}});function Yn(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 Xn,Zn=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 Qn(){return new Zn}(Xn=globalThis).__zod_globalRegistry??(Xn.__zod_globalRegistry=Qn());var $n=globalThis.__zod_globalRegistry;function er(e,t){return new e({type:`string`,...O(t)})}function tr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...O(t)})}function nr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...O(t)})}function rr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...O(t)})}function ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...O(t)})}function ar(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...O(t)})}function or(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...O(t)})}function sr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...O(t)})}function cr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...O(t)})}function lr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...O(t)})}function ur(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...O(t)})}function dr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...O(t)})}function fr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...O(t)})}function pr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...O(t)})}function mr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...O(t)})}function hr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...O(t)})}function gr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...O(t)})}function _r(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...O(t)})}function vr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...O(t)})}function yr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...O(t)})}function br(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...O(t)})}function xr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...O(t)})}function Sr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...O(t)})}function Cr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...O(t)})}function wr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...O(t)})}function Tr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...O(t)})}function Er(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...O(t)})}function Dr(e,t){return new e({type:`number`,checks:[],...O(t)})}function Or(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...O(t)})}function kr(e,t){return new e({type:`boolean`,...O(t)})}function Ar(e){return new e({type:`unknown`})}function jr(e,t){return new e({type:`never`,...O(t)})}function Mr(e,t){return new xt({check:`less_than`,...O(t),value:e,inclusive:!1})}function Nr(e,t){return new xt({check:`less_than`,...O(t),value:e,inclusive:!0})}function Pr(e,t){return new St({check:`greater_than`,...O(t),value:e,inclusive:!1})}function Fr(e,t){return new St({check:`greater_than`,...O(t),value:e,inclusive:!0})}function Ir(e,t){return new Ct({check:`multiple_of`,...O(t),value:e})}function Lr(e,t){return new Tt({check:`max_length`,...O(t),maximum:e})}function Rr(e,t){return new Et({check:`min_length`,...O(t),minimum:e})}function zr(e,t){return new Dt({check:`length_equals`,...O(t),length:e})}function Br(e,t){return new kt({check:`string_format`,format:`regex`,...O(t),pattern:e})}function Vr(e){return new At({check:`string_format`,format:`lowercase`,...O(e)})}function Hr(e){return new jt({check:`string_format`,format:`uppercase`,...O(e)})}function Ur(e,t){return new Mt({check:`string_format`,format:`includes`,...O(t),includes:e})}function Wr(e,t){return new Nt({check:`string_format`,format:`starts_with`,...O(t),prefix:e})}function Gr(e,t){return new Pt({check:`string_format`,format:`ends_with`,...O(t),suffix:e})}function Kr(e){return new Ft({check:`overwrite`,tx:e})}function qr(e){return Kr(t=>t.normalize(e))}function Jr(){return Kr(e=>e.trim())}function Yr(){return Kr(e=>e.toLowerCase())}function Xr(){return Kr(e=>e.toUpperCase())}function Zr(){return Kr(e=>ee(e))}function Qr(e,t,n){return new e({type:`array`,element:t,...O(n)})}function $r(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...O(n)})}function ei(e,t){let n=ti(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 ti(e,t){let n=new yt({check:`custom`,...O(t)});return n._zod.check=e,n}function ni(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??$n,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 ri(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,ri(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`&&oi(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 ii(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 ai(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:ci(t,`input`,e.processors),output:ci(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function oi(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 oi(r.element,n);if(r.type===`set`)return oi(r.valueType,n);if(r.type===`lazy`)return oi(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 oi(r.innerType,n);if(r.type===`intersection`)return oi(r.left,n)||oi(r.right,n);if(r.type===`record`||r.type===`map`)return oi(r.keyType,n)||oi(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:oi(r.in,n)||oi(r.out,n);if(r.type===`object`){for(let e in r.shape)if(oi(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(oi(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(oi(e,n))return!0;return!!(r.rest&&oi(r.rest,n))}return!1}var si=(e,t={})=>n=>{let r=ni({...n,processors:t});return ri(e,r),ii(r,e),ai(r,e)},ci=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ni({...i??{},target:a,io:t,processors:n});return ri(e,o),ii(o,e),ai(o,e)},li={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ui=(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=li[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}))])}},di=(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)},fi=(e,t,n,r)=>{n.type=`boolean`},pi=(e,t,n,r)=>{n.not={}},mi=(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},hi=(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}},gi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},_i=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},vi=(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=ri(a.element,t,{...r,path:[...r.path,`items`]})},yi=(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]=ri(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=ri(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},bi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>ri(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},xi=(e,t,n,r)=>{let i=e._zod.def,a=ri(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=ri(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]]},Si=(e,t,n,r)=>{let i=e._zod.def,a=ri(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`}]},Ci=(e,t,n,r)=>{let i=e._zod.def;ri(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},wi=(e,t,n,r)=>{let i=e._zod.def;ri(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ti=(e,t,n,r)=>{let i=e._zod.def;ri(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)))},Ei=(e,t,n,r)=>{let i=e._zod.def;ri(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},Di=(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;ri(o,t,r);let s=t.seen.get(e);s.ref=o},Oi=(e,t,n,r)=>{let i=e._zod.def;ri(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ki=(e,t,n,r)=>{let i=e._zod.def;ri(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ai=u(`ZodISODateTime`,(e,t)=>{Xt.init(e,t),N.init(e,t)});function ji(e){return Cr(Ai,e)}var Mi=u(`ZodISODate`,(e,t)=>{Zt.init(e,t),N.init(e,t)});function Ni(e){return wr(Mi,e)}var Pi=u(`ZodISOTime`,(e,t)=>{Qt.init(e,t),N.init(e,t)});function Fi(e){return Tr(Pi,e)}var Ii=u(`ZodISODuration`,(e,t)=>{$t.init(e,t),N.init(e,t)});function Li(e){return Er(Ii,e)}var Ri=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}),zi=Oe(Ri),Bi=ke(Ri),Vi=Ae(Ri),Hi=Me(Ri),Ui=Pe(Ri),Wi=Fe(Ri),Gi=Ie(Ri),Ki=Le(Ri),qi=Re(Ri),Ji=ze(Ri),Yi=Be(Ri),Xi=Ve(Ri),Zi=new WeakMap;function Qi(e,t,n){let r=Object.getPrototypeOf(e),i=Zi.get(r);if(i||(i=new Set,Zi.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:ci(e,`input`),output:ci(e,`output`)}}),e.toJSONSchema=si(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>zi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Vi(e,t,n),e.parseAsync=async(t,n)=>Bi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Hi(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ui(e,t,n),e.decode=(t,n)=>Wi(e,t,n),e.encodeAsync=async(t,n)=>Gi(e,t,n),e.decodeAsync=async(t,n)=>Ki(e,t,n),e.safeEncode=(t,n)=>qi(e,t,n),e.safeDecode=(t,n)=>Ji(e,t,n),e.safeEncodeAsync=async(t,n)=>Yi(e,t,n),e.safeDecodeAsync=async(t,n)=>Xi(e,t,n),Qi(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(co(e,t))},superRefine(e,t){return this.check(lo(e,t))},overwrite(e){return this.check(Kr(e))},optional(){return Ua(this)},exactOptional(){return Ga(this)},nullable(){return qa(this)},nullish(){return Ua(qa(this))},nonoptional(e){return $a(this,e)},array(){return F(this)},or(e){return Na([this,e])},and(e){return La(this,e)},transform(e){return ro(this,Va(e))},default(e){return Ya(this,e)},prefault(e){return Za(this,e)},catch(e){return to(this,e)},pipe(e){return ro(this,e)},readonly(){return oo(this)},describe(e){let t=this.clone();return $n.add(t,{description:e}),t},meta(...e){if(e.length===0)return $n.get(this);let t=this.clone();return $n.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 $n.get(e)?.description},configurable:!0}),e)),$i=u(`_ZodString`,(e,t)=>{Rt.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ui(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Qi(e,`_ZodString`,{regex(...e){return this.check(Br(...e))},includes(...e){return this.check(Ur(...e))},startsWith(...e){return this.check(Wr(...e))},endsWith(...e){return this.check(Gr(...e))},min(...e){return this.check(Rr(...e))},max(...e){return this.check(Lr(...e))},length(...e){return this.check(zr(...e))},nonempty(...e){return this.check(Rr(1,...e))},lowercase(e){return this.check(Vr(e))},uppercase(e){return this.check(Hr(e))},trim(){return this.check(Jr())},normalize(...e){return this.check(qr(...e))},toLowerCase(){return this.check(Yr())},toUpperCase(){return this.check(Xr())},slugify(){return this.check(Zr())}})}),ea=u(`ZodString`,(e,t)=>{Rt.init(e,t),$i.init(e,t),e.email=t=>e.check(tr(ta,t)),e.url=t=>e.check(sr(ia,t)),e.jwt=t=>e.check(Sr(ba,t)),e.emoji=t=>e.check(cr(oa,t)),e.guid=t=>e.check(nr(na,t)),e.uuid=t=>e.check(rr(ra,t)),e.uuidv4=t=>e.check(ir(ra,t)),e.uuidv6=t=>e.check(ar(ra,t)),e.uuidv7=t=>e.check(or(ra,t)),e.nanoid=t=>e.check(lr(sa,t)),e.guid=t=>e.check(nr(na,t)),e.cuid=t=>e.check(ur(ca,t)),e.cuid2=t=>e.check(dr(la,t)),e.ulid=t=>e.check(fr(ua,t)),e.base64=t=>e.check(yr(_a,t)),e.base64url=t=>e.check(br(va,t)),e.xid=t=>e.check(pr(da,t)),e.ksuid=t=>e.check(mr(fa,t)),e.ipv4=t=>e.check(hr(pa,t)),e.ipv6=t=>e.check(gr(ma,t)),e.cidrv4=t=>e.check(_r(ha,t)),e.cidrv6=t=>e.check(vr(ga,t)),e.e164=t=>e.check(xr(ya,t)),e.datetime=t=>e.check(ji(t)),e.date=t=>e.check(Ni(t)),e.time=t=>e.check(Fi(t)),e.duration=t=>e.check(Li(t))});function M(e){return er(ea,e)}var N=u(`ZodStringFormat`,(e,t)=>{A.init(e,t),$i.init(e,t)}),ta=u(`ZodEmail`,(e,t)=>{Vt.init(e,t),N.init(e,t)}),na=u(`ZodGUID`,(e,t)=>{zt.init(e,t),N.init(e,t)}),ra=u(`ZodUUID`,(e,t)=>{Bt.init(e,t),N.init(e,t)}),ia=u(`ZodURL`,(e,t)=>{Ht.init(e,t),N.init(e,t)});function aa(e){return sr(ia,e)}var oa=u(`ZodEmoji`,(e,t)=>{Ut.init(e,t),N.init(e,t)}),sa=u(`ZodNanoID`,(e,t)=>{Wt.init(e,t),N.init(e,t)}),ca=u(`ZodCUID`,(e,t)=>{Gt.init(e,t),N.init(e,t)}),la=u(`ZodCUID2`,(e,t)=>{Kt.init(e,t),N.init(e,t)}),ua=u(`ZodULID`,(e,t)=>{qt.init(e,t),N.init(e,t)}),da=u(`ZodXID`,(e,t)=>{Jt.init(e,t),N.init(e,t)}),fa=u(`ZodKSUID`,(e,t)=>{Yt.init(e,t),N.init(e,t)}),pa=u(`ZodIPv4`,(e,t)=>{en.init(e,t),N.init(e,t)}),ma=u(`ZodIPv6`,(e,t)=>{tn.init(e,t),N.init(e,t)}),ha=u(`ZodCIDRv4`,(e,t)=>{nn.init(e,t),N.init(e,t)}),ga=u(`ZodCIDRv6`,(e,t)=>{rn.init(e,t),N.init(e,t)}),_a=u(`ZodBase64`,(e,t)=>{on.init(e,t),N.init(e,t)}),va=u(`ZodBase64URL`,(e,t)=>{cn.init(e,t),N.init(e,t)}),ya=u(`ZodE164`,(e,t)=>{ln.init(e,t),N.init(e,t)}),ba=u(`ZodJWT`,(e,t)=>{dn.init(e,t),N.init(e,t)}),xa=u(`ZodNumber`,(e,t)=>{fn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>di(e,t,n,r),Qi(e,`ZodNumber`,{gt(e,t){return this.check(Pr(e,t))},gte(e,t){return this.check(Fr(e,t))},min(e,t){return this.check(Fr(e,t))},lt(e,t){return this.check(Mr(e,t))},lte(e,t){return this.check(Nr(e,t))},max(e,t){return this.check(Nr(e,t))},int(e){return this.check(Ca(e))},safe(e){return this.check(Ca(e))},positive(e){return this.check(Pr(0,e))},nonnegative(e){return this.check(Fr(0,e))},negative(e){return this.check(Mr(0,e))},nonpositive(e){return this.check(Nr(0,e))},multipleOf(e,t){return this.check(Ir(e,t))},step(e,t){return this.check(Ir(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 Dr(xa,e)}var Sa=u(`ZodNumberFormat`,(e,t)=>{pn.init(e,t),xa.init(e,t)});function Ca(e){return Or(Sa,e)}var wa=u(`ZodBoolean`,(e,t)=>{mn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fi(e,t,n,r)});function Ta(e){return kr(wa,e)}var Ea=u(`ZodUnknown`,(e,t)=>{hn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Da(){return Ar(Ea)}var Oa=u(`ZodNever`,(e,t)=>{gn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r)});function ka(e){return jr(Oa,e)}var Aa=u(`ZodArray`,(e,t)=>{vn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r),e.element=t.element,Qi(e,`ZodArray`,{min(e,t){return this.check(Rr(e,t))},nonempty(e){return this.check(Rr(1,e))},max(e,t){return this.check(Lr(e,t))},length(e,t){return this.check(zr(e,t))},unwrap(){return this.element}})});function F(e,t){return Qr(Aa,e,t)}var ja=u(`ZodObject`,(e,t)=>{Cn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yi(e,t,n,r),S(e,`shape`,()=>t.shape),Qi(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:Da()})},loose(){return this.clone({...this._zod.def,catchall:Da()})},strict(){return this.clone({...this._zod.def,catchall:ka()})},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(Ha,this,e[0])},required(...e){return he(Qa,this,e[0])}})});function I(e,t){return new ja({type:`object`,shape:e??{},...O(t)})}var Ma=u(`ZodUnion`,(e,t)=>{Tn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bi(e,t,n,r),e.options=t.options});function Na(e,t){return new Ma({type:`union`,options:e,...O(t)})}var Pa=u(`ZodDiscriminatedUnion`,(e,t)=>{Ma.init(e,t),En.init(e,t)});function Fa(e,t,n){return new Pa({type:`union`,options:t,discriminator:e,...O(n)})}var Ia=u(`ZodIntersection`,(e,t)=>{Dn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r)});function La(e,t){return new Ia({type:`intersection`,left:e,right:t})}var Ra=u(`ZodEnum`,(e,t)=>{An.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(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 Ra({...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 Ra({...t,checks:[],...O(r),entries:i})}});function L(e,t){return new Ra({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...O(t)})}var za=u(`ZodLiteral`,(e,t)=>{jn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(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 za({type:`literal`,values:Array.isArray(e)?e:[e],...O(t)})}var Ba=u(`ZodTransform`,(e,t)=>{Mn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(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 Va(e){return new Ba({type:`transform`,transform:e})}var Ha=u(`ZodOptional`,(e,t)=>{Pn.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 Ua(e){return new Ha({type:`optional`,innerType:e})}var Wa=u(`ZodExactOptional`,(e,t)=>{Fn.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 Ga(e){return new Wa({type:`optional`,innerType:e})}var Ka=u(`ZodNullable`,(e,t)=>{In.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Si(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qa(e){return new Ka({type:`nullable`,innerType:e})}var Ja=u(`ZodDefault`,(e,t)=>{Ln.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ya(e,t){return new Ja({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():re(t)}})}var Xa=u(`ZodPrefault`,(e,t)=>{zn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Za(e,t){return new Xa({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():re(t)}})}var Qa=u(`ZodNonOptional`,(e,t)=>{Bn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ci(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $a(e,t){return new Qa({type:`nonoptional`,innerType:e,...O(t)})}var eo=u(`ZodCatch`,(e,t)=>{Hn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function to(e,t){return new eo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var no=u(`ZodPipe`,(e,t)=>{Un.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Di(e,t,n,r),e.in=t.in,e.out=t.out});function ro(e,t){return new no({type:`pipe`,in:e,out:t})}var io=u(`ZodPreprocess`,(e,t)=>{no.init(e,t),Gn.init(e,t)}),ao=u(`ZodReadonly`,(e,t)=>{Kn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function oo(e){return new ao({type:`readonly`,innerType:e})}var so=u(`ZodCustom`,(e,t)=>{Jn.init(e,t),j.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r)});function co(e,t={}){return $r(so,e,t)}function lo(e,t){return ei(e,t)}function uo(e,t){return new io({type:`pipe`,in:Va(e),out:t})}var fo={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`},po;po||={},m({jitless:!0});var mo={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`}},ho=I({x:P(),y:P(),width:P().nonnegative(),height:P().nonnegative()}),go=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)}),_o=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)}),vo=I({sourceTimeMs:P().nonnegative(),x:P(),y:P()}),yo=I({startMs:P().nonnegative(),endMs:P().nonnegative()}),bo=I({actionId:M().min(1),anchorId:M().min(1),rect:ho,end:ho.optional()}),xo=I({actionId:M().min(1),pressMs:P().nonnegative(),releaseMs:P().nonnegative()}),So=I({sourceTimeMs:P().nonnegative(),scale:P().positive(),offsetX:P(),offsetY:P()}),Co=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:fo.custom,path:[`actEndSourceTimeMs`],message:`act end ${e.actEndSourceTimeMs}ms is before the step's marker at ${e.sourceTimeMs}ms`})}),wo=I({actionId:M().min(1),kind:M().min(1),anchorId:M().min(1).nullable(),text:M().nullable(),cut:Ta().optional()}),To=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 Eo(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(go),motionSpans:F(_o),cursorSamples:F(vo),cursorGaps:F(yo).default([]),anchorRects:F(bo),heldPresses:F(xo).optional(),viewportTransforms:F(So).optional(),markers:F(Co),degradations:F(To),madeFrom:F(wo).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`]}),Eo(e.keyframes.map(e=>e.sourceTimeMs),`keyframes`,t,[`keyframes`]),Eo(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(mo,t)&&!mo[t].cursorTravels})||t.addIssue({code:`custom`,message:`a replay bundle must carry the cursor samples it dispatched`,path:[`cursorSamples`]})}});function Do(e){return e.source===`capture`||e.timing===`real`}function Oo(e,t,n){return(e.pacedGaps??[]).some(e=>e.afterActionId===t&&(n===void 0||e.durationMs===n))}var ko=.02;function Ao(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)<=ko}function jo(e,t,n){return e.some(e=>e.startMs<n&&e.endMs>t)}function Mo(e,t){let n=e.motionSpans.find(e=>t>=e.startMs&&t<=e.endMs);if(!n||!Ao(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 No(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 Po(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function Fo(e,t,n){return e+(t-e)*n}function Io(e,t,n){return{x:Fo(e.x,t.x,n),y:Fo(e.y,t.y,n)}}function z(e,t,n){return Math.min(n,Math.max(t,e))}function Lo(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 Ro(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}var zo={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 Bo(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 Io(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 Vo(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 Ho=/^#?([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;function Uo(e){return e.length<=4?e.split(``).map(e=>e+e).join(``):e}var Wo=e=>e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055;function Go(e){return`#${e.map(e=>Math.round(Math.min(1,Math.max(0,e))*255).toString(16).padStart(2,`0`)).join(``)}`}function Ko({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 qo=e=>e.every(e=>e>=-1e-6&&e<=1+1e-6);function Jo(e,t=`chroma`){let n=Ko(e),r=!qo(n);if(r&&t===`chroma`){let t=0,r=e.c;for(let n=0;n<24;n++){let n=(t+r)/2;qo(Ko({...e,c:n}))?t=n:r=n}n=Ko({...e,c:t})}return{hex:Go(n.map(e=>Wo(Math.min(1,Math.max(0,e))))),clipped:r}}var Yo={ok:!1,reason:`Backgrounds are opaque — drop the alpha`};function Xo(e,t){let n=/^(-?\d*\.?\d+)%$/.exec(e);return n?Number(n[1])/100*t:/^-?\d*\.?\d+$/.test(e)?Number(e):null}function Zo(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 Qo(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 $o(e){let t=e.trim(),n={ok:!1,reason:`"${t}" is not a colour`},r=Ho.exec(t);if(r){let e=Uo(r[1]).toLowerCase();return e.length===8?e.slice(6)===`ff`?{ok:!0,hex:`#${e.slice(0,6)}`,note:null}:Yo:{ok:!0,hex:`#${e}`,note:null}}let i=Zo(t);if(!i)return n;if(i.alpha!==null){let e=Xo(i.alpha,1);if(e===null)return n;if(e!==1)return Yo}if(i.name===`rgb`||i.name===`rgba`){let e=i.parts.map(e=>Xo(e,255));return e.some(e=>e===null)?n:{ok:!0,hex:Go(e.map(e=>e/255)),note:null}}if(i.name===`hsl`||i.name===`hsla`){let e=Xo(i.parts[0].replace(/deg$/,``),360),t=e=>e.endsWith(`%`)?Xo(e,1):(e=>e===null?null:e/100)(Xo(e,1)),r=t(i.parts[1]),a=t(i.parts[2]);return e===null||r===null||a===null?n:{ok:!0,hex:Go(Qo((e%360+360)%360,r,a)),note:null}}if(i.name===`oklch`){let e=Xo(i.parts[0],1),t=Xo(i.parts[1],.4),r=Xo(i.parts[2].replace(/deg$/,``),360);if(e===null||t===null||r===null)return n;let a=Jo({l:e,c:t,h:r});return{ok:!0,hex:a.hex,note:a.clipped?`Nearest sRGB is ${a.hex}`:null}}return n}var es=L([`phone`,`tablet`]),ts={iphone:`phone`,android:`phone`,ipad:`tablet`},ns=uo(e=>typeof e==`string`&&e in ts?ts[e]:e,es),rs=I({brands:F(I({brand:M(),version:M()})).optional(),platform:M(),platformVersion:M(),architecture:M(),model:M(),mobile:Ta()}),is=I({preset:ns,width:P().int().positive(),height:P().int().positive(),mobile:Ta(),touch:Ta(),userAgent:M().min(1),userAgentMetadata:rs.optional()}),as=[{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`}}],os=`muted-1`;function ss(e){return as.find(t=>t.id===e)??null}function cs(e,t){return`${e}-${t}.webp`}var ls=I({x:P(),y:P(),width:P().nonnegative(),height:P().nonnegative()}),us=I({stableId:M().min(1).nullable(),role:M().min(1).nullable(),accessibleName:M().nullable(),textContent:M().nullable(),treePath:M().min(1).nullable(),boundingRect:ls.nullable(),imagePatchRef:M().min(1).nullable(),dataKey:M().min(1).nullable()}),ds=L([`stableId`,`roleName`,`text`,`treePath`,`imagePatch`,`ambiguous`,`broken`]),fs=L([`notInTree`,`closedShadowRoot`,`frameGone`,`frameUnreachable`,`patchUnavailable`,`ambiguousTie`]),ps=I({url:M(),actionIndex:P().int().nonnegative(),entryState:Ta(),strategy:ds,failureReason:fs.nullable(),candidates:P().int().nonnegative()}),ms=I({id:M().min(1),fingerprint:us,resolution:ps}).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`]})}),hs={id:M().min(1),anchorId:M().min(1),timestamp:P().nonnegative(),marker:M().min(1),rect:ls.optional()},gs=I({...hs,kind:R(`moveTo`),signal:L([`mutation`,`style`]).optional()}),_s=I({...hs,kind:R(`click`),button:L([`left`,`middle`,`right`]).optional(),textLines:F(ls).max(200).optional()}),vs=I({...hs,kind:R(`type`),text:M().nullable(),redacted:Ta(),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`]})}),ys=I({...hs,kind:R(`scrollTo`)}),bs=I({...hs,anchorId:M().min(1).nullable(),kind:R(`waitFor`),condition:L([`visible`,`hidden`,`loaded`]).optional()}),xs=I({x:P().min(0).max(1),y:P().min(0).max(1)}),Ss=Fa(`kind`,[gs,_s,vs,ys,bs,I({...hs,kind:R(`drag`),toAnchorId:M().min(1).nullable(),toRect:ls.optional(),fromAt:xs.optional(),pressedAt:xs.optional(),to:Na([I({at:xs.optional()}).strict(),I({by:I({x:P(),y:P()})}).strict()])})]),Cs=I({actionId:M().min(1),offsetMs:P()}),ws=I({actionId:M().min(1),sourceOffsetMs:P()}),Ts=I({x:P(),y:P()}),Es=I({id:M().min(1),kind:L([`zoom`,`pan`]),anchorId:M().min(1).optional(),point:Ts.optional(),marker:Cs,end:Cs.optional(),scale:P().positive().optional(),note:M().optional()}),Ds=Na([I({actionId:M().min(1),reason:L([`tooClose`,`sameTarget`]),afterActionId:M().min(1),gapMs:P()}),I({actionId:M().min(1),reason:L([`targetTooWide`,`textTooWide`]),scale:P().nonnegative()})]);function Os(e){let t=[[`actionId`,e.actionId]];return`afterActionId`in e&&t.push([`afterActionId`,e.afterActionId]),t}var ks=I({id:M().min(1),rect:ls,note:M().optional(),start:ws.optional(),end:ws.optional()}),As=I({id:M().min(1),marker:I({actionId:M().min(1),offsetMs:P()}),durationMs:P().positive()}),js=I({id:M().min(1),afterActionId:M().min(1),durationMs:P().nonnegative()}),Ms=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:Ta()}),Ns=I({level:L([`log`,`info`,`warn`,`error`,`debug`]),text:M(),timestamp:P().nonnegative()}),Ps=I({url:M(),timestamp:P().nonnegative()}),Fs=I({id:M().min(1),name:M(),createdAt:ji(),toolchain:I({resolverVersion:M().min(1),compositorVersion:M().min(1).nullable(),captureVersion:M().min(1).nullable()}),capture:I({originUrl:aa(),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:is.optional(),displayScale:P().positive().optional()}),renderMode:L([`screen`,`demo`]).optional()}),Is=L([`light`,`dark`,`touch`]),Ls=I({hidden:Ta(),style:Is,scale:P().min(.5).max(2),motionBlur:P().min(0).max(1),hideWhenIdle:Ta(),tilt:P().min(0).max(1).optional(),clickBounce:P().min(0).max(2).optional()}),Rs=Object.freeze({hidden:!1,style:`light`,scale:1,motionBlur:1,hideWhenIdle:!1}),zs=Object.freeze({tilt:.5,clickBounce:1}),Bs=I({smoothness:P().min(0).max(1),blur:P().min(0).max(1),follow:Ta()}),Vs=Object.freeze({smoothness:.5,blur:.5,follow:!0}),Hs=I({aspect:L([`auto`,`16:9`,`9:16`])}),Us=Object.freeze({aspect:`auto`}),Ws=M().regex(/^#[0-9a-f]{6}$/),Gs=P().min(0).max(1).optional(),Ks=Fa(`kind`,[I({kind:R(`solid`),color:Ws}),I({kind:R(`gradient`),from:Ws,to:Ws,angle:P().int().min(0).max(359)}),I({kind:R(`wallpaper`),id:M().regex(/^[a-z0-9-]+$/),blur:Gs}),I({kind:R(`image`),ref:M().min(1),blur:Gs})]),qs=[`top-left`,`top-right`,`bottom-left`,`bottom-right`],Js=I({background:Ks,logo:I({ref:M().min(1),corner:L(qs),size:P().min(.02).max(.2),opacity:P().min(.2).max(1)}).nullable(),padding:P().min(0).max(.2)}),Ys=Object.freeze({kind:`gradient`,from:Jo({l:.95,c:.005,h:260},`clip`).hex,to:Jo({l:.86,c:.008,h:260},`clip`).hex,angle:150}),Xs=Object.freeze({background:Object.freeze({kind:`wallpaper`,id:os,blur:0}),logo:null,padding:.12}),Zs=Object.freeze({corner:`bottom-right`,size:.06,opacity:.9}),Qs=I({schemaVersion:R(13),meta:Fs,anchors:F(ms),actions:F(Ss),camera:F(Es),zoomsSkipped:F(Ds).optional(),edits:I({masks:F(ks),holds:F(As),gaps:F(js).default([]),splits:F(I({id:M().min(1),at:ws})).default([]),removed:F(I({id:M().min(1),start:ws.nullable(),end:ws.nullable()})).default([]),trim:I({head:Cs.optional(),tail:Cs.optional()}).optional()}),sideChannels:I({network:F(Ms),consoleExcerpt:F(Ns),urlTrace:F(Ps),uncoveredOrigins:F(M())}),flags:I({mutating:Ta(),hoverSensitive:Ta()}),branding:Js,cursor:Ls,canvas:Hs,motion:Bs.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 Os(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 $s(e,t){return t===void 0?{x:e.x+e.width/2,y:e.y+e.height/2}:{x:e.x+t.x*e.width,y:e.y+t.y*e.height}}function ec(e,t,n){return`by`in t?{x:e.x+t.by.x,y:e.y+t.by.y}:n==null?null:$s(n,t.at)}function tc(e,t,n){if(t===void 0)return null;let r=$s(t,e.pressedAt??e.fromAt),i=ec(r,e.to,n);return i===null?null:{start:r,end:i}}function nc(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 rc=/^[a-z0-9][a-z0-9_-]{0,63}$/,ic=`lower-case letters, digits, "-" and "_", starting with a letter or digit, at most 64 characters`,ac=Na([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()]),oc=M().min(1).optional(),sc=I({on:ac,at:I({x:P().min(0).max(1),y:P().min(0).max(1)}).strict().optional()}).strict(),cc=Na([sc,I({by:I({x:P().finite(),y:P().finite()}).strict()}).strict()]),lc=Fa(`do`,[I({do:R(`click`),on:ac,recorded:oc}).strict(),I({do:R(`type`),into:ac,text:M(),recorded:oc}).strict(),I({do:R(`hover`),on:ac,recorded:oc}).strict(),I({do:R(`scrollTo`),on:ac,recorded:oc,landing:I({top:P().finite()}).strict().optional()}).strict(),I({do:R(`waitFor`),on:ac,until:L([`visible`,`hidden`]),recorded:oc}).strict(),I({do:R(`drag`),from:sc,to:cc,recorded:oc}).strict(),I({do:R(`waitForLoad`),recorded:oc}).strict(),I({do:R(`pause`),ms:P().positive()}).strict()]),uc={click:!0,type:!0,hover:!0,scrollTo:!0,waitFor:!0,drag:!0,waitForLoad:!0,pause:!1},dc=Js.extend({padding:Js.shape.padding.default(Xs.padding)});I({scriptVersion:R([1,2,3,4,5,6]),name:M().min(1),target:aa(),viewport:I({width:P().int().positive(),height:P().int().positive()}).optional(),device:es.optional(),account:M().regex(rc,{message:`an account name is ${ic}`}).optional(),steps:F(lc).min(1),recordedFrom:M().min(1).optional(),look:I({branding:dc.optional(),kit:M().trim().min(1).optional(),cursor:Ls.optional(),canvas:Hs.optional(),motion:Bs.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)=>{e.look?.kit!==void 0&&e.scriptVersion<2&&t.addIssue({code:`custom`,message:`a script that names look.kit declares scriptVersion 2: a build from before brand kits would drop the kit and record the default look`,path:[`scriptVersion`]});let n=e.look?.branding?.background;n?.kind===`wallpaper`&&!as.some(e=>e.id===n.id)&&t.addIssue({code:`custom`,message:`unknown wallpaper "${n.id}" — one of ${as.map(e=>e.id).join(`, `)}`,path:[`look`,`branding`,`background`,`id`]}),e.look?.motion!==void 0&&e.scriptVersion<3&&t.addIssue({code:`custom`,message:`a script that names look.motion declares scriptVersion 3: a build from before camera motion settings would drop them and record the default camera`,path:[`scriptVersion`]}),fc(e.look?.cursor)&&e.scriptVersion<3&&t.addIssue({code:`custom`,message:`a script that names look.cursor.tilt or look.cursor.clickBounce declares scriptVersion 3: a build from before them would drop them and draw the default lean and press`,path:[`scriptVersion`]}),e.device!==void 0&&e.scriptVersion<4&&t.addIssue({code:`custom`,message:`a script that names device declares scriptVersion 4: a build from before devices would drop it and record the desktop`,path:[`scriptVersion`]}),e.account!==void 0&&e.scriptVersion<5&&t.addIssue({code:`custom`,message:`a script that names account declares scriptVersion 5: a build from before accounts would drop it and record as whoever is signed in`,path:[`scriptVersion`]}),e.steps.forEach((n,r)=>{n.do===`drag`&&(e.scriptVersion<6&&t.addIssue({code:`custom`,message:`a script that uses drag declares scriptVersion 6: a build from before drag would refuse the step`,path:[`scriptVersion`]}),(`by`in n.to?n.to.by.x===0&&n.to.by.y===0:JSON.stringify(n.to.on)===JSON.stringify(n.from.on)&&(n.to.at?.x??.5)===(n.from.at?.x??.5)&&(n.to.at?.y??.5)===(n.from.at?.y??.5))&&t.addIssue({code:`custom`,message:`step ${r+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`,r,`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.steps.some(e=>uc[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`]})});function fc(e){return e?.tilt!==void 0||e?.clickBounce!==void 0}function pc(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 mc(e){return e.kind===`keyframeOnly`||e.kind===`surfaceMismatch`||e.kind===`encodeRefused`||e.kind===`motionReclaimed`}function hc(e,t=[]){return pc([...e.motionSpans.map(e=>({startMs:e.startMs,endMs:e.endMs})),...e.degradations.filter(mc).map(e=>({startMs:e.startMs,endMs:e.endMs})),...t])}function gc(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 _c(e,t){return e.some(e=>t>e.srcStartMs&&t<=e.srcEndMs)}function vc(e,t){return e.some(e=>t>e.srcStartMs&&t<e.srcEndMs)}var yc=1e-6;function bc(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 vc(r,a)?[]:[{sourceTimeMs:a,durationMs:Math.max(0,e.durationMs)}]}).sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}function xc(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 Sc(e,t){return e.origin===`authored`?e.idleTargetMs:Math.max(0,e.recordedSpanMs-t)}function Cc(e,t,n,r){if(e.paces===null||Do(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(_c(r,s))continue;let c=xc(n,e,s),l=Math.max(0,s-e-c),u=Math.max(0,Sc(t,c)-l);u>0&&a.push({sourceTimeMs:s,durationMs:u})}return{instants:a.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs),unplacedPaces:o}}function wc(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||_c(i,(a+l)/2))continue;let d=s(a,l)?`motion`:`idle`,f=d===`motion`?u:Dc(e,t,n,i,a,l,u);c.push({srcStartMs:a,srcEndMs:l,kind:d,outDurationMs:f})}return c}function Tc(e,t,n,r){if(!Do(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`||Oo(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 Ec(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=pc([...t,...n.map(e=>({startMs:e.srcStartMs,endMs:e.srcEndMs}))]);return Math.max(0,o-a-xc(s,a,o))}function Dc(e,t,n,r,i,a,o){let s=Tc(e,t,i,a);if(!s)return o;let c=Ec(t,n,r,s);return c<=0?o:s.idleTargetMs*(o/c)}function Oc(e,t){let n=e.findIndex(e=>e.srcStartMs+yc<t&&t<e.srcEndMs-yc);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 kc(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 pc(n)}function Ac(e,t,n=[]){let r=hc(t,n),i=t.keyframes[t.keyframes.length-1],a=Math.max(i?.sourceTimeMs??0,...t.markers.map(e=>e.sourceTimeMs),...r.map(e=>e.endMs)),{cuts:o,unplacedCuts:s}=gc(e,t,a),c=kc(t,o),l=[...o,...c.map(e=>({ids:[],srcStartMs:e.startMs,srcEndMs:e.endMs,trailing:!1}))].sort((e,t)=>e.srcStartMs-t.srcStartMs),u=bc(e,t,a,o),{instants:d,unplacedPaces:f}=Cc(e,t,r,o),p=(e.paces??[]).filter(e=>e.origin===`recorded`&&e.recordedSpanMs<0).length,m=wc(e,t,r,a,l);for(let e of u)m=Oc(m,e.sourceTimeMs);for(let e of d)m=Oc(m,e.sourceTimeMs);let h=[],g=0,_=e=>{for(let t of u)Math.abs(t.sourceTimeMs-e)>yc||(h.push({outStartMs:g,outEndMs:g+t.durationMs,srcStartMs:e,srcEndMs:e,kind:`hold`}),g+=t.durationMs)},v=e=>{for(let t of d)Math.abs(t.sourceTimeMs-e)>yc||(h.push({outStartMs:g,outEndMs:g+t.durationMs,srcStartMs:e,srcEndMs:e,kind:`pace`}),g+=t.durationMs)},y=e=>o.some(t=>Math.abs(t.srcStartMs-e)<=yc);for(let e of m)_(e.srcStartMs),v(e.srcStartMs),h.push({outStartMs:g,outEndMs:g+e.outDurationMs,srcStartMs:e.srcStartMs,srcEndMs:e.srcEndMs,kind:e.kind}),g+=e.outDurationMs,y(e.srcEndMs)&&(_(e.srcEndMs),v(e.srcEndMs));return _(a),v(a),{segments:h,outputDurationMs:g,sourceDurationMs:a,cuts:o,unplacedCuts:s,interruptions:c,unplacedPaces:f,nonMonotonicPaces:p}}function jc(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 Mc(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 Nc(e,t,n){let r=n.get(e.actionId);return r===void 0?null:Mc(t,r)+e.offsetMs}function Pc(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 Fc(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=Pc(t,i,a);if(o!==null&&o.endMs>o.startMs)return{range:o,unplaced:n,clamped:null};let s=o?.startMs??z(Mc(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 Ic(e){let{timeline:t}=e,n=t.outputDurationMs,r=[],i=e.start?Nc(e.start,t,e.markerSourceMs):0,a=e.end?Nc(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 Lc(e){if(!(Number.isFinite(e)&&e>=0&&e<=1))throw RangeError(`motion smoothness must be within 0..1, got ${e}`);return{stiffness:Fo(8,5.5,e),zoomInMs:Fo(1e3,1600,e),zoomOutMs:Fo(700,1150,e),followRatePerS:Fo(13,7,e)}}var Rc=Lc(Vs.smoothness),zc={defaultZoomScale:1.8,verticalMaxScale:1.15,fitMarginPx:24,leadInMs:-350,actSettleMs:400,zoomInMs:Rc.zoomInMs,zoomOutMs:Rc.zoomOutMs,stiffness:Rc.stiffness,maxScale:2.5,neutral:{minPlateauMs:250,zoomHoldMs:1200}};function Bc(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=tc(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,zc.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 Vc(e,t,n,r,i,a=null,o=Vs,s=new Map,c=[]){let l=Lc(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=Mc(n,o),u=Math.max(0,c+i.offsetMs),p=i.end?Nc(i.end,n,r):null,m=z(i.scale,1,zc.maxScale),h=Math.max(m,z(i.requestedScale??i.scale,1,zc.maxScale)),g=a===null?m:z(Hc(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(_,Mc(n,t)))}let v={id:i.id,outputTimeMs:u,center:Po(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&&!Wc(Uc(n,t.actionMs,c),t.outputTimeMs,l),i=(f.get(t)??-1/0)+(r?0:zc.actSettleMs);t.outputTimeMs-l.zoomInMs<i&&(t.transitionMs=Math.max(150,Math.min(l.zoomInMs,t.outputTimeMs-i)))}return Gc([{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 Hc(e,t){let n=2*zc.fitMarginPx,r=Math.min(t.width/(e.width+n),t.height/(e.height+n));return Math.floor(r*100)/100}function Uc(e,t,n){let r=Math.min(e.outputTimeMs+zc.neutral.zoomHoldMs,t);return Math.max(e.outputTimeMs,...n.filter(t=>t.startMs>=e.actionMs&&t.startMs<r).map(e=>e.endMs))}function Wc(e,t,n){let{minPlateauMs:r}=zc.neutral;return t-n.zoomInMs-r>=e+r+n.zoomOutMs}function Gc(e,t,n,r=[]){let{neutral:i}=zc,{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[n,u]of e.entries()){let d=o[o.length-1]?.outputTimeMs??u.outputTimeMs,f=Math.max(d,u.outputTimeMs-u.transitionMs);if(o.push(c(u)),!u.zoom)continue;let p=e[n+1],m=Uc(u,p?.actionMs??1/0,r),h=m+i.minPlateauMs+a,g=m+i.zoomHoldMs+a,_=u.authoredEndMs??g,v=u.authoredEndMs!==null,y=v||u.endUnplaced,b=e=>v&&Math.abs(e-_)>1e-6;if(!p){let e=Math.min(Math.max(_,h),t);if(e<=u.outputTimeMs){s.push({id:u.id,departMs:f,startMs:u.outputTimeMs,endMs:t,endAuthored:y,endClamped:b(t),endUnplaced:u.endUnplaced,fitted:u.fitted});continue}o.push(l(e,u.center)),s.push({id:u.id,departMs:f,startMs:u.outputTimeMs,endMs:e,endAuthored:y,endClamped:b(e),endUnplaced:u.endUnplaced,fitted:u.fitted});continue}let x=p.outputTimeMs-p.plannedTransitionMs-i.minPlateauMs;if(!Wc(m,p.outputTimeMs,{zoomInMs:p.plannedTransitionMs,zoomOutMs:a})){let t=Math.max(u.outputTimeMs,u.actionMs,m)+i.minPlateauMs;e[n+1]={...p,transitionMs:Math.max(150,Math.min(p.transitionMs,p.outputTimeMs-t))},s.push({id:u.id,departMs:f,startMs:u.outputTimeMs,endMs:p.outputTimeMs,endAuthored:y,endClamped:b(p.outputTimeMs),endUnplaced:u.endUnplaced,fitted:u.fitted});continue}let S=Math.min(Math.max(_,h),x);o.push(l(S,Io(u.center,p.center,.5))),s.push({id:u.id,departMs:f,startMs:u.outputTimeMs,endMs:S,endAuthored:y,endClamped:b(S),endUnplaced:u.endUnplaced,fitted:u.fitted})}return{keys:o,segments:s}}function Kc(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 qc(e,t,n,r,i){let{scale:a}=e,o=Kc(e.center,t,n,r),s=Po(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 Jc(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:Io(e.center,t.center,a),scale:r}}function Yc(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 Jc(i,r,Vo(z(o<=0?1:(t-(r.outputTimeMs-o))/o,0,1),r.stiffness))}return{center:r.center,scale:r.scale}}function Xc(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 Zc(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:Xc(t,l),f=t.slice(e+1,c+1).map((n,r)=>({at:Xc(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 Qc(e,t,n=e=>e){let r=e.cameraKeys.map(e=>({...e,center:n(e.center,e.scale)})),i=Yc(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:Io(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=Yc(r,a.pullOutDepartMs).scale;if(f<=1)return i;let p=Yc(r,a.endMs).center,m=(1/f-1/i.scale)/(1/f-1);return{center:Io(n(d,f),p,m),scale:i.scale}}function $c(e,t,n,r,i,a){return qc(Qc(e,t,(e,t)=>qc({center:e,scale:t},n,r,i,a).center),n,r,i,a)}var el={minDurationMs:480,maxDurationMs:1400,baseMs:360,msPerPx:.7,dwellMs:300,hoverDwellMs:450,bowFraction:.08};function tl(e,t){let n=Ro(e,t);return Math.round(z(el.baseMs+el.msPerPx*n,el.minDurationMs,el.maxDurationMs))}function nl(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*el.bowFraction*o;return{x:e.x+r/2-i/a*s,y:e.y+i/2+r/a*s}}function rl(e,t){return Bo(e.via,z(t,0,1))}function il(e,t){return{x:z(e.x-t.width*.25,0,t.width),y:z(e.y+t.height*.3,0,t.height)}}function al(e){let{from:t,to:n}=e;return{fromActionId:e.fromActionId,toActionId:e.toActionId,from:t,to:n,via:[t,nl(t,n,e.index),n],durationMs:tl(t,n),easing:`minimumJerk`,dwellMs:e.dwellMs??el.dwellMs}}function ol(e,t){let n=e.actions.flatMap(e=>{if(e.anchorId===null||!mo[e.kind].cursorTravels)return[];let n=t(e.anchorId,e.id);return n?[{action:e,point:Po(n)}]:[]});if(n.length===0)return[];let r=e.flags.hoverSensitive?el.hoverDwellMs:el.dwellMs,i=n[0],a=il(i.point,e.meta.capture.viewport),o=null;return n.map((e,t)=>{let n=e.point,i=al({from:a,to:n,index:t,fromActionId:o,toActionId:e.action.id,dwellMs:r});return a=n,o=e.action.id,i})}var sl=3;function cl(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 ll(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||jo(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 ul(e,t,n=[],r=[]){if(t<=0||e.length<3)return e;let i=cl(e,n),a=ll(e,50,r),o=sl*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&&!jo(r,n,_.sourceTimeMs)?_.sourceTimeMs-n:0,s=g<e.length-1&&!jo(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 dl(e){return 2*e}function fl(e){return 6*e}function pl(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 ml(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 hl=8;function gl(e,t,n,r=[]){if(t<=0||e.length<2)return e;if(r.length===0)return _l(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||jo(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:_l(l,t,n.filter(e=>e>=u.sourceTimeMs&&e<=d.sourceTimeMs))),a=o}return i}function _l(e,t,n){let r=1/t,i=fl(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=dl(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+hl;i<r.sourceTimeMs;i+=hl)(i<e||i>=t)&&p.push(i)}p.push(r.sourceTimeMs)}let m=ml(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+hl;e<=g.sourceTimeMs+i;e+=hl)d(e-h,g.x,g.y,e),h=e;return vl(o,e,n,i)}function vl(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=pl(t,n),d=pl(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 yl(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 bl(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 Sl(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 Cl(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 wl=.4;function Tl(e,t,n,r,i){let a=t-e,o=+!!n+ +!!r;if(o===0||a<=0)return i;let s=Math.min(wl*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 El(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=yl(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=>bl(e,t,n,c,r)),f=Sl(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,Cl(u,d,f,s<=h?Tl(p,h,i.in,h===m&&i.out,s):s>=g?Tl(g,m,!1,i.out,s):s));a[r]={sourceTimeMs:o.sourceTimeMs,x:l.x,y:l.y}}}function Dl(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&&jo(r,u.sourceTimeMs,l.sourceTimeMs);(l===void 0||d||l.sourceTimeMs-u.sourceTimeMs>n)&&(El(e,s,i-1,t,{in:!c&&a(e[s]),out:!d&&a(u)},o),s=i,c=d)}return o}var Ol=48,kl=.05,Al=.5,jl=.25;function Ml(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>=kl){let i={x:t.x/r,y:t.y/r},a=24+r*50;if(Nl(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 Nl(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 Pl(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<=Ol;)i--;return{at:r,velocity:Fl(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<=Ol;)a++;return{at:i,velocity:Fl(i,e[a])}}function Fl(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 Il(e,t,n,r){let i=Math.max(n,Al);return{speed:i,ms:(Nl(e,t,r)+jl*Math.max(r.width,r.height))/i}}function Ll(e,t,n,r){return{x:e.x+t.x*n*r,y:e.y+t.y*n*r}}var Rl=8;function zl(e,t,n,r){let i=[],a=r-t;for(let o=t+Rl;o<r;o+=Rl)i.push({sourceTimeMs:o,...Io(e,n,(o-t)/a)});return i}function Bl(e,t,n){if(e.length===0)return{samples:e,gaps:t};let r=[],i=[];for(let a of t){let t=Pl(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?Ml(t.at,s,n):null;if(!t||!c){i.push(a);continue}let l=t.at,u=Il(l,c,Vl(s),n),d=t.at.sourceTimeMs;o&&(d=Math.max(d,a.startMs-Nl(l,c,n)/u.speed),r.push({sourceTimeMs:d,x:l.x,y:l.y}));let f=Pl(e,a.endMs,`after`),p=f?Ml(f.at,Hl(f.velocity),n):null,m=f&&p?Il(f.at,p,Vl(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=Ll(l,c,u.speed,n);r.push(...zl(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(...zl(a,d+n,f.at,e));continue}let s=m.ms*t,h=e-s,g=Ll(f.at,p,m.speed,s);r.push({sourceTimeMs:h,x:g.x,y:g.y}),r.push(...zl(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=Ll(l,c,u.speed,h);r.push(...zl(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?Pl(e,a.sourceTimeMs,`after`):null,s=o?Ml(o.at,Hl(o.velocity),n):null;if(o&&s){let e=Il(a,s,Vl(o.velocity),n),t=Ll(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(...zl(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 Vl=e=>Math.hypot(e.x,e.y),Hl=e=>({x:-e.x,y:-e.y}),Ul=`1.1.0`;function Wl(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 Gl={motionDiffThreshold:.02};function Kl(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=nc(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:Ul,sceneId:e.meta.id,viewport:e.meta.capture.viewport,cursorSegments:ol(e,i),cameraIntents:Bc(e,s,c),cosmetics:Wl(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:{...Gl,...t.retiming},hoverSensitive:e.flags.hoverSensitive,durationHintMs:a?.timestamp??0}}function ql(e,t){let n=e[0]??null;for(let r of e){if(r.sourceTimeMs>t)break;n=r}return n}var Jl=(e,t)=>({x:(e.x-t.offsetX)*t.scale,y:(e.y-t.offsetY)*t.scale}),Yl=(e,t)=>({...e,...Jl(e,t),width:e.width*t.scale,height:e.height*t.scale}),Xl=e=>e.scale===1&&e.offsetX===0&&e.offsetY===0;function Zl(e,t){let n=e.viewportTransforms??[];if(n.every(Xl))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=>ql(n,e),a=e=>i((e===void 0?void 0:r.get(e))??0),o={...e,viewportTransforms:[],cursorSamples:e.cursorSamples.map(e=>({...e,...Jl(e,i(e.sourceTimeMs))})),anchorRects:e.anchorRects.map(e=>({...e,rect:Yl(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:Yl(e.rect,a(e.id))}:e),anchors:t.anchors.map(e=>{let t=e.fingerprint.boundingRect;return t?{...e,fingerprint:{...e.fingerprint,boundingRect:Yl(t,a(s.get(e.id)))}}:e})}}}function Ql(e,t,n){return t.every(Xl)?[...e]:e.map(e=>{let r=ql(t,n.get(e.toActionId)??0);return{...e,from:Jl(e.from,r),to:Jl(e.to,r),via:e.via.map(e=>Jl(e,r))}})}function $l(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 Io({x:o.x,y:o.y},{x:s.x,y:s.y},l)}var eu=.01;function tu(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=$l(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-eu),x:t.x,y:t.y});return a.sort((e,t)=>e.sourceTimeMs-t.sourceTimeMs)}function nu(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 ru=120;function iu(e,t){let n=[],r=e.hoverSensitive?zo.easeInOutSine:zo.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*ru));for(let e=0;e<=c;e++){let t=e/c,a=rl(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 au=.5;function ou(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)<au||t.push({startMs:r.sourceTimeMs,endMs:i.sourceTimeMs})}return t}var su=1e3;function cu(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=$l(e,i.srcStartMs);if(a===null)continue;let o=jc(t,Mc(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=$l(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 lu(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)>=au)){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=Mc(t,e.startMs),r=Mc(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 uu(e){let t=e-su;return t<=0?1:Math.max(0,1-t/250)}function du(e,t){for(let n of e){if(t>=n.startMs&&t<n.endMs)return uu(t-n.startMs);let e=t-n.endMs;if(e>=0&&e<250){let t=uu(n.endMs-n.startMs);return t+(1-t)*(e/250)}}return 1}function fu(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 Zc({keys:t,cursorAt:o.follow&&e.drawsPointer?e=>$l(a,jc(i,e)):null,holds:(r.heldPresses??[]).filter(e=>s.has(e.actionId)).map(e=>({startMs:Mc(i,e.pressMs),endMs:Mc(i,e.releaseMs)})),outputDurationMs:i.outputDurationMs,rate:Lc(o.smoothness).followRatePerS})}function mu(e,t,n,r=[],i=null){let a=e,{bundle:o,scene:s}=Zl(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`?Bl(o.cursorSamples,o.cursorGaps,a.viewport):{samples:o.cursorSamples,gaps:o.cursorGaps},p=o.source===`capture`?ul(nu(f.samples,50,f.gaps),30,o.markers.map(e=>e.sourceTimeMs),f.gaps):f.samples,m=f.samples.length>0?tu(p,f.gaps):iu({...a,cursorSegments:Ql(a.cursorSegments,t.viewportTransforms??[],d)},d),h=o.markers.map(e=>e.sourceTimeMs),g=o.source===`capture`&&f.samples.length>0?tu(gl(Dl(p,h,50,f.gaps,a.viewport),55,h,f.gaps),f.gaps):m,_=o.source===`capture`?fl(55):0,v=o.source===`capture`?dl(55):0,y=[...r,...ou(m).map(e=>({startMs:Math.max(0,e.startMs-v),endMs:e.endMs+_}))],b=Ac(a,o,y),x=new Set(b.unplacedCuts.flatMap(e=>e.ids));if(x.size>0&&n!==void 0){let e=Kl({...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=Ac(a,o,y)}let S=cu(g,b,250),C=Ic({id:`trim`,kind:`trim`,start:a.trim.head,end:a.trim.tail,timeline:b,markerSourceMs:d}),w=C.clamped?[C.clamped]:[],T=s?.motion??Vs,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:Mc(b,e.pressMs),endMs:Mc(b,e.releaseMs)})),ne=Vc(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 ${fu(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 ${fu(t)}x, and was narrowed to ${fu(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`]:[`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=>Mc(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=$l(S,e.sourceTimeMs);return t===null?[]:[{outputMs:Mc(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??Rs).hidden}),le=a.cosmetics.map(e=>{let t=null,n=[];if(e.range){let r=Fc({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??Rs,motion:T,cursorRestOutputMs:lu(S,b,oe),cosmetics:le,range:C.range,trimUnplaced:C.unplaced.map(e=>e===`start`?`head`:`tail`),clampedRanges:w,loweredZooms:re}}var hu=Object.freeze({press:1,angleRad:0}),gu=[{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}],_u=.42,vu={light:{height:40,hotspot:{x:0,y:0},ink:yu(gu)},dark:{height:40,hotspot:{x:0,y:0},ink:yu(gu)},touch:{height:40,hotspot:{x:.5,y:.5},ink:{min:{x:.08000000000000002,y:.08000000000000002},max:{x:.9199999999999999,y:.9199999999999999}}}};function yu(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 bu={light:{fill:`#ffffff`,stroke:`#111827`},dark:{fill:`#111827`,stroke:`#ffffff`},touch:{fill:`rgba(255, 255, 255, 0.45)`,stroke:`#111827`}};function xu(e,t,n,r,i=`light`){let a=vu[i].height*n*r.press,o=bu[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*_u,0,Math.PI*2);else{let t=gu[0];if(t){e.moveTo(t.x*a,t.y*a);for(let t of gu.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 Su=.55;function Cu(e){return e<=0?0:Math.ceil(2+8*z(e,0,1))}function wu(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*Su,xu(e,a,n,{press:1,angleRad:a.angleRad??0},r)}),e.globalAlpha=i}function Tu(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(),Eu(e,t,a-l,c,`rgba(15, 23, 42, ${.75*o})`),Eu(e,t,a+l,c,`rgba(15, 23, 42, ${.75*o})`),Eu(e,t,a,s,`rgba(255, 255, 255, ${.95*o})`),e.restore()}function Eu(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 Du=.14,Ou=80,ku=320,Au=e=>{let t=z(e,0,1);return t*t*(3-2*t)};function ju(e,t,n,r=[]){let i=Du*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/Ou)*Math.cos(2*Math.PI*t/ku):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)*Au(r)}}return s(e)}var Mu=15*Math.PI/180,Nu=16,Pu=1.1,Fu=.65,Iu=8,Lu=20,Ru=60;function zu(e,t,n){let r=z(n,0,1),i=e.cursor[0],a=t-Nu;if(r<=0||!i||a<0)return 0;let o=jc(e.timeline,a);if(o<i.sourceTimeMs)return 0;let s=$l(e.cursor,o),c=$l(e.cursor,jc(e.timeline,t));if(!s||!c)return 0;let l=(c.x-s.x)*1e3/Nu,u=(c.y-s.y)*1e3/Nu,d=Math.hypot(l,u);if(d<.001)return 0;let f=z((l+Fu*u)/d,-1,1),p=e.plan.viewport.width,m=Pu*(p>0?p:1);return f*Math.min(1,d/m)*Mu*r}function Bu(e,t,n){if(!(n>0))return 0;let r=0,i=0;for(let a=0;a<Iu;a++){let o=Math.exp(-a*Lu/Ru);r+=o*zu(e,t-a*Lu,n),i+=o}return r/i}function Vu(e,t){let n=No(e,t);if(!n)throw Error(`frame bundle has no keyframes; cannot resolve a frame`);return n}function Hu(e,t,n){let r=No(e,t);return e.keyframes.filter(e=>e===r||e.sourceTimeMs>t&&e.sourceTimeMs<=n)}function Uu(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=Vu(e,t);return{...await r(n.ref),sourceTimeMs:n.sourceTimeMs}},warm(t,n){for(let i of Hu(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 Wu=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Gu=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)},Ku=e=>{let t=V(e);return t&1?t+1>>1:-(t>>1)},qu=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),Ju=new TextDecoder,Yu=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),Xu={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Zu=Yu(Xu),Qu={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},$u=Yu(Qu),ed={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},td=Yu(ed),nd=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),rd=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}},id=/^[0-9a-fA-F]+$/,ad=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),od=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},sd=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),cd=(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},ld=(e,t,n)=>{let r=U(e,n(t),n);e.splice(r+1,0,t)},ud=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},dd=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},fd=(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},md=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},hd=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},gd=e=>{throw Error(`Unexpected value: ${e}`)},_d=(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},vd=(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))},yd=(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}}),bd=(e,t,n)=>Math.max(t,Math.min(n,e)),xd=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},Sd=(e,t)=>Math.round(e/t)*t,Cd=(e,t)=>Math.round(e*t)/t,wd=(e,t)=>Math.floor(e/t)*t,Td=e=>{let t=0;for(;e;)t++,e>>=1;return t},Ed=e=>{let t=0;for(;e!==0;)e&=e-1,t++;return t},Dd=/^[a-z]{3}$/,Od=e=>Dd.test(e),kd=1e6*(1+2**-52),Ad=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},jd=null,Md=()=>jd===null?jd=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):jd,Nd=null,Pd=()=>Nd===null?Nd=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):Nd,Fd=null,Id=()=>Fd===null?Fd=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):Fd,Ld=null,Rd=()=>{if(Ld!==null)return Ld;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Ld=Number(e[1]):null},zd=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.`,Bd=(e,t)=>e===-1?t:e,Vd=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},Hd=(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},Ud=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Wd=e=>typeof e==`number`&&!Number.isNaN(e),Gd=(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(`/`)},Kd=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},qd=(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},Jd=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}},Yd=(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.`)},Xd=e=>new Promise(t=>setTimeout(t,e)),Zd=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)}}},Qd;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(Qd||={});var W=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==Qd.Silent&&t!==Qd.Errors&&t!==Qd.Warnings&&t!==Qd.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 Zd}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=Qd.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=Qd.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=Qd.Info&&console.info(...t)}};W._level=Qd.Info,W._emitterInstance=null;var $d=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.`)}},ef=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.`)}},tf={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}},nf=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],rf=[-1,1,2,3,4,5,6,8],af=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<nf.length&&(i=nf[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=rf[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},of=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],sf=[`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`],cf=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,`dts`,...sf],lf=[{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}],uf=[{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}],df=`.01.01.01.01.00`,ff=`.0.110.01.01.01.0`,pf=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],mf=[`dtsc`,`dtsh`,`dtsl`,`dtse`],hf=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}.${ad(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}.${ad(n.subarray(1,4))}`}if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=sd(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=sd(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=Gu(uf).level;for(let e of uf)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(df)&&(u=u.slice(0,-15)),u}if(t===`av1`){if(!s){let t=e.width*e.height,n=Gu(uf).level;for(let e of uf)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?Xu[r.primaries]:1,u=r?.transfer?Qu[r.transfer]:1,d=r?.matrix?ed[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(ff)&&(p=p.slice(0,-17)),p}if(t===`prores`)return c??`apch`;throw t!==null&&gd(t),TypeError(`Unhandled codec '${t}'.`)},gf=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?af(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&&sf.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},_f=48e3,vf=/^pcm-([usf])(\d+)(be)?$/,yf=e=>{if(B(sf.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=vf.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}},bf=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`:mf.includes(e)?`dts`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:vf.test(e)?e:e===`webvtt`?`webvtt`:null;[...pf];var xf=[44100,48e3,32e3],Sf=[-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],Cf=(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,wf=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,Tf=(e,t)=>e===3?t===3?21:36:t===3?13:21,Ef=(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=Sf[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=xf[d]>>o+s,x=Cf(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}},Df=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},Of;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(Of||={});var kf=e=>e===3?1:2,Af=[48e3,44100,32e3],jf=[24e3,22050,16e3],Mf;(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`})(Mf||={});var Nf;(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`})(Nf||={});var Pf=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})},Ff=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=_d(r,n,!1):(B(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},If=(e,t)=>t.description?Ff(e,(qu(t.description)[4]&3)+1):Pf(e),Lf=e=>e&31,Rf=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)},zf=new Uint8Array([0,0,0,1]),Bf=e=>{let t=e.reduce((e,t)=>e+zf.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(zf,r),r+=zf.byteLength,n.set(t,r),r+=t.byteLength;return n},Vf=(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:vd(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},Hf=(e,t)=>t.description?Vf(e,(qu(t.description)[4]&3)+1):Bf(e),Uf=e=>{try{let t=[],n=[],r=[];for(let i of Pf(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Lf(a[0]);o===Mf.SPS?t.push(a):o===Mf.PPS?n.push(a):o===Mf.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Kf(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}},Wf=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}},Gf={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}},Kf=e=>{try{let t=new G(Rf(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=Ku(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),Ku(t),Ku(t);let e=V(t);for(let n=0;n<e;n++)Ku(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=Gf[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&&qf(t);let n=t.readBits(1);n&&qf(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=lf.find(e=>e.level>=i)??Gu(lf),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}},qf=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)},Jf=(e,t)=>t.description?Vf(e,(qu(t.description)[21]&3)+1):Bf(e),Yf=(e,t)=>t.description?Ff(e,(qu(t.description)[21]&3)+1):Pf(e),Xf=e=>e>>1&63,Zf=e=>{try{let t=new G(Rf(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}=$f(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)&&ep(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),V(t),V(t),t.skipBits(1)),tp(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=rp(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}},Qf=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Pf(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Xf(o[0]);s===Nf.VPS_NUT?t.push(o):s===Nf.SPS_NUT?n.push(o):s===Nf.PPS_NUT?r.push(o):(s===Nf.PREFIX_SEI_NUT||s===Nf.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Zf(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new G(Rf(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),Ku(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&V(t),Ku(t),Ku(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:Nf.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Nf.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Nf.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Xf(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}},$f=(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}},ep=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&&Ku(e);for(let t=0;t<n;t++)Ku(e)}},tp=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=np(e,r,t,n)},np=(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},rp=(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=Gf[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)&&ip(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}},ip=(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&&ap(e,s,a),i&&ap(e,s,a)}},ap=(e,t,n)=>{for(let r=0;r<t;r++)V(e),V(e),n&&(V(e),V(e)),e.readBits(1)},op;(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`})(op||={});var sp=(e,t)=>{let n=new Set,r=op.audAllowed;for(let i of Yf(e,t)){if(r===op.noMoreDataAllowed){n.add(i.offset);continue}let t=Xf(e[i.offset]);if(r===op.eoBitstreamAllowed&&t!==37){n.add(i.offset);continue}let a=!1;t===35?r>op.audAllowed?a=!0:r=op.beforeFirstVcl:t<=31?r>op.afterFirstVcl?a=!0:r=op.afterFirstVcl:t===36?r===op.afterFirstVcl?r=op.eoBitstreamAllowed:a=!0:t===37?r<op.afterFirstVcl?a=!0:r=op.noMoreDataAllowed:t===32||t===33||t===34||t===39||t>=41&&t<=44||t>=48&&t<=55?r>op.beforeFirstVcl?a=!0:r=op.beforeFirstVcl:(t===38||t===40||t>=45&&t<=47||t>=56&&t<=63)&&r<op.afterFirstVcl&&(a=!0),a&&n.add(i.offset)}if(n.size===0)return null;let i=[];for(let r of Yf(e,t))n.has(r.offset)||i.push(e.subarray(r.offset,r.offset+r.length));return Jf(i,t)},cp=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=Gu(uf).level;for(let e of uf)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}},lp=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)}},up=e=>{for(let{type:t,data:n}of lp(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},dp=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}},fp=[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:fp[t]*r}},mp=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}},hp=(e,t,n)=>{switch(e){case`avc`:for(let e of If(n,t)){let t=n[e.offset],r=Lf(t);if(r>=Mf.NON_IDR_SLICE&&r<=Mf.SLICE_DPC)return`delta`;if(r===Mf.IDR)return`key`;if(r===Mf.SEI&&(!Id()||Rd()>=144)){let t=Rf(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 Yf(n,t)){let t=Xf(n[e.offset]);if(t<Nf.BLA_W_LP)return`delta`;if(t<=Nf.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 lp(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:gd(e),B(!1)}},gp;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(gp||={});var _p=(e,t)=>{let n=H(e),r=0,i=n.getUint32(r,!0);r+=4;let a=Ju.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=Ju.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=Vd(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=Ju.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})}}}},vp=[2,1,2,3,3,4,4,5],yp=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)}},bp=[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],xp=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Sp=[1,2,3,6],Cp=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=Sp[o],d;return d=i<3?Af[i]/1e3:jf[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}]}},wp=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}},Tp=e=>{let t=e.substreams[0];return B(t),t.fscod<3?Af[t.fscod]:t.fscod2!==null&&t.fscod2<3?jf[t.fscod2]:null},Ep=e=>{let t=e.substreams[0];B(t);let n=vp[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},Dp=4096,Op=8,kp=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Ap=[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],jp=[16,16,20,20,0,24,24,0],Mp=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Np=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Pp=8,Fp=44646,Ip=[32e3,44100,48e3,0],Lp=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Rp=[512,1024,2048,4096],zp=e=>{let t=Vp(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=Hp(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}},Bp=e=>{let t=zp(e);return t?.core?t.hasExtensions?`dtsh`:`dtsc`:null},Vp=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%Op!==0)return null;let i=t.readBits(14)+1;if(i<96)return null;let a=t.readBits(6);if(a>=Mp.length)return null;let o=kp[t.readBits(4)];if(o===0)return null;let s=Ap[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=jp[t.readBits(3)];if(l===0)return null;let u=c!==0;return{frameSize:i,sampleRate:o,numberOfChannels:Mp[a]+ +!!u,sampleCount:r*32,channelLayout:Np[a]|(u?Pp:0),amode:a,lfePresent:u,bitRate:s,pcmResolution:l}},Hp=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=Ip[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*Ed(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=Lp[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}}},Up=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<Mp.length&&(c=Mp[o]+a):c=Wp(s),{sampleRate:n,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:Rp[i],channelLayout:s,numberOfChannels:c}},Wp=e=>Ed(e)+Ed(e&Fp),Gp=class{constructor(e){this.input=e}dispose(){}},Kp=new Uint8Array,qp=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===Kp&&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===Kp}get microsecondTimestamp(){return Math.trunc(kd*this.timestamp)}get microsecondDuration(){return Math.trunc(kd*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)}},Jp=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},Yp=e=>{let t=H(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=ad(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(ad(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)}},Xp=(e,t)=>e.systemId===t.systemId&&Hd(e.data,t.data),Zp=e=>{let t=Q(e),n=$(e,4),r=8;t===1&&(t=uv(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},Qp=e=>sv(e)/65536,$p=e=>sv(e)/1073741824,em=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},tm=e=>{let t=Z(e);return e.skip(2),t=Math.min(t,e.remainingLength),Ju.decode(Y(e,t))},nm=e=>{let t=Zp(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 Ju.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new $d(r,`image/jpeg`);case 14:return new $d(r,`image/png`);case 27:return new $d(r,`image/bmp`);default:return r}},rm=new Uint32Array(256),im=new Uint32Array(256),am=new Uint32Array(256),om=new Uint32Array(256),sm=new Uint32Array(256),cm=new Uint32Array(256),lm=new Uint32Array(10),um=!1,dm=()=>{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);rm[t]=n<<24|n<<16|n<<8|n,cm[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;im[t]=l,am[t]=l>>>8|l<<24,om[t]=l>>>16|l<<16,sm[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)lm[e]=i<<24,i=i<<1^(i&128?283:0);um=!0},fm=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),um||dm();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]^rm[t>>>16&255]&4278190080^rm[t>>>8&255]&16711680^rm[t>>>0&255]&65280^rm[t>>>24&255]&255^lm[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]=im[rm[n>>>24&255]&255]^am[rm[n>>>16&255]&255]^om[rm[n>>>8&255]&255]^sm[rm[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=im[e>>>24]^am[r>>>16&255]^om[n>>>8&255]^sm[t&255]^this.roundkey[a],l=im[t>>>24]^am[e>>>16&255]^om[r>>>8&255]^sm[n&255]^this.roundkey[a+1],u=im[n>>>24]^am[t>>>16&255]^om[e>>>8&255]^sm[r&255]^this.roundkey[a+2],d=im[r>>>24]^am[n>>>16&255]^om[t>>>8&255]^sm[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=cm[e>>>24&255]&4278190080^cm[r>>>16&255]&16711680^cm[n>>>8&255]&65280^cm[t>>>0&255]&255^this.roundkey[40],p=cm[t>>>24&255]&4278190080^cm[e>>>16&255]&16711680^cm[r>>>8&255]&65280^cm[n>>>0&255]&255^this.roundkey[41],m=cm[n>>>24&255]&4278190080^cm[t>>>16&255]&16711680^cm[e>>>8&255]&65280^cm[r>>>0&255]&255^this.roundkey[42],h=cm[r>>>24&255]&4278190080^cm[n>>>16&255]&16711680^cm[t>>>8&255]&65280^cm[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 fm;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()}})},mm=class e extends Gp{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 Jp({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=Zp(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=Zp(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 gm(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new _m(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&&sf.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){B(e.info?.type===`audio`);let n=yf(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=Gu(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=Zp(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)Sm(e,r.timestamp);else{let t=U(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Sm(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 Em(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=Zp(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=Zp(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=uv(e)):(e.skip(8),this.movieTimescale=Q(e),this.movieDurationInTimescale=Q(e))}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...tf,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 gm(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new _m(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=X(e),r=!!(rv(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=uv(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=Wu(Sd(Cm([Qp(e),Qp(e),$p(e),Qp(e),Qp(e),$p(e),Qp(e),Qp(e),$p(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?uv(e):Q(e),o=n===1?dv(e):sv(e),s=Qp(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=uv(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;Od(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=Zp(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=mv(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=_f;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(mf.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=ad(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:Zu[r],transfer:$u[i],matrix:td[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),em(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=em(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=em(e);if(t.info.codecDescription=Y(e,n),t.info.codec===`aac`){let e=af(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=iv(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=rv(e);if((n&127)===gp.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=Af[r]),t.info.numberOfChannels=vp[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`);let r=wp(Y(e,n.contentSize));if(!r){W._warn(`Invalid dec3 box contents, ignoring.`);break}let i=Tp(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=Ep(r)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;B(t.info?.type===`audio`);let r=Up(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=sv(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=uv(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?uv(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,rv,Q],l=c[a],u=c[o],d=c[s],f=Q(e);for(let n=0;n<f;n++){let n=t===1?uv(e):Q(e),i=t===1?uv(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[Gu(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=n.presentationTimestamp+n.duration;let{currentFragmentState:r}=this.currentTrack;B(r),r.startTimestamp!==null&&(Sm(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=Yp(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=rv(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=uv(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):uv(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=rv(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=sv(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):sv(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),rv(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=Tm(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(rv(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(uv(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Tm(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=!!(rv(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]??=tm(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=Ju.decode(Y(n,e.contentSize)):this.metadataTags.title??=tm(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=tm(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=tm(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=tm(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=tm(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=tm(n));break;case`©day`:if(!this.currentTrack){let e=new Date(tm(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=tm(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=tm(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=Ju.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=nm(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 $d?(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}},hm=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 xd(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=vm(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!wm(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=ym(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!wm(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=xm(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=bm(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=Kp;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 Em(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(r=await Dm(this.internalTrack,t[e],r,null))}}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new qp(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=Kp;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 Dm(this.internalTrack,r.encryption,i,e))}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new qp(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=Zp(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}},gm=class extends hm{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&&Uf(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Qf(e.data)}else if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&cp(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&up(e.data)}let e={codec:hf(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}},_m=class extends hm{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&&Bp(e.data)}return{codec:gf(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},vm=(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)}},ym=(e,t)=>{if(!e.keySampleIndices)return vm(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(cd(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=vm(e,t),r=U(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},bm=(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||cd(e.keySampleIndices,t,e=>e)!==-1}},xm=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=U(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Sm=(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},Cm=e=>{let[t,n]=e,r=Math.atan2(n,t);return Number.isFinite(r)?180/Math.PI*r:0},wm=e=>e.sampleSizes.length===0,Tm=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},Em=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},Dm=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++)Xp(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&&id.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:od(n)})();e.demuxer.decryptionKeyCache.set(a,t),o=await t}return i.scheme===`cenc`||i.scheme===`cens`?Om(o,i,t,n):km(o,i,t,n)},Om=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=Am(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},km=(e,t,n,r)=>{let i=new fm;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=Am(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},Am=(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 jm=[K.EBML,K.Segment],Mm=[K.SeekHead,K.Info,K.Cluster,K.Tracks,K.Cues,K.Attachments,K.Chapters,K.Tags],Nm=[...jm,...Mm],Pm=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},Fm=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},Im=(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},Lm=e=>{let t=Pm(e);return t===null||e.remainingLength<t?null:q(e,t)},Rm=e=>{if(e.remainingLength<1)return null;if(X(e)===255)return;e.skip(-1);let t=Fm(e);if(t===null)return null;if(t!==72057594037927940)return t},zm=e=>{B(e.remainingLength>=2);let t=Lm(e);if(t===null)return null;let n=Rm(e);return n===null?null:{id:t,size:n}},Bm=(e,t)=>{let n=Y(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Vm=(e,t)=>{let n=Y(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return Ju.decode(n.subarray(0,r))},Hm=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?pv(e):mv(e)},Um=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=zm(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Km(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},Wm=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=Lm(t);if(e!==null&&a.has(e))return o;o++}}return null},Gm={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 Km(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var qm=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},Jm;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(Jm||={});var Ym;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(Ym||={});var Xm;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(Xm||={});var Zm=[{id:K.SeekHead,flag:`seekHeadSeen`},{id:K.Info,flag:`infoSeen`},{id:K.Tracks,flag:`tracksSeen`},{id:K.Cues,flag:`cuesSeen`}],Qm=10*2**20,$m=class extends Gp{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 qm({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=zm(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===K.EBML){Km(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 Um(this.reader,a,Nm,this.reader.fileSize)).pos-a);let e=Gu(this.segments);e&&(e.elementEndPos=a+i)}Km(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=zm(e);if(!r||!Mm.includes(r.id)&&r.id!==K.Void){let e=await Wm(this.reader,t,Mm,Math.min(this.currentSegment.elementEndPos??1/0,t+Qm));if(e){n=e;continue}break}let{id:i,size:a}=r,o=e.filePos,s=Zm.findIndex(e=>e.id===i);if(s!==-1){let e=Zm[s].flag;this.currentSegment[e]=!0,Km(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,Km(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=Zm.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=zm(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Km(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=zm(n);B(i);let a=i.id;B(a===K.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await Um(this.reader,s,Nm,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,Nm));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!==Jm.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===Jm.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[Gu(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===Jm.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=ev.tempFromBytes(r.data),a=[],o=X(i)+1;switch(r.lacing){case Jm.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 Jm.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case Jm.Ebml:{let e=Fm(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=Fm(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:Jm.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=zm(n);if(!r||r.id!==t.id)continue;let{size:i}=r;Km(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=zm(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch(Km(i),r){case K.DocType:this.isWebM=Bm(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=Hm(e,i);break;case K.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...tf,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!==Ym.Block||e.data.algorithm!==Xm.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===Gm.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Gm.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Gm.vp8)this.currentTrack.info.codec=`vp8`;else if(t===Gm.vp9)this.currentTrack.info.codec=`vp9`;else if(t===Gm.av1)this.currentTrack.info.codec=`av1`;else if(t===Gm.prores){let e=this.currentTrack.codecPrivate?Ju.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 th(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===Gm.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===Gm.mp3?this.currentTrack.info.codec=`mp3`:t===Gm.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=_f):t===Gm.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gm.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gm.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gm.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Gm.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 nh(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=Bm(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=Vm(e,i);break;case K.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Bm(e,i),Od(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case K.LanguageBCP47:{if(!this.currentTrack)break;let t=Bm(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=td[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=$u[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=Zu[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=-Hm(e,i);try{this.currentTrack.info.rotation=Wu(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=Hm(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=Fm(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=iv(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=Fm(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=iv(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=Vm(e,i);break;case K.TagString:{if(!this.currentSimpleTagName)break;let t=Vm(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 ef(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=Im(e,i);break;case K.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Vm(e,i);break;case K.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Bm(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=Vm(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:Ym.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:Xm.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 Xm.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)}}}},eh=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 xd(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?Kp: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?Kp:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new qp(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=zm(e);if(!u||!Mm.includes(u.id)&&u.id!==K.Void){let e=await Wm(a.reader,n,Mm,Math.min(o.elementEndPos??1/0,n+Qm));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 Um(a.reader,p,Nm,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(Lm(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}},th=class extends eh{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:hf({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?Uf(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Qf(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?cp(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?up(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}},nh=class extends eh{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&&Bp(e.data)}return{codec:gf({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}},rh=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=Ef(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&&kf(n.header.channel)===kf(r.channel)))return{header:n.header,startPos:a};o.filePos=t+n.bytesAdvanced,a=o.filePos}}return null},ih=class extends Gp{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 rd,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 ah(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=xv(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await rh(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=Tf(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&Of.FrameCount?e.getUint32(4,!1):null,fileSize:n&Of.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=xv(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;Sv(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`&&yv(e,this.metadataTags)}return this.metadataTags}finally{e()}}},ah=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=wf(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),kf(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return B(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...tf}}async getDecoderConfig(){return B(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:kf(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=Kp;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 qp(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=cd(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)}},oh=79764919,sh=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^oh:t<<1;sh[e]=t>>>0&4294967295}var ch=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^sh[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},lh=(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<<Td(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}},uh=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},dh=65307,fh=e=>{let t=e.filePos;if(ov(e)!==1399285583)return null;e.skip(1);let n=X(e),r=fv(e),i=ov(e),a=ov(e),o=ov(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=ov(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},mh=class extends Gp{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=fh(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 hh(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:mp(i.data).modeBlockflags},_p(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=dp(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=_f,t.codecInfo.opusInfo={preSkip:i.preSkip},_p(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=fh(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=fh(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(),uh({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}},hh=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new rd,this.internalSampleRate=e.codecInfo.codec===`opus`?_f: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{...tf,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}=lh(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new qp(n.metadataOnly?Kp: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=xd(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+dh,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=fh(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=ch(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=fh(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:Kp,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=_h(l,c,u);B(e);let t=gh(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=_h(l,c,u);if(!e)break;let t=gh(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=xd(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(Gu(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)}},gh=(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=fd(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}},_h=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=fd(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},vh;(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`})(vh||={});var yh=class extends Gp{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=av(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=av(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=lv(e,n);s=lv(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 xh(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=nv(r,n),a=nv(r,n),o=av(r,n);r.skip(4);let s=nv(r,n),c;if(c=t===14?8:nv(r,n),t>=18&&i!==357){let e=nv(r,n),a=t-18;if(Math.min(a,e)>=22&&i===vh.EXTENSIBLE){r.skip(6);let e=Y(r,16);i=e[0]|e[1]<<8}}if((i===vh.MULAW||i===vh.ALAW)&&(c=8),i!==vh.PCM&&i!==vh.IEEE_FLOAT&&i!==vh.ALAW&&i!==vh.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===vh.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===vh.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=av(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=xv(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&Sv(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(B(this.audioInfo),this.audioInfo.format===vh.MULAW)return`ulaw`;if(this.audioInfo.format===vh.ALAW)return`alaw`;if(this.audioInfo.format===vh.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===vh.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}},bh=2048,xh=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{...tf}}async getPacketAtIndex(e,t){B(e>=0),B(this.demuxer.audioInfo);let n=e*bh*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(bh*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=Kp;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*bh/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 qp(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/bh,(this.demuxer.dataSize-1)/(bh*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/bh);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Sh=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}},Ch=1024,wh=class extends Gp{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new rd,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 Th(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=xv(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=Sh(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=nf[t.samplingFrequencyIndex];B(n!==void 0);let r=Ch/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=Ch,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=xv(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;Sv(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},Th=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ch}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=rf[this.demuxer.firstFrameHeader.channelConfiguration];return B(e!==void 0),e}getSampleRate(){B(this.demuxer.firstFrameHeader);let e=nf[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return B(e!==void 0),e}getDisposition(){return{...tf}}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=Kp;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 qp(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=cd(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)}},Eh=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,Dh=(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}},Oh=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)},kh=(e,t)=>{if(t===`uncommon-u16`)return Z(e)+1;if(t===`uncommon-u8`)return X(e)+1;if(typeof t==`number`)return t;gd(t),B(!1)},Ah=(e,t)=>t===`uncommon-u16`?Z(e):t===`uncommon-u16-10`?Z(e)*10:t===`uncommon-u8`?X(e):typeof t==`number`?t:null,jh=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},Mh=class extends Gp{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 rd,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=xv(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);r instanceof Promise&&(r=await r),B(r),Sv(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=rv(t),i=!!(n&128);switch(n&127){case gp.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 Nh(this);break}case gp.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),B(t),_p(Y(t,r),this.metadataTags);break}case gp.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),B(t);let n=Q(t),i=Q(t),a=Ju.decode(Y(t,i)),o=Q(t),s=Ju.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=Eh(r.readBits(4));if(!i)return null;B(this.audioInfo);let a=Dh(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=Oh(e),s=kh(e,i),c=Ah(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===jh(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}}},Nh=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{...tf}}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=Kp;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 qp(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)}},Ph=9e4,Fh=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},Ih=`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.`,Lh=5,Rh=1212435798,zh=1212436562,Bh=1146376960,Vh=new Set([133,134,162]),Hh=new Set,Uh=class extends Gp{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===Lh&&n>=4){let t=e.readBits(32);s||=t===Rh||t===zh}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===Lh&&n>=4){let t=e.readBits(32);c||=(t&4294967040)===Bh}e.pos=r}let l=null,u=s&&Vh.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:Hh.has(t)||(W._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Hh.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=Gh(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 Xh(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=Uf(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];B(t);let n=Kf(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:Zu[n.colourPrimaries],transfer:$u[n.transferCharacteristics],matrix:td[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=Qf(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Nf.SPS_NUT).nalUnits[0];B(t);let n=Zf(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:Zu[n.colourPrimaries],transfer:$u[n.transferCharacteristics],matrix:td[n.matrixCoefficients],fullRange:!!n.fullRangeFlag},e.info.reorderSize=n.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:hf({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=Sh(ev.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=rf[t.channelConfiguration],e.info.sampleRate=nf[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=Ef(Q(ev.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=kf(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=yp(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=vp[t.acmod]+t.lfeon,e.info.sampleRate=Af[t.fscod]}else if(e.info.codec===`eac3`){let t=Cp(r.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=Tp(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=Ep(t),e.info.sampleRate=n}else if(e.info.codec===`dts`){let t=zp(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:gf({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 qh(e)):this.trackBackingEntries.push(new Jh(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),Fh(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(cd(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)}}},Wh=(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(Ih);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:a,randomAccessIndicator:e.randomAccessIndicator}},Gh=(e,t)=>{B(e.endPos!==null);let n=Wh(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}},Kh=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{...tf,primary:!1}}getTimeResolution(){return Ph}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 qp(n.metadataOnly?Kp:e.data,r,e.pts/Ph,Math.max(t/Ph,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;B(t);let n=Gh(t,!0);B(n);let r=new Xh(this.elementaryStream,n),i=new Zh(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=Gh(i,!0);B(a);let o=new Xh(this.elementaryStream,a);n=new Zh(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=xd(e*Ph),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=Wh(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=Wh(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=wd(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=wd(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=Gh(a,!0);B(o);let s=new Xh(this.elementaryStream,o),c=new Zh(this,s);for(;!((Gu(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=Wh(t,!1);if(e&&e.pts!==null){if(e.pts>r)break outer;h=e,Yh(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=Wh(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=Gh(m,!0);B(t);let n=new Xh(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=Wh(t,!1);if(e&&e.pts!==null){p=e,m=t,Yh(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=Wh(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(wd(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},qh=class extends Kh{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}},Jh=class extends Kh{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}},Yh=(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},Xh=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=Gu(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=Gh(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=Lf(v),b=y===Mf.NON_IDR_SLICE||y===Mf.SLICE_DPA||y===Mf.IDR,x=y===Mf.SEI||y===Mf.SPS||y===Mf.PPS||y===Mf.AUD;else{if(y=Xf(v),((v&1)<<5|c[g+1]>>3)>0){u+=m;continue}b=y<=Nf.RASL_R||y>=Nf.BLA_W_LP&&y<=21,x=y>=Nf.VPS_NUT&&y<=37||y===Nf.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=Sh(ev.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(Ch*Ph/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=Ef(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*Ph/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=bp[3*o+a];B(s!==void 0),this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=await r);let c=Math.round(xp*Ph/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=Sp[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*Ph/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=Vp(i),o=a?null:Hp(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,Dp),n=this.ensureBuffered(e);n instanceof Promise&&(n=await n),o=Hp(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=Hp(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*Ph/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(Ih);r=n.pts,Yh(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=hp(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}},Zh=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}},Qh=`application/vnd.apple.mpegurl`,$h=`#EXT-X-STREAM-INF:`,eg=`#EXT-X-I-FRAME-STREAM-INF:`,tg=`#EXT-X-MEDIA:`,ng=`#EXTINF:`,rg=`#EXT-X-MAP:`,ig=`#EXT-X-KEY:`,ag=`#EXT-X-MEDIA-SEQUENCE:`,og=`#EXT-X-BYTERANGE:`,sg=`#EXT-X-PROGRAM-DATE-TIME:`,cg=`#EXT-X-TARGETDURATION:`,lg=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`),ug=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)}},dg=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=Kd(e,e=>e.getType()===`video`)+1;e.push(new pg(this,t,n))}else if(t.type===`audio`){let n=Kd(e,e=>e.getType()===`audio`)+1;e.push(new mg(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=Kd(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=Kd(e,e=>e.getType()===`audio`)+1;e.push(new mg(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}},fg=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:Cd(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 fg{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())}},mg=class extends fg{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={}}))(),Ud();var hg=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var gg=class extends Zd{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 Q_;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,hg),e=this._getFileSize(),B(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new Q_;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 Cg(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new _g(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},_g=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()}},vg=class extends gg{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 gg||e instanceof _g))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof gg?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(n):n(t)}},yg=(e,t)=>e.path===t.path,bg=class extends vg{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 gg?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())}},xg=class extends gg{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=qu(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(){}},Sg=class extends gg{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&&(!Wd(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}=ud();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 Q_);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Cg=class extends gg{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:bd(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()}},wg=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},Tg=(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}),Eg=/^0[xX][0-9a-fA-F]+$/,Dg=/^data:.*;base64,/i,Og=class extends dg{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 Xd(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=wg(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=await new $_(n.source).requestEntireFile();B(r),e=hv(r,r.length,{ignore:lg}),n.source instanceof vg&&(this.rootPath=n.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{Tg(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=Gu(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:Gd(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(ng.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 ug(y.slice(rg.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:Gd(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 ug(y.slice(ig.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(!Eg.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:Gd(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(Dg.test(n)){let e=n.indexOf(`,`),t=Vd(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=Yp(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(ag.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(og.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(sg.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=Gu(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(cg.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=>Xp(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},a=new X_({source:new bg(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 Sg(pm(new $_(a.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new $_(wg(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{Tg(t)}},()=>{a.free()})).ref()}else B(!1);return r}),formats:this.input._formats.filter(e=>!(e instanceof Jg)),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=qd(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}},kg=class extends Gp{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 vg);let e=await this.input._reader.requestEntireFile();B(e);let t=hv(e,e.length,{ignore:lg}),{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=Gd(n,o),c=new ug(a.slice($h.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 ug(a.slice(eg.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=Gd(n,i);r.push({fullPath:o,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(a.startsWith(`#EXT-X-MEDIA:`)){let t=new ug(a.slice(tg.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=Gd(n,o)),i.push({fullPath:r,attributes:t,lineNumber:e})}else if(a!==`#EXT-X-I-FRAMES-ONLY`&&a.startsWith(`#EXTINF:`)){let e=new Og(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=>of.includes(bf(e))),f=c.some(e=>cf.includes(bf(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=Gd(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=Gd(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=bf(n);if(s!==null){if(of.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:Ng(n.attributes),autoselect:Ng(n.attributes)||Pg(n.attributes),languageCode:Fg(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(cf.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:Ng(n.attributes),autoselect:Ng(n.attributes)||Pg(n.attributes),languageCode:Fg(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 jg(e)):this.trackBackings.push(new Mg(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 Og(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Qh}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Ag=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 jg){for(let e of n)if(await e.getCodec()===this.getCodec()){t=e;break}}else{B(this instanceof Mg);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{...tf,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)}},jg=class extends Ag{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return bf(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()}},Mg=class extends Ag{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return bf(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()}},Ng=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}".`)},Pg=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}".`)},Fg=e=>e===null?`und`:e.split(`-`)[0]||`und`,Ig=class{constructor(){this._isIsobmff=!1}},Lg=class extends Ig{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 mm(e)}},Rg=class extends Lg{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`}},zg=class extends Lg{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Bg=class extends Ig{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Pm(n);if(r===null||r<1||r>8||q(n,r)!==K.EBML)return!1;let i=Rm(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=zm(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(Bm(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 $m(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},Vg=class extends Bg{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},Hg=class extends Ig{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=xv(n);if(!r)break;t=n.filePos+r.size}let n=await rh(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=Tf(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 rh(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 ih(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},Ug=class extends Ig{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 yh(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},Wg=class extends Ig{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 mh(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},Gg=class extends Ig{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=xv(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 Mh(e)}},Kg=class extends Ig{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=xv(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=Sh(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=Sh(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new wh(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},qg=class extends Ig{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 Uh(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Jg=class extends Ig{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 vg))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 kg(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return Qh}},Yg=[new Jg,new Rg,new zg,new Bg,new Vg,new Ug,new Wg,new Gg,new Hg,new Kg,new qg],Xg=(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.`)}},Zg=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},Qg=(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});Ud();var $g=-1/0,e_=-1/0,t_=null;typeof FinalizationRegistry<`u`&&(t_=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-$g>=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.`),$g=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-e_>=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.`),e_=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var n_=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},r_=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],i_=new Set(r_),a_=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(kd*this.timestamp)}get microsecondDuration(){return Math.trunc(kd*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||!i_.has(n.format))throw TypeError(`init.format must be one of: `+r_.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&&Yd(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??g_(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?qu(t):qu(t).slice(),this._layout=e,this.colorSpace=new d_(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&&Yd(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 d_(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&&Yd(n.visibleRect,`init.visibleRect`),typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*kd),duration:Math.trunc((n.duration??0)*kd)||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:Pd(),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 d_({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof n_){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&&!r_.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=Jd({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),t_?.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 n_?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):f_(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||=(t_?.unregister(this),this._data instanceof n_?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):f_(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(h_(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 f_(this._data)?this._data.allocationSize(e):v_(this,e).allocationSize}async copyTo(t,n={}){if(!nd(t))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(h_(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),f_(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 n_){let r={stack:[],error:void 0,hasError:!1};try{let i=Zg(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{Qg(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=v_(this,n);B(this.format);let i=qu(t);if(i.byteLength<r.allocationSize)throw TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${i.byteLength}`);let a=__(this.format),o;if(this._data instanceof n_){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:qu(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 n_){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 f_(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&&m_(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?u_(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 n_||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&&m_(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=Wu(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=Sd(l,t.roundDimensionsTo??1),u=Sd(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 o_){let t=e(this,d);if(t instanceof Promise&&(t=await t),t!==null)return t}let{canvas:f,context:p,isNew:m}=u_(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()}},o_=[],s_=3,c_=[],l_=0,u_=(e,t)=>{for(let n of c_)if(n.canvas.width===e&&n.canvas.height===t)return n.age=l_++,{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 c_.length>=s_&&c_.splice(qd(c_,e=>e.age),1),c_.push({canvas:n,context:r,age:l_++}),{canvas:n,context:r,isNew:!0}},d_=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(Xu);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(Qu);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(ed);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}}},f_=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}},m_=(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.`)},h_=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.`)}},g_=(e,t,n)=>{let 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},__=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:gd(e),B(!1)}},v_=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=y_(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 x_(i,o,a)},y_=(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(!b_(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},b_=(e,t)=>{if(e===null)return!0;let n=__(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},x_=(e,t,n)=>{let 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}},S_=[],C_=[],w_=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.`)},T_=e=>{if(!Wd(e))throw TypeError(`timestamp must be a number.`)},E_=(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,D_=class{constructor(e){if(!(e instanceof R_))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(w_(e),this._track.input._disposed)throw new Q_;return E_(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){w_(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(T_(e),w_(t),this._track.input._disposed)throw new Q_;return E_(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof qp))throw TypeError(`packet must be an EncodedPacket.`);if(w_(t),this._track.input._disposed)throw new Q_;return E_(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(T_(e),w_(t),this._track.input._disposed)throw new Q_;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 qp))throw TypeError(`packet must be an EncodedPacket.`);if(w_(t),this._track.input._disposed)throw new Q_;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 qp))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 qp))throw TypeError(`endPacket must be an EncodedPacket.`);if(w_(n),this._track.input._disposed)throw new Q_;let r=[],{promise:i,resolve:a}=ud(),{promise:o,resolve:s}=ud(),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}=ud()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=ud(),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 Q_;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}}}},O_=class{constructor(e,t){this.onSample=e,this.onError=t}},k_=class{mediaSamplesInRange(e=-1/0,t=1/0,n){T_(e),T_(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=ud(),{promise:c,resolve:l}=ud(),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}=ud())},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=A_(r.length);if(r.length+p.getDecodeQueueSize()>e){({promise:c,resolve:l}=ud()),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 Q_;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){hd(e);let n=md(e),r=[],i=[],{promise:a,resolve:o}=ud(),{promise:s,resolve:c}=ud(),l=!1,u=!1,d=null,f=null,p=!1,m=e=>{i.push(e),o(),{promise:a,resolve:o}=ud()},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=A_(i.length);for(;i.length+d.getDecodeQueueSize()>n&&!u;)({promise:s,resolve:c}=ud()),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(T_(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 Q_;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}}}},A_=e=>e===0?40:8,j_=class extends O_{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 Ad,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=S_.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 a_))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&&Id()){let e=Wf(qu(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=Kf(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),Md()||ld(this.inputTimestamps,e.timestamp,e=>e),Id()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[],n=!1;for(let r of If(e.data,this.decoderConfig)){let i=Lf(e.data[r.offset]);if(n||=i>=1&&i<=5,i===Mf.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}e=new qp(Hf(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=sp(e.data,this.decoderConfig);t&&(e=new qp(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 N_,!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=hp(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 Yf(e,this.decoderConfig)){let n=Xf(e[t.offset]);if(n===Nf.RASL_N||n===Nf.RASL_R)return!0}return!1}sampleHandler(e){if(Md()){if(this.sampleQueue.length>0&&e.timestamp>=Gu(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ld(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=ud();this.mergeAlphaPromises.push(n.promise);let r={sample:null};this.finalSamples.push(r);try{for(t?(B(this.merger),r.sample=new a_(await this.merger.merge(e,t))):r.sample=new a_(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){dd(this.finalSamples,r),this.onError(e)}finally{dd(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),Md()){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}},M_=null,N_=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!M_){let e=new Blob([`(${P_.toString()})()`],{type:`application/javascript`});M_=URL.createObjectURL(e)}let e=bd(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(M_);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=ud();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()}},P_=()=>{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)}},F_=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.`)},I_=class extends k_{constructor(e,t={}){if(!(e instanceof B_))throw TypeError(`videoTrack must be an InputVideoTrack.`);F_(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof VideoDecoder>`u`?zd(`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 j_(e,t,n,i,r,a)}_createPacketSink(){return new D_(this._track)}async getSample(e,t={}){T_(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)}},L_=class{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof B_))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&&m_(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&&F_(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new I_(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||Pd()});B(a),e._drawWithFitAndMipmapping(r,a,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:i,fillBlack:!this._alpha&&Pd()});let o={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){T_(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*yd(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*yd(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},R_=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof B_}isAudioTrack(){return this instanceof V_}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 Cd((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 D_(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(G_({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(G_({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(G_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(G_({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(G_({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=z_(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&&=z_(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=z_(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},z_=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},B_=class extends R_{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??=Jd({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Jd({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),S_.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 qp))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),hp(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 D_(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=q_(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?Y_(w):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:w,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},V_=class extends R_{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),C_.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 qp))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},H_=e=>-(e??-1/0),U_=e=>-e,W_=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}},G_=(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}),K_=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)},q_=(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=J_(p,m,n),r=J_(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},J_=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return Jd({num:n,den:r})}return null},Y_=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};Ud();var X_=class e extends Zd{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 Ig)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof gg||t.source instanceof _g))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof gg&&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&&Xg(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof gg?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){B(this._rootSource instanceof vg);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&&yg(n.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let r=this._sourceCachePromises.find(n=>n.cacheGroup===t&&yg(n.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());let i=(async()=>{let n=await this._getSourceUncached(e);if(Kd(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=qd(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(),dd(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 $_(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 Z_})()}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 Z_)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&&=W_(e),K_((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=W_(e),K_((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=W_(e),K_((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=W_(e);let t=G_(e,{sortBy:async e=>[U_((await e.getDisposition()).default),U_(await e.hasPairableAudioTrack()),U_(!await e.hasOnlyKeyPackets()),H_(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=W_(e);let t=await this.getPrimaryVideoTrack(),n=G_(e,{sortBy:async e=>[U_(!t||e.canBePairedWith(t)),U_((await e.getDisposition()).default),H_(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 B_(this,e):new V_(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()}},Z_=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},Q_=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},$_=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 Q_;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=new Uint8Array;return new ev(t,H(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,hg);return r instanceof Promise?r.then(t=>t?new ev(t.bytes,t.view,t.offset,e,n):null):r?new ev(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new Q_;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,bd(this.fileSizeNonStrict-e,t,n));{let r=this.requestSlice(e,n),i=r=>r||(B(this.fileSizeNonStrict!==null),this.requestSlice(e,bd(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 ev(n,H(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},ev=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)}},tv=(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)=>{tv(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},X=e=>(tv(e,1),e.view.getUint8(e.bufferPos++)),nv=(e,t)=>{tv(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},Z=e=>{tv(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},rv=e=>{tv(e,3);let t=_d(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},iv=e=>{tv(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},av=(e,t)=>{tv(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Q=e=>{tv(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},ov=e=>{tv(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},sv=e=>{tv(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},cv=e=>{tv(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},lv=(e,t)=>{let n,r;return t?(n=av(e,!0),r=av(e,!0)):(r=av(e,!1),n=av(e,!1)),r*4294967296+n},uv=e=>{let t=Q(e),n=Q(e);return t*4294967296+n},dv=e=>{let t=sv(e),n=Q(e);return t*4294967296+n},fv=e=>{let t=ov(e);return cv(e)*4294967296+t},pv=e=>{tv(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},mv=e=>{tv(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},$=(e,t)=>{tv(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},hv=(e,t,n)=>Ju.decode(Y(e,t)).split(`
|
|
65
|
-
`).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e)),gv;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(gv||={});var _v;(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`})(_v||={});var vv=`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(`.`),yv=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=Y(e,125),e.filePos=n;let r=bv(e,30);r&&(t.title??=r);let i=bv(e,30);i&&(t.artist??=i);let a=bv(e,30);a&&(t.album??=a);let o=bv(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=bv(e,28),e.skip(2)}else e.skip(-30),l=bv(e,30);l&&(t.comment??=l);let u=X(e);u<vv.length&&(t.genre??=vv[u])},bv=(e,t)=>{let n=Y(e,t),r=Bd(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()},xv=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=Df(o);return a&gv.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},Sv=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){W._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new Cv(t,Y(e,t.flags&gv.Footer?t.size-10:t.size));if(t.flags&gv.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&gv.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&gv.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(vv[e]!==void 0){n.genre??=vv[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(vv[e]!==void 0){n.genre??=vv[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}},Cv=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?Df(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:Df(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 _v.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 _v.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=Bd(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=Bd(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=Bd(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Ju.decode(r.subarray(0,e))}case _v.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=Bd(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 _v.UTF_8:{let e=Bd(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Ju.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},wv=.5;function Tv(e,t){return e===null||t<e.servedSeconds||t-e.servedSeconds>wv}async function Ev(e){try{let t=await new X_({formats:Yg,source:new xg(e)}).getPrimaryVideoTrack();return t?await t.canDecode()?{sink:new L_(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 Dv(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 Ev(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(Tv(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||!Ao(i,e.viewport)?r:r===null||i.endMs>r.endMs?i:r,null);return{async at(t){let n=Mo(e,t);if(n){let e=await u(n,t);if(e)return e}let r=Vu(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 Hu(e,t,n))s(r.ref).catch(()=>void 0)},describe:()=>({keyframes:e.keyframes,motionSpans:e.motionSpans}),unavailable:()=>[...i]}}var Ov=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:kv,GIFEncoder:Av,quantize:jv}=typeof Ov.GIFEncoder==`function`?Ov:Ov.default??Ov,Mv=.012,Nv=1.5,Pv=2,Fv=24;function Iv(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=$c(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=Mv*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/Nv),Pv,Fv),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>=Fv)break;m=Math.min(Fv,Math.ceil(m*e/Nv))}return h}var Lv=new WeakMap;function Rv(e,t,n){let r=Lv.get(n);(!r||r.width!==e||r.height!==t)&&(r=new OffscreenCanvas(e,t),Lv.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 zv(e,t){if(t.length===0)return;let{width:n,height:r}=e.canvas,{scratch:i,ctx:a}=Rv(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 Bv=`#4b5563`;function Vv(e,t){e.save(),e.fillStyle=Bv,e.fillRect(t.x,t.y,t.width,t.height),e.restore()}function Hv(e,t,n){for(let r of t)Vv(e,n(r.rect))}var Uv={format:`mp4`,width:3840,height:2160,fps:60,bitrate:4e7,cornerRadius:36,fit:`contain`},Wv={format:`mp4`,width:2560,height:1440,fps:60,bitrate:18e6,cornerRadius:24,fit:`contain`},Gv={format:`mp4`,width:1920,height:1080,fps:60,bitrate:1e7,cornerRadius:18,fit:`contain`},Kv={format:`mp4`,width:1080,height:1920,fps:60,bitrate:12e6,cornerRadius:24,fit:`cover`},qv={format:`mp4`,width:2560,height:1440,fps:30,bitrate:9e6,cornerRadius:24,fit:`contain`,encoder:{quality:.5}},Jv={format:`mp4`,width:720,height:1280,fps:30,bitrate:267e4,cornerRadius:16,fit:`cover`,encoder:{quality:.5}},Yv={...Wv,bitrate:8e6},Xv=1e7,Zv={...Kv,bitrate:Yv.bitrate},Qv={format:`gif`,width:800,height:450,fps:15,bitrate:0,cornerRadius:10,fit:`contain`},$v={format:`png`,width:2560,height:1440,fps:0,bitrate:0,cornerRadius:24,fit:`contain`},ey={format:`gif`,width:450,height:800,fps:15,bitrate:0,cornerRadius:10,fit:`cover`},ty={format:`png`,width:1080,height:1920,fps:0,bitrate:0,cornerRadius:24,fit:`cover`};function ny(e){let t=Math.max(...e.keyframes.map(e=>e.width),0);return t>=Uv.width?Uv:t>=Wv.width?Wv:Gv}function ry(e){let t=Math.max(...e.keyframes.map(e=>Math.max(e.width,e.height)),0);return t>=Uv.width?Uv:t>=Wv.width?Wv:Gv}function iy(e,t){return t===`auto`?ry(e):ny(e)}function ay(e,t,n,r){return e===`auto`?cy(t,n,r):t}var oy=36864,sy=(e,t)=>Math.ceil(e/16)*Math.ceil(t/16);function cy(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`&&sy(c,l)>oy)for(s=2*Math.floor(s*Math.sqrt(oy*256/(c*l))/2);{width:c,height:l}=o(s),!(sy(c,l)<=oy);)s-=2;return{...e,width:c,height:l,fit:`contain`,shapedToRecording:!0,bitrate:Math.round(e.bitrate*c*l/(e.width*e.height))}}function ly(e){return e.map(e=>{let t=z(e.scale,1,zc.verticalMaxScale);return t<e.scale?{...e,scale:t,requestedScale:e.requestedScale??e.scale}:{...e,scale:t}})}function uy(e,t){return e.fit===`cover`?ly(t):t}var dy=Uv.width*zc.maxScale,fy=dy*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 my(e){return e.height>e.width?`portrait`:`landscape`}function hy(e){return my(e)===`portrait`?{width:fy,height:dy}:{width:dy,height:fy}}function gy(e,t=hy(e)){let n=Math.max(e.width/t.width,e.height/t.height),r=Math.min(1,n*zc.maxScale);return{width:Math.ceil(t.width*r),height:Math.ceil(t.height*r)}}function _y(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 vy(e,t){return e.logo===null?0:Math.ceil(e.logo.size*Math.min(t.width,t.height))}function yy(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:Lo(n,o),d=e.logo,f=d!==null&&r!==null?_y(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 by(e,t){return Math.max(e.width/t.width,e.height/t.height)}function xy(e,t,n,r){let i=by(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 Sy(e,t,n,r){let i=xy({x:e.x,y:e.y},t,n,r),a=by(n,r)*t.scale;return{x:i.x,y:i.y,width:e.width/a,height:e.height/a}}function Cy(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 wy(e,t,n){let r=n.background;if(r.kind===`solid`)e.fillStyle=r.color;else{let n=r.kind===`gradient`?r:Ys,{x0:i,y0:a,x1:o,y1:s}=Cy(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;let{sx:a,sy:o,sw:s,sh:c}=py(i,t);e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`,e.drawImage(i.image,a,o,s,c,0,0,t.width,t.height)}function Ty(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 Ey(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`,Ty(e,t),e.fill(),e.restore()}function Dy(e,t){Ty(e,t),e.clip()}function Oy(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 ky(e,t,n,r){let i=e.plan.viewport,{frameRect:a}=t;return $c(e,r,by(a,i),a,i,n)}function Ay(e,t,n,r){let i=by(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 jy(e,t,n,r){let i=Ay({x:e.x,y:e.y},t,n,r),a=by(n,r)*t.scale;return{x:i.x,y:i.y,width:e.width*a,height:e.height*a}}function My(e,t,n){let r=Cu(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=jc(e.timeline,s);if(c<i.sourceTimeMs)continue;let l=$l(e.cursor,c);l&&o.push({x:l.x,y:l.y,outputMs:s})}return o}function Ny(e,t,n,r){return My(e,t,n).map(t=>({x:t.x,y:t.y,angleRad:Bu(e,t.outputMs,r)}))}async function Py(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=jc(t.timeline,o),d=by(l,c),f=ky(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`,()=>wy(a,n,r)),s(`chrome`,()=>Ey(a,r,f.scale)),a.restore(),a.save(),h(),Dy(a,r),a.setTransform(1,0,0,1,0,0);let g=Ay({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`,()=>Hv(a,t.cosmetics.filter(e=>e.range===null||o>=e.range.startMs&&o<e.range.endMs),e=>jy(e,f,l,c))),a.restore(),a.save(),h(),s(`logo`,()=>Oy(a,n,r)),a.restore(),s(`blur`,()=>zv(a,Iv({camera:t,outputTimeMs:o,blur:t.motion.blur,current:f,base:d,frameRect:l,viewport:c,canvas:n}))),a.save(),h(),Dy(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:$l(t.cursor,u);if(b){let e=Ay(b,f,l,c),r=n.height/1080*y.scale*f.scale,i=a.globalAlpha;a.globalAlpha=y.hideWhenIdle?du(t.cursorRestOutputMs,o):1;let s=y.style===`touch`?0:y.tilt??zs.tilt,u=Bu(t,o,s),d=Ny(t,o,y.motionBlur,s).map(e=>({...Ay(e,f,l,c),angleRad:e.angleRad})),p=d[0];p&&Math.hypot(e.x-p.x,e.y-p.y)>=1&&wu(a,d,r,y.style);for(let n of t.clickOutputMs){let t=(o-n)/400;t>=0&&t<=1&&Tu(a,e,r,t)}xu(a,e,r,{press:ju(o,t.clickOutputMs,y.clickBounce??zs.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=Ay(n.at,f,l,c);a.globalAlpha=t<0?1+t/110:1-t/400,t>=0&&Tu(a,r,e,t/400),xu(a,r,e,{press:ju(o,[n.outputMs],1),angleRad:0},`touch`)}a.globalAlpha=r}e.onStage?.(`cursor`,performance.now()-v),a.restore()}function Fy(e,t){let n=Mo(e,t);return n?n.width:No(e,t)?.width??0}function Iy(e){let{keys:t,timeline:n,bundle:r,outputPxPerCssPx:i,viewport:a}=e,o=[],s=t.map(e=>{let t=Fy(r,jc(n,e.outputTimeMs));if(t===0)return e;let s=No(r,jc(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(...Ly(s,o,n,r,i,a)),{keys:s,violations:o}}function Ly(e,t,n,r,i,a){let o=[];for(let s of r.motionSpans){let c=Mc(n,s.startMs),l=Mc(n,s.endMs);if(l<=c||!Ao(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 Ry(e,t){let n=uy(t,e.cameraIntents);return n===e.cameraIntents?e:{...e,cameraIntents:n}}function zy(e,t,n){if(e.fit!==`cover`)return null;let r=by(t,n);return{width:t.width/r,height:t.height/r}}function By(e){let{plan:t,bundle:n,scene:r,target:i,hints:a,logo:o=null,wallpaper:s=null}=e,c=e.detailTarget??i,l=yy(r?.branding??Xs,i,t.viewport,o,s),u=c===i?l.frameRect:yy(r?.branding??Xs,c,t.viewport,o).frameRect,d=mu(Ry(t,i),n,r,a,zy(i,u,t.viewport)),f=Iy({keys:d.cameraKeys,timeline:d.timeline,bundle:n,outputPxPerCssPx:by(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 Vy(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 Hy(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 Uy(e,t,n){let r=(t,n)=>e.motionSpans.some(e=>e.startMs<n&&e.endMs>t)||e.degradations.some(e=>mc(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)||Hy(Vy((await t.at(o.sourceTimeMs)).image),Vy((await t.at(s.sourceTimeMs)).image))>n&&i.push({startMs:o.sourceTimeMs,endMs:s.sourceTimeMs})}return i}var Wy=.12;function Gy(e,t,n){let r=py(t,e).sw/e.width;return n*Wy*Math.min(e.width,e.height)*r}function Ky(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 qy(e){if(e==null)return{state:`missing`};let t=Js.safeParse(Yy(e));return t.success?{state:`ready`,kit:t.data}:{state:`invalid`,reason:t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}}var Jy=.08;function Yy(e){return typeof e!=`object`||!e||Array.isArray(e)||`padding`in e?e:{...e,padding:Jy}}var Xy=e=>e.trim().toLocaleLowerCase();function Zy(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=qy(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 Qy(e){return e.state!==`ready`||e.defaultId===null?null:e.kits.find(t=>t.id===e.defaultId)??null}var $y=(e,t,n)=>`${e} ${e===1?t:n}`,eb=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 tb(e,t){return e===void 0||e.byteLength<=e.maxBytes?[]:[`it is ${eb(e.byteLength)}, over the ${eb(e.maxBytes)} a GIF is kept under even at ${t} px wide; an MP4 of this take is much smaller`]}function nb(e){let t=e[0];return t===void 0?[]:[`${$y(e.length,`step got no still`,`steps got no still`)} (${t.actionId}: ${t.reason})`]}function rb(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 ib(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({ video: { id: "${t}" } }) re-records it`:` — re-record it with run's video: { id }`:i===r?``:` — ${i.actionId}'s step changed from ${i.was??``} to ${i.now??``}, so derive this take, check the step, and run the draft`;return[`${$y(e.length,`step was`,`steps were`)} edited after recording (${rb(r)})${a}`,...n>0?[`a re-recording leaves its ${$y(n,`mask`,`masks`)} behind`]:[]]}function ab(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?[]:[`${$y(r.length,`stretch of motion is a still`,`stretches of motion are stills`)}`],...nb(s??[]),...(i??[]).map(e=>e.replace(/\.$/,``)),...ib(a??[],e.warnings.videoId,o??0),...tb(c,e.width)]}var ob=new Set([`image/svg+xml`,`image/png`,`image/webp`,`image/jpeg`]);function sb(e){return e.type===``?{ok:!1,reason:`The logo "${e.name}" has no file type — use SVG, PNG, WebP or JPEG`}:ob.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 cb(e){return e.type===``?{ok:!1,reason:`The image "${e.name}" has no file type — use PNG, JPEG, WebP or SVG`}:ob.has(e.type)?{ok:!0}:{ok:!1,reason:`The image "${e.name}" is a ${e.type} file — use PNG, JPEG, WebP or SVG`}}var lb=e=>({image:e,width:e.width,height:e.height,sourceTimeMs:0});function ub(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 db=e=>{if(e===null)return null;let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0&&!e.trim().endsWith(`%`)?t:null};function fb(e){let t=ub(e),n=db(t.getAttribute(`width`)),r=db(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 pb(e){let t=fb(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),lb(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 mb(e,t){if(t===`image/svg+xml`){let t=await pb(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=lb(n);return{contentType:t,aspect:n.width/n.height,naturalHeight:n.height,rasterAt:async()=>r}}async function hb(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 gb=`image/webp`,_b=.97;async function vb(e){let t=e instanceof File?e.name:`(unnamed)`,n,r,i;try{if(e.type===`image/svg+xml`){let t=await mb(new Uint8Array(await e.arrayBuffer()),e.type),a=await t.rasterAt(t.aspect>=1?dy/t.aspect:dy);({image:n,width:r,height:i}=a)}else{let t=await createImageBitmap(e),a=Math.min(1,dy/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:gb,quality:_b})}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!==gb)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 yb=`X-Demoman-Studio`,bb={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`},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`},reveal:{method:`POST`,path:`/api/reveal`},window:{method:`POST`,path:`/api/window`},events:{method:`GET`,path:`/api/events`}};function xb(e,t={}){return bb[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 Sb=`X-File-Name`,Cb=`brandKit`,wb=`brandKits`,Tb=`defaultKitId`;function Eb(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&&Xy(e.name)===Xy(r));return i===void 0?{ok:!0,name:r}:{ok:!1,reason:`a kit is already named "${i.name}"`}}function Db(e,t){let n=new Set(t.map(e=>Xy(e.name)));if(!n.has(Xy(e)))return e;for(let t=2;;t+=1){let r=`${e} ${t}`;if(!n.has(Xy(r)))return r}}var Ob=()=>`kit-${crypto.randomUUID()}`,kb=`demoman-brand-kits`,Ab=Promise.resolve(),jb=e=>{let t=Ab.then(e);return Ab=t.catch(()=>void 0),t},Mb=e=>typeof navigator<`u`&&navigator.locks!==void 0?navigator.locks.request(kb,e):jb(e),Nb=e=>e instanceof Error?e.message:String(e),Pb=`kit-migrated`,Fb=class extends Error{};function Ib(e,t=Mb){async function n(){let t=await e().get([wb,Tb,Cb]),n=t[wb],r=t[Tb],i=t[Cb];if(i===void 0)return{list:n,def:r,pending:!1};if(n===void 0){let t=Pb;n=[{id:t,name:`Brand kit`,branding:i}],r=t;try{await e().set({[wb]:n,[Tb]:r})}catch(e){throw new Fb(Nb(e))}}try{return await e().remove(Cb),{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 Zy(e,r,i)}catch(e){return{state:`invalid`,storageRefused:!0,reason:e instanceof Fb?`storage refused moving your brand kit into the kit list: ${e.message}`:`storage refused the read: ${Nb(e)}`}}}async function i(){try{let{list:e,def:t}=await n(),r=Zy(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 (${Nb(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({[wb]:r.kits,[Tb]:r.defaultId}),null)}),reset:()=>t(()=>e().set({[wb]:[],[Tb]:null}))}}async function Lb(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 Rb=/`([^`]*)`/g;function zb(e,t=document){let n=[],r=0;for(let i of e.matchAll(Rb)){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 Bb=e=>e.replace(Rb,`$1`);function Vb(e,t){e.replaceChildren(...zb(t,e.ownerDocument))}var Hb={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.`};function Ub(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(...zb(Hb[e],t)),r.append(i),n.append(r)}var Wb=class extends Error{reason;status;constructor(e,t,n){super(t),this.name=`StudioError`,this.reason=e,this.status=n}},Gb=new Set([`hostRefused`,`tokenMissing`,`tokenWrong`,`headerMissing`]),Kb=`Your brand kits kept changing in another window, so this change was not saved.`,qb=`Ask your agent for a demo video. Each take shows up here, grouped by the day you made it.`,Jb=e=>`Ask your agent to re-record this take — \`run({ video: { id: "${e}" } })\``,Yb=`Ask your agent to re-record this take.`,Xb=e=>`Couldn't read which video this take is in: ${e}`,Zb=e=>e instanceof Error?e.message:String(e),Qb=e=>e.slice(e.lastIndexOf(`/`)+1)||e;function $b(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 ex(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:[Qb(e.file.path)],byteLength:e.file.byteLength,reveal:{kind:`path`,path:e.file.path},summary:e.summary,outputRefs:[]}}function tx(e){try{return ab(e)}catch(e){return[`its warnings could not be read: ${e instanceof Error?e.message:String(e)}`]}}function nx(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:Qb(e.path),byteLength:e.byteLength,path:e.path,exists:e.exists,sceneDigest:e.sceneDigest,renderedAt:e.renderedAt,detail:r,caveats:n===null?[]:tx(n)}}function rx(e={}){let t=!1,n=null,r=e=>{t||(n??=e,Ub(e))};async function i(e,t={}){let n=bb[e];n.method!==`GET`&&await s;let i=xb(e,t.params);t.query!==void 0&&(i+=`?${new URLSearchParams(t.query).toString()}`);let a={[yb]:`1`,...t.headers},o;t.json===void 0?t.raw!==void 0&&(o=t.raw):(a[`Content-Type`]=`application/json`,o=JSON.stringify(t.json));let c;try{c=await fetch(i,{method:n.method,headers:a,body:o,credentials:`same-origin`,signal:t.signal})}catch(e){throw t.retried!==!0&&r(`stopped`),new Wb(`studioGone`,`The Studio did not answer ${n.method} ${i} (${Zb(e)}).`,0)}if(c.ok)return c;let l=null;try{l=await c.json()}catch{}let u=typeof l?.reason==`string`?l.reason:`noReason`,d=typeof l?.detail==`string`?l.detail:`The Studio answered ${c.status} to ${n.method} ${i} without saying why.`;throw c.status===403&&(u===`noReason`||Gb.has(u))&&r(`expired`),new Wb(u,d,c.status)}async function a(e){try{return await e.json()}catch(t){throw new Wb(`internalError`,`The Studio's answer was not JSON (${Zb(t)}).`,e.status)}}let o=`0.8.1`,s=(async()=>{let e=await a(await i(`ping`));if(e.version!==o)throw r(`updated`),new Wb(`versionSkew`,`${Hb.updated} (this page is ${o}, the Studio ${e.version})`,0)})();s.catch(e=>{console.info(`demoman studio: no edits will be sent:`,Zb(e))});let c=new Set,l=new Set,u=new Set,d=new Set,f=(e,t,n)=>{for(let r of[...e])try{r(t)}catch(e){console.error(`demoman studio: a ${n} listener failed`,e)}},p=e=>f(c,e,`export`),m=new Set,h=0,g=[];function _(e){if(!m.has(e.jobId)){if(h>0){g.push(e);return}e.phase===`saved`&&p({kind:`outputsChanged`});return}switch(e.phase){case`queued`:p({kind:`queued`,jobId:e.jobId,position:e.position});return;case`rendering`:p({kind:`rendering`,jobId:e.jobId,done:e.done,total:e.total});return;case`saving`:p({kind:`saving`,jobId:e.jobId});return;case`saved`:{m.delete(e.jobId);let t=e.report;t.outcome===`saved`?p({kind:`saved`,jobId:e.jobId,save:ex(t),summary:t.summary}):p({kind:`failed`,jobId:e.jobId,detail:t.summary}),p({kind:`outputsChanged`});return}case`failed`:m.delete(e.jobId),p({kind:`failed`,jobId:e.jobId,detail:e.detail}),p({kind:`outputsChanged`});return}}function v(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`:_(n);return;case`kits`:f(l,void 0,`kits`);return;case`takes`:f(u,void 0,`takes`);return;case`watchFailed`:switch(n.feed){case`takes`:f(u,void 0,`takes`);return;case`kits`:f(l,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`:f(d,n.path,`open`);return;case`server:stopping`:r(`stopped`);return;default:console.info(`demoman studio: an event this page does not know: ${e}`)}}let y=new AbortController;globalThis.addEventListener?.(`pagehide`,()=>{t=!0,y.abort()});let b=e.reload??(()=>location.reload());globalThis.addEventListener?.(`pageshow`,e=>{e.persisted&&b()});async function x(){let e=0;for(;;){if(t||n!==null)return;let a;try{let t=(await i(`events`,{signal:y.signal,retried:!0})).body;if(t===null)throw Error(`the event stream has no body`);let n=t.getReader(),r=new TextDecoder,o=``;for(;;){let{done:t,value:i}=await n.read();if(t)break;e=0,o+=r.decode(i,{stream:!0}).replace(/\r\n?/g,`
|
|
68
|
-
`);let a=o.indexOf(`
|
|
69
|
-
|
|
70
|
-
`);for(;a>=0;){let e=$b(o.slice(0,a));o=o.slice(a+2),e!==null&&v(e.type,e.data),a=o.indexOf(`
|
|
71
|
-
|
|
72
|
-
`)}}a=`the Studio closed the event stream`}catch(e){if(e instanceof Wb&&e.status===403)return;a=Zb(e)}if(t||n!==null)return;if(e+=1,e>=2){console.info(`demoman studio: the event stream is gone (${a})`),r(`stopped`);return}console.info(`demoman studio: reconnecting the event stream (${a})`)}}x();let S=new Map,C=null,w=null,T={async get(){let e=await a(await i(`kitsGet`));if(C=e.revision,w=e.unwatched,`invalid`in e)throw Error(e.invalid.reason);return{[wb]:e.stored.kits,[Tb]:e.stored.default}},async set(e){if(C===null)throw Error(`the brand kits were written before they were read`);C=(await a(await i(`kitsPut`,{json:{kits:e.brandKits??[],default:e.defaultKitId??null},headers:{"If-Match":C}}))).revision},async remove(){throw Error(`the Studio keeps no old brand kit key to remove`)}},ee=Ib(()=>T,e.kitLock),te={async read(){let e;try{e=await a(await i(`kitsGet`)),w=e.unwatched}catch(e){return{state:`invalid`,storageRefused:!0,reason:`the Studio did not answer the kits read: ${Zb(e)}`}}return`invalid`in e?{state:`invalid`,reason:e.invalid.reason,...e.invalid.storageRefused===!0?{storageRefused:!0}:{}}:Zy(e.stored.kits,e.stored.default)},readStored:()=>ee.readStored(),async update(e){for(let t=1;;t+=1)try{return await ee.update(e)}catch(e){if(!(e instanceof Wb&&e.status===409))throw e;if(t>=3)throw new Wb(`kitsBusy`,Kb,409)}},async reset(){return{backup:(await a(await i(`kitsReset`))).backup}},onChange(e){return l.add(e),()=>l.delete(e)},unwatched:()=>w};async function E(e){try{let t=await a(await e);return{ok:!0,...t.note===null?{}:{note:t.note},...t.partly===void 0?{}:{partly:t.partly}}}catch(e){if(!(e instanceof Wb)||e.status===0)throw e;return{ok:!1,error:e.reason,detail:e.message.replace(/\.$/,``)}}}let ne=new Map,D=new Map;async function re(){let e=await a(await i(`takes`));for(let[t,n]of Object.entries(e.videoOf))ne.set(t,n.videoId);return{videos:e.videos,videoOf:e.videoOf,scenes:e.scenes,sizes:e.sizes,unreadable:e.unreadable,unwatched:e.unwatched}}return{scenes:{async get(e){try{let t=await a(await i(`sceneGet`,{params:{id:e}}));return t.videoId===null?ne.delete(e):ne.set(e,t.videoId),t.videoError===null?D.delete(e):D.set(e,t.videoError),{scene:t.scene,revision:t.revision,notes:t.notes}}catch(e){if(e instanceof Wb&&e.reason===`takeNotFound`)return null;throw e}},async put(e,t){return{revision:(await a(await i(`scenePut`,{params:{id:e.meta.id},json:e,headers:t===null?{}:{"If-Match":t}}))).revision}},async list(){return(await re()).scenes},remove:e=>E(i(`takeDelete`,{params:{id:e}}))},videos:{async rename(e,t){await a(await i(`videoRename`,{params:{id:e},json:{name:t}}))},remove:e=>E(i(`videoDelete`,{params:{id:e}}))},folder:{read:re,onChange(e){return u.add(e),()=>u.delete(e)},async thumb(e){let t=S.get(e);if(t===void 0)throw Error(`the frame "${e}" is in no take this page has read a bundle for, so its preview cannot be asked for`);let n=await i(`thumb`,{params:{id:t,ref:e}});return createImageBitmap(await n.blob())}},bundles:{async active(e){let t=await a(await i(`bundle`,{params:{id:e}}));for(let n of t.bundle?.keyframes??[])S.set(n.ref,e);for(let n of t.bundle?.motionSpans??[])S.set(n.ref,e);return{bundle:t.bundle,replay:t.replay??null,capture:null}},async load(e){let t=S.get(e);if(t===void 0)throw Error(`the frame "${e}" is in no take this page has read a bundle for`);let n=await i(`frame`,{params:{id:t,ref:e}});return Lb(e,new Uint8Array(await n.arrayBuffer()))}},outputs:{async list(e){return[...(await a(await i(`outputs`,{params:{id:e}}))).outputs].sort((e,t)=>t.renderedAt.localeCompare(e.renderedAt)).map(nx)}},logos:{async put(e){return{ref:(await a(await i(`assetPut`,{raw:e,headers:{[Sb]:encodeURIComponent(e.name),"Content-Type":e.type}}))).ref}},async load(e){let t;try{t=await i(`logo`,{query:{ref:e}})}catch(e){return{ok:!1,error:Zb(e)}}try{let e=new Uint8Array(await t.arrayBuffer()),n=(t.headers.get(`Content-Type`)??``).split(`;`)[0];return{ok:!0,source:await mb(e,n?.trim()??``)}}catch(e){return{ok:!1,error:Zb(e)}}}},wallpapers:{async put(e){let t=cb(e);if(!t.ok)throw new Wb(`wallpaperRefused`,t.reason,400);let n;try{n=await vb(e)}catch(e){throw new Wb(`wallpaperRefused`,Zb(e),400)}return{ref:(await a(await i(`wallpaperPut`,{raw:n.blob,headers:{[Sb]:encodeURIComponent(e.name),"Content-Type":n.blob.type}}))).ref}},async load(e){try{return{ok:!0,blob:await(await i(`wallpaper`,{query:{ref:e}})).blob()}}catch(e){return{ok:!1,error:Zb(e)}}}},kits:te,pullRequests:{async read(){return a(await i(`pullRequestsGet`))},async write(e){let t=await a(await i(`pullRequestsPut`,{json:{value:e}}));return t.replaced===void 0?{}:{replaced:t.replaced}}},exportQuality:{async read(){let e=await a(await i(`exportQualityGet`));return{quality:e.exportQuality,...e.unreadable===void 0?{}:{unreadable:e.unreadable}}},async write(e){let t=await a(await i(`exportQualityPut`,{json:{exportQuality:e}}));return t.replaced===void 0?{}:{replaced:t.replaced}}},exports:{async start(e,{fileType:t,revision:n,quality:r}){if(n===null)throw new Wb(`sceneNotSaved`,`The export was not started: this page has no saved revision of the take to name.`,0);let o={fileType:t,revision:n,...r===void 0?{}:{quality:r}};h+=1;let s=null;try{s=await a(await i(`exportStart`,{params:{id:e},json:o})),m.add(s.jobId)}finally{--h;let e=s?.jobId,t=g.filter(t=>t.jobId===e||h===0);g=g.filter(e=>!t.includes(e));for(let e of t)_(e)}return{jobId:s.jobId}},onEvent(e){return c.add(e),()=>c.delete(e)}},files:{async reveal(e){if(e.kind!==`path`)throw Error(`the Studio shows a file by its path, not a download`);await i(`reveal`,{json:{path:e.path}})}},nav:{editor:e=>`/editor.html?scene=${encodeURIComponent(e)}`,library:()=>`/`,kits:()=>`/settings.html`,firstTakeHint:()=>qb,rerun:e=>{let t=ne.get(e),n=D.get(e);return{kind:`line`,text:t===void 0?n===void 0?Yb:Xb(n):Jb(t)}},onOpen(e){d.add(e)}}}}async function ix(e,t,n){let r=[],i=async e=>{let t=await n(e);return t instanceof Uint8Array||r.push(t),t};try{let n=Kl(e),r=mu(n,t,e,(e.edits.gaps??[]).length>0?await Uy(t,Uu(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 ax(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 ox={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`],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`],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`],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`]},sx=`http://www.w3.org/2000/svg`,cx=new Set([`play`,`pause`,`rewind`,`fastForward`,`skipBack`]);function lx(e){let t=document.createElementNS(sx,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,cx.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 ox[e]){let e=document.createElementNS(sx,`path`);e.setAttribute(`d`,n),t.append(e)}return t}var ux={glyph:`trash`,title:`Delete demo`,body:`This permanently removes the video. It can’t be undone.`,confirmLabel:`Delete`,danger:!0,focus:`cancel`},dx={...ux,title:`Delete recording`,body:`This permanently removes this recording. It can’t be undone.`},fx=e=>({...ux,title:`Delete video`,body:`This permanently removes the video and ${e===1?`its recording`:`its ${e} recordings`}. It can’t be undone.`}),px={...ux,title:`Delete video record`,body:`This removes the unreadable record. Its recordings stay.`},mx=0;function hx(e){mx+=1;let t=`confirm-${mx}`,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(lx(`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(lx(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)}})}export{$l as $,vy as A,qv as B,By as C,Do as Ct,yy as D,by as E,ey as F,cy as G,$v as H,Yv as I,Dv as J,ay as K,Xv as L,gy as M,my as N,wy as O,Qv as P,xu as Q,Zv as R,Uy as S,Oo as St,Py as T,ty as U,Jv as V,Kv as W,vu as X,Uu as Y,hu as Z,sb as _,os as _t,fx as a,Mc as at,Ky as b,ss as bt,ax as c,Xs as ct,Bb as d,zs as dt,Zl as et,Eb as f,qs as ft,mb as g,Qs as gt,hb as h,Ys as ht,hx as i,Lc as it,Sy as j,Oy as k,rx as l,Js as lt,Db as m,Vs as mt,px as n,$c as nt,lx as o,jc as ot,Ob as p,Zs as pt,iy as q,dx as r,zc as rt,ix as s,nc as st,ux as t,Kl as tt,Vb as u,Us as ut,qy as v,as as vt,jy as w,Gy as x,$o as xt,Qy as y,cs as yt,Gv as z};
|