@omnimedia/omnitool
Version:
open source video processing tools
7 lines • 340 kB
JavaScript
function ms(t,e){return{error:r=>t.error({...e,...r}),rpcRequest:r=>t.rpcRequest({...e,...r}),rpcError:r=>t.rpcError({...e,...r})}}var Zr=()=>t=>({plain:t.none,errMessage:t.mix(t.brightRed,t.bold),errName:t.red,errStack:t.mix(t.red,t.dim),timestamp:t.blue,timestampErr:t.red});function Cn(){return Zr()}var Ke=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var Jr=()=>({none:t=>t,uncolor:Jo,mix:ec,hex:tc,rgb:_n,bgRgb:rc});function Jo(t){return t.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function ec(...t){return e=>{for(let r of t)e=r(e);return e}}function tc(t){t=t.replace(/^#/,"");let e,r,i,s;if(t.length===3)e=parseInt(t.split("").map(n=>n+n).join(""),16);else if(t.length===6)e=parseInt(t,16);else throw new Error("Invalid hex color");return r=e>>16&255,i=e>>8&255,s=e&255,_n(r,i,s)}function _n(t,e,r){let i=`\x1B[38;2;${t};${e};${r}m`;return s=>`${i}${s}${Ke.reset}`}function rc(t,e,r){let i=`\x1B[48;2;${t};${e};${r}m`;return s=>`${i}${s}${Ke.reset}`}var mr={...Object.fromEntries(Object.entries(Ke).map(([t])=>[t,e=>e])),...Jr()};var pr={...Object.fromEntries(Object.entries(Ke).map(([t,e])=>[t,r=>`${e}${r}${Ke.reset}`])),...Jr()};function ps(){return typeof Deno<"u"&&typeof Deno.version<"u"}function gs(){return typeof process<"u"&&process.versions&&process.versions.node}function Pn(){return gs()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":ps()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var ws=()=>Pn()?pr:mr;var ei=()=>({colors:t,theme:e})=>{let r=e(t);function i(a){let o=a.stack?`
`+a.stack+`
`:"";return[r.errName(a.name+":"),r.errMessage(a.message)].join(" ")+r.errStack(o)}function s(a){return a&&a instanceof Error?i(a):a}function n(a){return a&&a instanceof Error?i(a):r.errMessage(a)}return{stdout:a=>a.map(s),stderr:a=>a.map(n)}};function gr(...t){return e=>({stdout:r=>{for(let i of t)r=i(e).stdout(r);return r},stderr:r=>{for(let i of t)r=i(e).stderr(r);return r}})}function ic(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var ti=t=>({colors:e,theme:r})=>{let i={...ic(),...t},s=r(e),n=new Date(i.now()),a=n.getUTCFullYear().toString().padStart(4,"0"),o=(n.getUTCMonth()+1).toString().padStart(2,"0"),c=n.getUTCDate().toString().padStart(2,"0"),l=`${a}-${o}-${c}`,d=n.getUTCHours().toString().padStart(2,"0"),u=n.getUTCMinutes().toString().padStart(2,"0"),h=n.getUTCSeconds().toString().padStart(2,"0"),f=n.getUTCMilliseconds().toString().padStart(3,"0"),p=`${d}:${u}:${h}.${f}`,g=`${l}::${p}`;return{stdout:w=>[s.timestamp(g),...w],stderr:w=>[s.timestampErr(g),...[i.icon].filter(Boolean),...w]}};function En(){return gr(ei(),ti())}var ri=()=>({stdout:async t=>{await Deno.stdout.write(new TextEncoder().encode(t+`
`))},stderr:async t=>{await Deno.stderr.write(new TextEncoder().encode(t+`
`))}});var ii=()=>({stdout:async t=>{process.stdout.write(t+`
`)},stderr:async t=>{process.stderr.write(t+`
`)}});var si=()=>({stdout:async t=>console.log(t),stderr:async t=>console.error(t)});var In=()=>ps()?ri():gs()?ii():si();var vn=()=>({stdout:async()=>{},stderr:async()=>{}});function An(){return()=>({stdout:t=>t,stderr:t=>t})}var Rt=class t{static writers={auto:In,void:vn,deno:ri,node:ii,console:si};static colors={auto:ws,colorful:()=>pr,colorless:()=>mr};static themes={auto:Cn,basic:Zr};static shapers={auto:En,none:An,errors:ei,timestamp:ti};writer=t.writers.auto();colors=t.colors.auto();theme=t.themes.auto();shaper=t.shapers.auto();async log(...e){await this.writer.stdout(this.shaper(this).stdout(e).join(" "))}async error(...e){await this.writer.stderr(this.shaper(this).stderr(e).join(" "))}setWriter(e){return this.writer=e,this}setColors(e){return this.colors=e,this}setTheme(e){return this.theme=e,this}setShaper(...e){return this.shaper=gr(...e),this}};var wr=class extends Rt{static dummy(){return new this().setWriter(Rt.writers.void())}rpcRequest=async({request:e,...r})=>{let i=this.colors.none;this.log(...this.#e(r),i(`${e.method}()`))};rpcError=async({request:e,error:r,...i})=>{this.error(...this.#e(i),`${e.method}()`,r)};#e({meta:e,label:r,remote:i}){let s=this.colors.mix(this.colors.blue,this.colors.dim),n=this.colors.mix(this.colors.cyan,this.colors.dim);return[e?this.#t(e):void 0,r||void 0,i===void 0?void 0:i?s("<-"):n("->")].filter(Boolean)}#t(e){let{headers:r}=e.request;return[this.colors.yellow(`[${e.ip}]`),this.colors.green(r.origin?r.origin:"(no-origin)")].join(" ")}};var Pe=class extends wr{rpcRequest=async()=>{}};function Ee(){let t,e,r=new Promise((s,n)=>{t=s,e=n});function i(s){return s.then(t).catch(e),r}return{promise:r,resolve:t,reject:e,entangle:i}}var Fn=Object.freeze({happy:t=>t!=null,sad:t=>t==null,boolean:t=>typeof t=="boolean",number:t=>typeof t=="number",string:t=>typeof t=="string",bigint:t=>typeof t=="bigint",object:t=>typeof t=="object"&&t!==null,array:t=>Array.isArray(t),fn:t=>typeof t=="function",symbol:t=>typeof t=="symbol"});var br=class extends Error{milliseconds;name=this.constructor.name;constructor(e){super(`deadline exceeded (${(e/1e3).toFixed(1)} seconds)`),this.milliseconds=e}};function Rn(t,e){return t<=0||t===1/0?e():new Promise((r,i)=>{let s=setTimeout(()=>i(new br(t)),t);e().then(r).catch(i).finally(()=>clearTimeout(s))})}function ni(){let t=[];function e(){for(let r of t)r();t=[]}return e.schedule=(...r)=>(t.push(...r),e),e}function Bn(t,e){let r=t;for(let i of e)if(r=r[i],Fn.sad(r))break;return r}function sc(){let t=new Set;async function e(...c){await Promise.all([...t].map(l=>l(...c)))}function r(c){return t.add(c),()=>{t.delete(c)}}async function i(...c){return e(...c)}function s(c){return r(c)}async function n(c){let{promise:l,resolve:d}=Ee(),u=s(async(...h)=>{c&&await c(...h),d(h),u()});return l}function a(){t.clear()}let o={pub:i,sub:s,publish:e,subscribe:r,on:r,next:n,clear:a};return Object.assign(s,o),Object.assign(i,o),o}function ai(t){let e=sc();return t&&e.sub(t),e.pub}var De;(function(t){t.version="2.0";function e(r){return"id"in r?r.id:null}t.getId=e,t.errorCodes={serverError:-32e3,unexposedError:-32001}})(De||(De={}));var oi=class extends Error{name=this.constructor.name},at=class extends Error{name=this.constructor.name};async function Dn({tap:t,request:e,action:r}){let i=De.getId(e);try{let s=await r();return i===null?null:{id:i,result:s,jsonrpc:De.version}}catch(s){return t.rpcError({request:e,error:s}),i===null?null:{id:i,jsonrpc:De.version,error:s instanceof oi?{code:De.errorCodes.serverError,message:s.message}:{code:De.errorCodes.unexposedError,message:"unexposed error"}}}}function ci(t){let e=t.tap??new Pe;return async r=>{let i=r.method.split("."),s=Bn(t.fns,i),n=async()=>await s(...r.params);return e.rpcRequest({request:r}),await Dn({tap:e,request:r,action:n})}}var On=Symbol("tune"),nc=Symbol("query"),ac=Symbol("notify"),oc=Symbol("settings");function zn(t){function e(r){let i={notify:void 0};return new Proxy((()=>{}),{apply:(s,n,a)=>t(r,a,i),get:(s,n)=>{if(n!=="then")return n===On?a=>(...o)=>t(r,o,{...i,...a}):n===ac?(...a)=>t(r,a,{...i,notify:!0}):n===nc?(...a)=>t(r,a,{...i,notify:!1}):n===oc?i:(s[n]||(s[n]=e([...r,n])),s[n])},set:(s,n,a)=>(s[n]=a,!0)})}return e([])}function ot(t){let{endpoint:e,tap:r=new Pe}=t,i=1;return zn(async(s,n,a)=>{let o=a.notify??t.notify??!1,c=a.transfer,l={jsonrpc:"2.0",method:s.join("."),params:n},d=o?l:{...l,id:i++};r.rpcRequest({request:d});let u=await e(d,{transfer:c});if(o&&!u)return null;if(!u)throw new at("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new at(t.label?`${t.label}: ${u.error.message}`:u.error.message);return u.result})}function kr(t){return ot({endpoint:ci(t),tap:t.tap})}var ct=class{recv=ai();sendRequest=ai();sendResponse=ai();static makeEntangledPair({origin:e="example.e280.org"}={}){let r=new this,i=new this,s=[r.sendRequest.sub(a=>i.recv(a,{origin:e})),r.sendResponse.sub(a=>i.recv(a,{origin:e})),i.sendRequest.sub(a=>r.recv(a,{origin:e})),i.sendResponse.sub(a=>r.recv(a,{origin:e}))];return[r,i,()=>s.forEach(a=>a())]}};function li(t,e){return t.addEventListener("message",e),()=>t.removeEventListener("message",e)}function Mn(t,e){return async(r,{transfer:i}={})=>{if("id"in r){let s=Ee();return e(r,i,s.promise),t.wait(r.id,r.method).then(n=>(s.resolve(n),n))}else{let s=Promise.resolve(null);return e(r,i,s),s}}}function Un(t){let e=[],r=[];for(let i of Array.isArray(t)?t:[t])"method"in i?e.push(i):r.push(i);return{requests:e,responses:r}}async function Nn(t,e){let r=(await Promise.all(e.map(async i=>t(i)))).filter(i=>i!==null);return r.length===0?null:r.length===1?r[0]:r}var Bt=class extends ct{dispose=ni();constructor(e){super(),this.dispose.schedule(this.sendRequest.sub((r,i)=>e.postMessage(r,i)),this.sendResponse.sub((r,i)=>e.postMessage(r,i)),li(e,r=>this.recv(r.data,r)))}};var ui=class{remote;transfer;constructor(e){this.remote=e}};var bs=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var di=class{timeout;pending=new Map;constructor(e){this.timeout=e}async wait(e,r){let i=Ee();return this.pending.set(e,{method:r,deferred:i}),await Rn(this.timeout,()=>i.promise).catch(s=>{throw s instanceof br&&(s.message=`request #${e} ${r}(), ${s.message}`),s})}deliverResponse(e){let r=this.pending.get(e.id);r&&("error"in e?r.deferred.reject(new at(e.error.message)):r.deferred.resolve(e))}};var lt=class{options;remote;remoteEndpoint;dispose=ni();#e;constructor(e){this.options=e;let{conduit:r,tap:i}=e;this.#e=new di(e.timeout??bs.timeout),this.remoteEndpoint=Mn(this.#e,r.sendRequest.pub.bind(r.sendRequest)),this.remote=ot({endpoint:this.remoteEndpoint,tap:i&&ms(i,{remote:!0})}),this.dispose.schedule(r.recv.sub(s=>this.recv(s)))}async recv(e){let r=new ui(this.remote),{conduit:i,rpc:s,tap:n}=this.options,{requests:a,responses:o}=Un(e);for(let u of o)this.#e.deliverResponse(u);if(!s)return;let c=await s(r),l=ci({fns:c,tap:n&&ms(n,{remote:!1})}),d=await Nn(l,a);d&&await i.sendResponse(d,r.transfer)}};var Oe={derive:{host:t=>({host:t.remote.host,get transfer(){return t.transfer},set transfer(e){t.transfer=e}}),work:t=>({work:t.remote,get transfer(){return t.transfer},set transfer(e){t.transfer=e}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var ze=new Pe;async function Vn(t,e,r={}){let i=r.tap??ze,s=new lt({tap:i,timeout:r.timeout??1/0,conduit:new Bt(t.getSelf()),rpc:async n=>e(Oe.derive.host(n))});return await s.remote.infra.ready(),s.remote.host}var Dt=class{worker;messenger;constructor(e,r){this.worker=e,this.messenger=r}static async make(e,r){let i=r.tap??ze,s=r.label??"comrade",n=e.loadWorker(r.workerUrl,s),a=Ee(),o={async ready(){a.resolve()}},c=new lt({tap:i,timeout:r.timeout??1/0,conduit:new Bt(n),rpc:async l=>({infra:o,host:r.setupHost(Oe.derive.work(l))})});return await a.promise,new this(n,c)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var hi=class{threads;static async make(e,r){let i=r.workerCount??e.guessOptimalThreadCount(),s=await Promise.all([...Array(i)].map(async(n,a)=>Dt.make(e,{...r,label:r.label??`${r.label??"comrade"}_${a+1}`})));return new this(s,{tap:r.tap})}work;#e=new Set;#t=[];constructor(e,r={}){this.threads=e;let i=r.tap??ze,s=async(n,a)=>this.#i({request:n,prom:Ee(),transfer:a?.transfer});this.work=ot({tap:i,endpoint:s}),e.forEach(n=>this.#e.add(n))}get threadCount(){return this.threads.length}terminate(){for(let e of this.threads)e.terminate()}#i(e){return this.#t.push(e),this.#r(),e.prom.promise}#r(){for(;this.#e.size>0&&this.#t.length>0;){let e=[...this.#e].pop();this.#e.delete(e);let r=this.#t.shift();this.#e.delete(e);let i=e.messenger.remoteEndpoint(r.request,{transfer:r.transfer});r.prom.entangle(i).finally(()=>{this.#e.add(e),this.#r()})}}};var Ln=t=>({thread:e=>Dt.make(t,e),cluster:e=>hi.make(t,e),worker:(e,r={})=>Vn(t,e,r),work:e=>e,host:e=>e,mocks(e){let{setupWork:r,setupHost:i,tap:s=ze}=e,n=Oe.mock.host(),a=Oe.mock.work();return a.work=kr({tap:s,fns:r(n)}),n.host=kr({tap:s,fns:i(a)}),{workShell:a,hostShell:n,work:a.work,host:n.host}},mockWork(e,r=ze){let i=Oe.mock.host(),s=Oe.mock.work();return s.work=kr({tap:r,fns:e(i)}),{workShell:s,hostShell:i,work:s.work,mockHost:n=>(i.host=kr({tap:r,fns:n(s)}),{workShell:s,hostShell:i,work:s.work,host:i.host})}}});var Wn=()=>({getSelf(){return self},guessOptimalThreadCount(){let t=navigator.hardwareConcurrency??1;return Math.max(1,t-1)},loadWorker(t,e){return new window.Worker(t,{name:e,type:"module"})},async loadWasm(t){return WebAssembly.instantiateStreaming(fetch(t))}});var uc=Wn(),fi=Ln(uc);function m(t){if(!t)throw new Error("Assertion failed.")}var mi=t=>{let e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},q=t=>t&&t[t.length-1],ut=t=>t>=0&&t<2**32,H=class t{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),s=(r&1<<i)>>i;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let i=this.pos+e;for(let s=this.pos;s<i;s++){let n=Math.floor(s/8),a=this.bytes[n],o=7-(s&7);a&=~(1<<o),a|=(r&1<<i-s-1)>>i-s-1<<o,this.bytes[n]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}},I=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},Ie=t=>{let e=I(t);return(e&1)===0?-(e>>1):e+1>>1};var K=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),V=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),ie=new TextDecoder,ue=new TextEncoder;var Ss=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),dt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},pi=Ss(dt),ht={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},gi=Ss(ht),ft={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},wi=Ss(ft),qn=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,Ot=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),le=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,r=new Promise(s=>{e=s}),i=this.currentPromise;return this.currentPromise=r,await i,e}},Cs=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),_s=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),mt=(t,e,r)=>{let i=0,s=t.length-1,n=-1;for(;i<=s;){let a=i+s>>1,o=r(t[a]);o===e?(n=a,s=a-1):o<e?i=a+1:s=a-1}return n},M=(t,e,r)=>{let i=0,s=t.length-1,n=-1;for(;i<=s;){let a=i+(s-i+1)/2|0;r(t[a])<=e?(n=a,i=a+1):s=a-1}return n},Ps=(t,e,r)=>{let i=M(t,r(e),r);t.splice(i+1,0,e)},se=()=>{let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}};var Es=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return t[r]},bi=(t,e)=>{for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1},jn=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},$n=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},ne=t=>{throw new Error(`Unexpected value: ${t}`)},pt=(t,e,r)=>{let i=t.getUint8(e),s=t.getUint8(e+1),n=t.getUint8(e+2);return r?i|s<<8|n<<16:i<<16|s<<8|n},Qn=(t,e,r)=>pt(t,e,r)<<8>>8,yr=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},Gn=(t,e,r,i)=>{r=X(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),yr(t,e,r,i)};var X=(t,e,r)=>Math.max(e,Math.min(r,t)),G="und",gt=t=>{let e=Math.round(t);return Math.abs(t/e-1)<10*Number.EPSILON?e:t},Kn=(t,e)=>Math.round(t/e)*e,Xn=t=>{let e=0;for(;t;)e++,t>>=1;return e},dc=/^[a-z]{3}$/,zt=t=>dc.test(t),ve=1e6*(1+Number.EPSILON),Is=(t,e)=>{let r={...t,...e};if(t.headers||e.headers){let i=t.headers?Hn(t.headers):{},s=e.headers?Hn(e.headers):{},n={...i};Object.entries(s).forEach(([a,o])=>{let c=Object.keys(n).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),r.headers=n}return r},Hn=t=>{if(t instanceof Headers){let e={};return t.forEach((r,i)=>{e[i]=r}),e}if(Array.isArray(t)){let e={};return t.forEach(([r,i])=>{e[r]=i}),e}return t},vs=async(t,e,r,i,s)=>{let n=0;for(;;)try{return await t(e,r)}catch(a){if(s())throw a;n++;let o=i(n,a,e);if(o===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await new Promise(c=>setTimeout(c,1e3*o)),s())throw a}},Yn=(t,e)=>{let r=t<0?-1:1;t=Math.abs(t);let i=0,s=1,n=1,a=0,o=t;for(;;){let c=Math.floor(o),l=c*n+i,d=c*a+s;if(d>e)return{numerator:r*n,denominator:a};if(i=n,s=a,n=l,a=d,o=1/(o-c),!isFinite(o))break}return{numerator:r*n,denominator:a}},Xe=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},ks=null,Ye=()=>ks!==null?ks:ks=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ys=null,Mt=()=>ys!==null?ys:ys=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Ts=null,Tr=()=>Ts!==null?Ts:Ts=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),xs=null,Zn=()=>{if(xs!==null)return xs;if(typeof navigator>"u")return null;let t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?xs=Number(t[1]):null},wt=(t,e)=>t!==-1?t:e,ki=(t,e,r,i)=>t<=i&&r<=e,xr=function*(t){for(let e in t){let r=t[e];r!==void 0&&(yield{key:e,value:r})}};var Jn=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return r};var yi=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Sr=t=>typeof t=="number"&&!Number.isNaN(t);var ke=class{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}},Cr=class{constructor(e,r,i,s){if(this.data=e,this.mimeType=r,this.name=i,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}},ea=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof ke)&&!(e instanceof Cr))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}};var de={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},ta=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var Ae=["avc","hevc","vp9","av1","vp8"],Q=["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"],As=["aac","opus","mp3","vorbis","flac"],Ue=[...As,...Q],bt=["webvtt"],ra=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],ia=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Me=[{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}],sa=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],na=".01.01.01.01.00",aa=".0.110.01.01.01.0",oa=(t,e,r,i)=>{if(t==="avc"){let n=Math.ceil(e/16)*Math.ceil(r/16),a=ra.find(u=>n<=u.maxMacroblocks&&i<=u.maxBitrate)??q(ra),o=a?a.level:0,c="64".padStart(2,"0"),l="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${d}`}else if(t==="hevc"){let o=e*r,c=ia.find(d=>o<=d.maxPictureSize&&i<=d.maxBitrate)??q(ia);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){let n=e*r;return`vp09.00.${(Me.find(c=>n<=c.maxPictureSize&&i<=c.maxBitrate)??q(Me)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){let n=e*r,a=sa.find(l=>n<=l.maxPictureSize&&i<=l.maxBitrate)??q(sa);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)};var ca=t=>{let e=t.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,l=a.slice(-1)==="H"?1:0,u=Number(e[3])===8?0:1,h=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,b=(l<<7)+(u<<6)+(h<<5)+(f<<4)+(p<<3)+(g<<2)+w;return[s,c,b,0]},Ti=t=>{let{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o}=t;if(e==="avc"){if(m(t.avcType!==null),s){let c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${t.avcType}.${Cs(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Cs(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,u,h,f;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,d=_s(n.generalProfileCompatibilityFlags),u=n.generalTierFlag,h=n.generalLevelIdc,f=[...n.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let g=V(r),w=g.getUint8(1);c=w>>6&3,l=w&31,d=_s(g.getUint32(2)),u=w>>5&1,h=g.getUint8(12),f=[];for(let b=0;b<6;b++)f.push(g.getUint8(6+b))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=u===0?"L":"H",p+=h;f.length>0&&f[f.length-1]===0;)f.pop();return f.length>0&&(p+=".",p+=f.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let b=t.width*t.height,k=q(Me).level;for(let y of Me)if(b<=y.maxPictureSize){k=y.level;break}return`vp09.00.${k.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),u=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),f=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),g=a.videoFullRangeFlag.toString().padStart(2,"0"),w=`vp09.${c}.${l}.${d}.${u}`;return w+=`.${h}.${f}.${p}.${g}`,w.endsWith(na)&&(w=w.slice(0,-na.length)),w}else if(e==="av1"){if(!o){let y=t.width*t.height,x=q(Me).level;for(let P of Me)if(y<=P.maxPictureSize){x=P.level;break}return`av01.0.${x.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",u=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",f=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=i?.primaries?dt[i.primaries]:1,g=i?.transfer?ht[i.transfer]:1,w=i?.matrix?ft[i.matrix]:1,b=i?.fullRange?1:0,k=`av01.${c}.${l}${d}.${u}`;return k+=`.${h}.${f.toString().padStart(3,"0")}`,k+=`.${p.toString().padStart(2,"0")}`,k+=`.${g.toString().padStart(2,"0")}`,k+=`.${w.toString().padStart(2,"0")}`,k+=`.${b}`,k.endsWith(aa)&&(k=k.slice(0,-aa.length)),k}}throw new TypeError(`Unhandled codec '${e}'.`)},la=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(Q.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},xi=t=>{let{codec:e,codecDescription:r,aacCodecInfo:i}=t;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":`mp4a.40.${_r(r).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Q.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Ut=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Si=[-1,1,2,3,4,5,6,8],_r=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new H(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let i=e.readBits(4),s=null;i===15?s=e.readBits(24):i<Ut.length&&(s=Ut[i]);let n=e.readBits(4),a=null;return n>=1&&n<=7&&(a=Si[n]),{objectType:r,frequencyIndex:i,sampleRate:s,channelConfiguration:n,numberOfChannels:a}},ua=t=>{let e=Ut.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);let i=Si.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let s=13;t.objectType>=32&&(s+=6),e===15&&(s+=24);let n=Math.ceil(s/8),a=new Uint8Array(n),o=new H(a);return t.objectType<32?o.writeBits(5,t.objectType):(o.writeBits(5,31),o.writeBits(6,t.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,r),o.writeBits(4,i),a},kt=48e3,da=/^pcm-([usf])(\d+)+(be)?$/,fe=t=>{if(m(Q.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=da.exec(t);m(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";let i=Number(e[2])/8,s=e[3]!=="be",n=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:s,silentValue:n}},Fs=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":da.test(t)?t:t==="webvtt"?"webvtt":null,ha=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},fa=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},hc=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],fc=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,mc=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,pc=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,gc=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ma=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!hc.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!Ot(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(dt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let i=Object.keys(ht);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let s=Object.keys(ft);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!fc.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!mc.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!pc.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")&&!gc.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},wc=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],pa=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!wc.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!Ot(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Q.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Q.join(", ")}).`)},ga=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Ci=class{constructor(e){this.mutex=new le,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let s=this.trackTimestampInfo.get(e);if(!s){if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,s)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),r<s.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${s.maxTimestampBeforeLastKeyPacket}s.`);return s.maxTimestamp=Math.max(s.maxTimestamp,r),r}};var yt;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(yt||(yt={}));var ce;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ce||(ce={}));var Nt=t=>{let e=[],r=0;for(;r<t.length;){let i=-1,s=0;for(let n=r;n<t.length-3;n++){if(t[n]===0&&t[n+1]===0&&t[n+2]===1){i=n,s=3;break}if(n<t.length-4&&t[n]===0&&t[n+1]===0&&t[n+2]===0&&t[n+3]===1){i=n,s=4;break}}if(i===-1)break;if(r>0&&i>r){let n=t.subarray(r,i);n.length>0&&e.push(n)}r=i+s}if(r<t.length){let i=t.subarray(r);i.length>0&&e.push(i)}return e},ba=(t,e)=>{let r=[],i=0,s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let n;e===1?n=s.getUint8(i):e===2?n=s.getUint16(i,!1):e===3?n=pt(s,i,!1):e===4?n=s.getUint32(i,!1):(ne(e),m(!1)),i+=e;let a=t.subarray(i,i+n);r.push(a),i+=n}return r},_i=t=>{let e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},Rs=new Uint8Array([0,0,0,1]),bc=t=>{let e=t.reduce((s,n)=>s+Rs.byteLength+n.byteLength,0),r=new Uint8Array(e),i=0;for(let s of t)r.set(Rs,i),i+=Rs.byteLength,r.set(s,i),i+=s.byteLength;return r},Bs=(t,e)=>{let r=t.reduce((n,a)=>n+e+a.byteLength,0),i=new Uint8Array(r),s=0;for(let n of t){let a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:yr(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,i.set(n,s),s+=n.byteLength}return i},Ds=(t,e)=>{if(e.description){let s=(K(e.description)[4]&3)+1;return ba(t,s)}else return Nt(t)},ka=(t,e)=>{if(e.description){let s=(K(e.description)[4]&3)+1;return Bs(t,s)}else return bc(t)},Tt=t=>t[0]&31,Pi=t=>{try{let e=Nt(t),r=e.filter(c=>Tt(c)===yt.SPS),i=e.filter(c=>Tt(c)===yt.PPS),s=e.filter(c=>Tt(c)===yt.SPS_EXT);if(r.length===0||i.length===0)return null;let n=r[0],a=Os(n);m(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:r,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?s:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},ya=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){m(t.chromaFormat!==null),m(t.bitDepthLumaMinus8!==null),m(t.bitDepthChromaMinus8!==null),m(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(r[s])}}return new Uint8Array(e)},Ta=t=>{try{let e=V(t),r=0,i=e.getUint8(r++),s=e.getUint8(r++),n=e.getUint8(r++),a=e.getUint8(r++),o=e.getUint8(r++)&3,c=e.getUint8(r++)&31,l=[];for(let f=0;f<c;f++){let p=e.getUint16(r,!1);r+=2,l.push(t.subarray(r,r+p)),r+=p}let d=e.getUint8(r++),u=[];for(let f=0;f<d;f++){let p=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+p)),r+=p}let h={configurationVersion:i,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&r+4<=t.length){let f=e.getUint8(r++)&3,p=e.getUint8(r++)&7,g=e.getUint8(r++)&7,w=e.getUint8(r++);h.chromaFormat=f,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=g;let b=[];for(let k=0;k<w;k++){let y=e.getUint16(r,!1);r+=2,b.push(t.subarray(r,r+y)),r+=y}h.sequenceParameterSetExt=b}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Os=t=>{try{let e=new H(_i(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();I(e);let a=null,o=null,c=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=I(e),a===3&&e.skipBits(1),o=I(e),c=I(e),e.skipBits(1),e.readBits(1))){for(let h=0;h<(a!==3?8:12);h++)if(e.readBits(1)){let p=h<6?16:64,g=8,w=8;for(let b=0;b<p;b++){if(w!==0){let k=Ie(e);w=(g+k+256)%256}g=w===0?g:w}}}I(e);let l=I(e);if(l===0)I(e);else if(l===1){e.skipBits(1),Ie(e),Ie(e);let u=I(e);for(let h=0;h<u;h++)Ie(e)}I(e),e.skipBits(1),I(e),I(e);let d=e.readBits(1);return{profileIdc:i,constraintFlags:s,levelIdc:n,frameMbsOnlyFlag:d,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},zs=(t,e)=>{if(e.description){let s=(K(e.description)[21]&3)+1;return ba(t,s)}else return Nt(t)},Ne=t=>t[0]>>1&63,Ei=t=>{try{let e=Nt(t),r=e.filter(N=>Ne(N)===ce.VPS_NUT),i=e.filter(N=>Ne(N)===ce.SPS_NUT),s=e.filter(N=>Ne(N)===ce.PPS_NUT),n=e.filter(N=>Ne(N)===ce.PREFIX_SEI_NUT||Ne(N)===ce.SUFFIX_SEI_NUT);if(i.length===0||s.length===0)return null;let a=i[0],o=new H(_i(a));o.skipBits(16),o.readBits(4);let c=o.readBits(3),l=o.readBits(1),{general_profile_space:d,general_tier_flag:u,general_profile_idc:h,general_profile_compatibility_flags:f,general_constraint_indicator_flags:p,general_level_idc:g}=kc(o,c);I(o);l