demoman 0.9.7 → 0.9.8

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