UNPKG

@diffusionstudio/core-v4

Version:

A fast, browser based video compositing engine powered by WebCodecs

11 lines (9 loc) 480 kB
/*! * @diffusionstudio/core-v4 v4.0.2 * Copyright (c) 2025 Diffusion Studio Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ class e{toJSON(e){const t={},i=this.constructor.__serializableProperties||[],r=this.constructor.__displayName;r&&(t.displayName=r);const a=e=>{if(null==e||e instanceof Blob||e instanceof FileSystemFileHandle)return e;if(Array.isArray(e))return e.map(e=>a(e)).filter(e=>void 0!==e);if("object"==typeof e&&"toJSON"in e)return e.toJSON();if("object"==typeof e){const t={};for(const i in e){const r=a(e[i]);void 0!==r&&(t[i]=r)}return t}return e};return i.forEach(({propertyKey:i,mapTo:r})=>{if(e?.includes(i))return;const s=this[i],n=r??i,o=a(s);void 0!==o&&(t[n]=o)}),t}fromJSON(e){return(this.constructor.__serializableProperties||[]).forEach(({propertyKey:t,deserializer:i,mapTo:r})=>{const a=r??t,s=i.fromJSON?.bind(i)??(e=>e);if(e.hasOwnProperty(a))try{this[t]=s(e[a])}catch(n){console.error(`Error deserializing property ${t}:`,n)}}),this}static fromJSON(e){return(new this).fromJSON(e)}}function t(e={},t){return function(i,r){const a=i.constructor;a.__serializableProperties||(a.__serializableProperties=[]),a.__serializableProperties=[...a.__serializableProperties.filter(e=>e.propertyKey!==r),{propertyKey:r,deserializer:e,mapTo:t}]}}function i(e){return function(t){t.__displayName=e}}function r(e){return Math.floor(255*e).toString(16).padStart(2,"0").toUpperCase()}function a(e,t){return e.reduce((e,i)=>{const r=i[t];return e[r]||(e[r]=[]),e[r].push(i),e},{})}function s(e,t){return[e.slice(0,t),e.slice(t)].filter(e=>e.length>0)}function n(e,t){return t?Math.floor(Math.random()*(t-e+1)+e):e}async function o(e){e<=0||await new Promise(t=>setTimeout(t,e))}function c(e,t=300){let i;return(...r)=>{clearTimeout(i),i=setTimeout(()=>{e.apply(e,r)},t)}}function l(e,t,i){i<0&&(i=0);const r=e[t];e.splice(t,1),e.splice(i,0,r)}function h(e){return e.charAt(0).toUpperCase()+e.slice(1)}function d(e,t,i){return Math.max(t,Math.min(i,e))}function u(e){throw new Error("This should not run!")}function m(e,t="Unknown error"){if(!e)throw new Error(`Assertion failed: ${t}`)}let p=class{currentPromise=Promise.resolve();async acquire(){let e;const t=new Promise(t=>{e=t}),i=this.currentPromise;return this.currentPromise=t,await i,e}};const f=(e,t,i)=>{let r=-1,a=0,s=e.length-1;for(;a<=s;){const n=a+(s-a+1)/2|0;i(e[n])<=t?(r=n,a=n+1):s=n-1}return r};function g(e){if(1===e.numberOfChannels)return e.getChannelData(0);const t=[];for(let n=0;n<e.numberOfChannels;n++)t.push(e.getChannelData(n));const i=Math.max(...t.map(e=>e.length)),r=new Float32Array(i*e.numberOfChannels);let a=0,s=0;for(;s<i;)t.forEach(e=>{r[a++]=void 0!==e[s]?e[s]:0}),s++;return r}function k(e,t,i){for(let r=0;r<i.length;r++)e.setUint8(t+r,i.charCodeAt(r))}function y(e,t,i){for(let r=0;r<t.length;r++,i+=2){const a=Math.max(-1,Math.min(1,t[r]));e.setInt16(i,a<0?32768*a:32767*a,!0)}return e}function w(e,t="audio/wav"){const i=function(e,t,i){const r=2*t,a=2*e.length,s=36+a,n=new ArrayBuffer(8+s),o=new DataView(n);return k(o,0,"RIFF"),o.setUint32(4,s,!0),k(o,8,"WAVE"),k(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,t,!0),o.setUint32(24,i,!0),o.setUint32(28,i*r,!0),o.setUint16(32,r,!0),o.setUint16(34,16,!0),k(o,36,"data"),o.setUint32(40,a,!0),y(o,e,44)}(g(e),e.numberOfChannels,e.sampleRate);return new Blob([i.buffer],{type:t})}function b(e){const t=new Float32Array(e.length*e.numberOfChannels);let i=0;for(let r=0;r<e.numberOfChannels;r++){const a=e.getChannelData(r);t.set(a,i),i+=a.length}return t}function T(e){const t=e.numberOfChannels,i=e.length,r=new Int16Array(i*t);for(let a=0;a<i;a++)for(let i=0;i<t;i++){let s=32767*e.getChannelData(i)[a];s>32767&&(s=32767),s<-32767&&(s=-32767),r[a*t+i]=s}return r}async function C(e,t=22050,i=Math.sqrt(2)){const r=await e.arrayBuffer(),a=new OfflineAudioContext({sampleRate:t,length:1}),s=await a.decodeAudioData(r),n=a.createBuffer(1,s.length,t);if(s.numberOfChannels>=2){const e=s.getChannelData(0),t=s.getChannelData(1),r=n.getChannelData(0);for(let a=0;a<s.length;++a)r[a]=i*(e[a]+t[a])/2;return n}return s}function S(e,t=44100,i=2){if(e.sampleRate==t&&e.numberOfChannels==i)return e;const r=Math.floor(e.duration*t),a=new OfflineAudioContext(i,1,t).createBuffer(i,r,t);for(let s=0;s<e.numberOfChannels;s++){const i=e.getChannelData(s),r=a.getChannelData(s),n=e.sampleRate/t;for(let e=0;e<r.length;e++){const t=e*n,a=Math.floor(t),s=Math.ceil(t);if(s>=i.length)r[e]=i[a];else{const n=t-a;r[e]=i[a]*(1-n)+i[s]*n}}}return a}function v(e){return{"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/bmp":".bmp","image/tiff":".tiff","image/x-icon":".ico","image/vnd.microsoft.icon":".ico","image/avif":".avif","image/heic":".heic","image/heif":".heif","application/pdf":".pdf","text/plain":".txt","audio/mpeg":".mp3","audio/mp3":".mp3","audio/wav":".wav","audio/wave":".wav","audio/x-wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/m4a":".m4a","audio/flac":".flac","audio/webm":".webm","video/mp4":".mp4","video/mpeg":".mpeg","video/quicktime":".mov","video/x-msvideo":".avi","video/webm":".webm","video/ogg":".ogv","video/3gpp":".3gp","video/x-flv":".flv","video/x-ms-wmv":".wmv","text/html":".html","application/json":".json","text/xml":".xml","application/xml":".xml"}[e.toLowerCase().trim().split(";")[0].trim()]||".bin"}async function x(e,t){const i=document.createElement("a");if(document.head.appendChild(i),i.target="_blank",t&&!t.match(/\.[^.]+$/))if(e instanceof File)t+=v(e.type);else if(e instanceof FileSystemFileHandle){t+=v((await e.getFile()).type)}if(t?i.download=t:e instanceof File?i.download=e.name:e instanceof Blob?i.download="untitled":"string"==typeof e&&(i.download=e.split("/").pop()??"untitled"),"string"==typeof e&&e.startsWith("data:image/svg+xml;base64,")){const r=e.split(",")[1],a=atob(r),s=new Array(a.length);for(let e=0;e<a.length;e++)s[e]=a.charCodeAt(e);const n=new Uint8Array(s),o=new Blob([n],{type:"image/svg+xml"});i.href=URL.createObjectURL(o),i.download=t?.split(".")[0]+".svg"}else"string"==typeof e?i.href=e:e instanceof Blob?i.href=URL.createObjectURL(e):i.href=URL.createObjectURL(await e.getFile());i.click(),i.remove()}async function P(e="image/*,video/*,audio/*,text/*",t=!0){try{return"showOpenFilePicker"in window?await window.showOpenFilePicker({multiple:t,startIn:"downloads"}):new Promise(i=>{const r=document.createElement("input");r.type="file",r.accept=e,r.multiple=t,r.onchange=e=>{const t=Array.from(e.target?.files??[]);i(t)},r.click()})}catch(i){return[]}}const E=.2,I=1;let _=30,A=48e3;const B={set experimental_timeBase(e){_=e},set experimental_canonicalTimeBase(e){A=e}};function F(e){return Math.round(e*_)}function M(e){return Math.round(e*A)/A}function D(e){if(!e)return 0;if("number"==typeof e)return M(F(e)/_);const t=e.split(":");if(3===t.length){const[i,r,a]=t.map(Number);if(isNaN(i)||isNaN(r)||isNaN(a))throw new Error(`Invalid time format: ${e}`);return M(F(3600*i+60*r+a)/_)}if(2===t.length){const[i,r]=t.map(Number);if(isNaN(i)||isNaN(r))throw new Error(`Invalid time format: ${e}`);return M(F(60*i+r)/_)}if(e.includes("/")){const[t,i]=e.split("/").map(Number);if(isNaN(t)||isNaN(i))throw new Error(`Invalid time format: ${e}`);return M(t/i)}if("string"==typeof e){const t=parseFloat(e);if(isNaN(t))throw new Error(`Invalid time format: ${e}`);if(e.endsWith("ms"))return M(F(t/1e3)/_);if(e.endsWith("s"))return M(F(t)/_);if(e.endsWith("f"))return M(t/_);if(e.endsWith("min"))return M(F(60*t)/_);throw new Error(`Invalid time format: ${e}`)}throw new Error(`Invalid time format: ${e}`)}function O(e){const t=[];for(const i of e){const e={id:i.id,mimeType:i.mimeType,input:i.input};for(const[t,r]of Object.entries(i))"function"!=typeof r&&"symbol"!=typeof r&&"object"!=typeof r&&(e[t]=r);t.push(e)}return JSON.parse(JSON.stringify(t))}const R={fromJSON:e=>new Date(e)};function z(e){let t=1,i="";const r=e=>{const t=new Date(1970,0,1);return t.setSeconds(e),t.setMilliseconds(Math.round(e%1*1e3)),`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")},`+t.getMilliseconds().toString().padStart(3,"0")};for(const a of e){const e=a.words.join(" "),s=a.words.at(0)?.start,n=a.words.at(-1)?.end;s&&n&&(i+=`${t}\n`+r(s)+" --\x3e "+r(n)+`\n${e}\n\n`,t+=1)}return{text:i,blob:new Blob([i],{type:"text/plain;charset=utf8"})}}var N=Object.defineProperty,U=Object.getOwnPropertyDescriptor,L=(e,t,i,r)=>{for(var a,s=r>1?void 0:r?U(t,i):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(r?a(t,i,s):a(s))||s);return r&&s&&N(t,i,s),s};class V extends e{_background="#000000";canvas=document.createElement("canvas");videoCtx=this.canvas.getContext("2d");resolution=1;width=0;height=0;textScale=4;audioCtx;audioDestination;hardwareOffset=0;playbackOffset=0;inactiveFps=1;playing=!1;stopped=!0;lastFrameTime=0;constructor({width:e=1920,height:t=1080,background:i="#000000",resolution:r=1,callback:a,context:s=new AudioContext,audioDestination:n=s.destination}={}){super(),this.resolution=r,this.background=i,this.callback=a,this.audioCtx=s,this.audioDestination=n,this.resize(e,t)}get hardwareTime(){return this.audioCtx.currentTime}get playbackTime(){return this.playing?this.hardwareTime-this.hardwareOffset+this.playbackOffset:this.playbackOffset}start(){this.stopped&&(this.stopped=!1,this.timer())}stop(){this.stopped=!0}async play(){this.playing||this.stopped||(this.resumeAudioContext(),this.hardwareOffset=this.hardwareTime,this.playing=!0)}async pause(){this.playing&&(this.playbackOffset=this.playbackTime,this.playing=!1)}async timer(e=0){if(this.stopped)return;const t=1e3/(this.playing?_:this.inactiveFps);e-this.lastFrameTime>=t&&(this.lastFrameTime=e,await(this.callback?.())),requestAnimationFrame(this.timer.bind(this))}async resumeAudioContext(){"suspended"===this.audioCtx.state&&await this.audioCtx.resume()}get background(){return this._background}set background(e){this.background!=e&&(this.canvas.style.background=e,this._background=e)}resize(e=this.width,t=this.height,i=this.resolution){const r=2*Math.round(e/2),a=2*Math.round(t/2);return r===this.width&&a===this.height&&i===this.resolution||(this.width=r,this.height=a,this.resolution=i,this.canvas.width=2*Math.round(r*this.resolution/2),this.canvas.height=2*Math.round(a*this.resolution/2),this.videoCtx.imageSmoothingEnabled=!1),this}clear(e){let t=0,i=0,r=this.width*this.resolution,a=this.height*this.resolution;return this.videoCtx.fillStyle=this._background,e&&(t=(e.x??0)*this.resolution,i=(e.y??0)*this.resolution,r=e.width*this.resolution,a=e.height*this.resolution),this.videoCtx.setTransform(1,0,0,1,0,0),this.videoCtx.clearRect(t,i,r,a),this.videoCtx.fillRect(t,i,r,a),this.videoCtx.scale(this.resolution,this.resolution),this}mount(e){e.appendChild(this.canvas)}unmount(){this.canvas.parentElement?.removeChild(this.canvas)}}function W(e,t){return"lower"==t?e.toLocaleLowerCase():"upper"==t?e.toUpperCase():e}function H(e="#000000",t=100){return`${e}${Math.round(t/100*255).toString(16)}`}function $(e,t){return"number"==typeof e?e:Number.parseFloat(e.replace("%",""))*t/100}function j(e){return class extends e{_handlers={};_regexHandlers=[];on(e,t,i={}){if(e instanceof RegExp){const r=t;return this._regexHandlers.push({pattern:e,callback:r,...i}),()=>this.off(e)}{const r=t;return this._handlers[e]?(this.off(e,r),this._handlers[e]?.push({callback:r,...i})):this._handlers[e]=[{callback:r,...i}],()=>this.off(e,r)}}off(e,t){"function"!=typeof e?Array.isArray(e)?e.forEach(e=>e()):e instanceof RegExp?this._regexHandlers=this._regexHandlers.filter(t=>{return i=t.pattern,r=e,!(i.source===r.source&&i.flags===r.flags);var i,r}):this._handlers[e]=this._handlers[e]?.filter(e=>e.callback!==t):e()}offAny(){this._handlers={},this._regexHandlers=[]}emit(e,t){for(const i of this._handlers[e]??[])i.callback(t),i.once&&this.off(e,i.callback);for(const i of this._regexHandlers)i.pattern.test(String(e))&&(i.callback({type:e,detail:t}),i.once&&this.off(i.pattern))}}}L([t()],V.prototype,"resolution",2),L([t()],V.prototype,"width",2),L([t()],V.prototype,"height",2),L([t()],V.prototype,"background",1);let q=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_","");var K=Object.defineProperty,Q=(e,t,i,r)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,i,s)||s);return s&&K(t,i,s),s};class X extends e{id=`source_${q()}`;mimeType;input;name;createdAt=/* @__PURE__ */(new Date).toISOString();constructor(e){super(),this.input=e.input,this.mimeType=e.mimeType,e.name?this.name=e.name:"string"==typeof this.input?this.name=this.input.split("/").at(-1)??"":this.input instanceof File||this.input instanceof FileSystemFileHandle?this.name=this.input.name:this.name="UNTITLED_BLOB"}async init(){}async arrayBuffer(){if("string"==typeof this.input){const e=await fetch(this.input);return await e.arrayBuffer()}if(this.input instanceof Blob)return await this.input.arrayBuffer();{const e=await this.input.getFile();return await e.arrayBuffer()}}toJSON(){return this.id}}function G(e){return class extends e{height=1080;width=1920;get aspectRatio(){return this.width/this.height}}}Q([t()],X.prototype,"id"),Q([t()],X.prototype,"mimeType"),Q([t()],X.prototype,"input"),Q([t()],X.prototype,"name"),Q([t()],X.prototype,"createdAt");class Y extends Error{name="DecoderError";constructor(e){super(e)}}class J extends Error{name="EncoderError";constructor(e){super(e)}}class Z extends Error{name="IOError";constructor(e){super(e)}}class ee extends Error{name="ReferenceError";constructor(e){super(e)}}class te extends Error{name="ValidationError";constructor(e){super(e)}}function ie(e){if(!e)throw new Error("Assertion failed.")}const re=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},ae=e=>e&&e[e.length-1],se=e=>e>=0&&e<2**32;class ne{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<<i)>>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let r=this.pos;r<i;r++){const e=Math.floor(r/8);let a=this.bytes[e];const s=7-(7&r);a&=~(1<<s),a|=(t&1<<i-r-1)>>i-r-1<<s,this.bytes[e]=a}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new ne(this.bytes);return e.pos=this.pos,e}}const oe=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},ce=e=>{const t=oe(e);return 1&t?t+1>>1:-(t>>1)},le=e=>e.constructor===Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),he=e=>e.constructor===DataView?e:e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),de=/* #__PURE__ */new TextDecoder,ue=/* #__PURE__ */new TextEncoder,me=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),pe={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},fe=/* #__PURE__ */me(pe),ge={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ke=/* #__PURE__ */me(ge),ye={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},we=/* #__PURE__ */me(ye),be=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),Te=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class Ce{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const Se=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),ve=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,xe=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o<t?r=n+1:a=n-1}return s},Pe=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},Ee=(e,t,i)=>{const r=Pe(e,i(t),i);e.splice(r+1,0,t)},Ie=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},_e=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Ae=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Be=e=>{throw new Error(`Unexpected value: ${e}`)},Fe=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},Me=(e,t,i,r)=>{i>>>=0,i&=16777215,r?(e.setUint8(t,255&i),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,i>>>16&255)):(e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i))},De=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),Oe=(e,t,i)=>Math.max(t,Math.min(i,e)),Re="und",ze=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Ne=(e,t)=>Math.round(e/t)*t,Ue=/^[a-z]{3}$/,Le=e=>Ue.test(e),Ve=1e6*(1+Number.EPSILON),We=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?He(e.headers):{},a=t.headers?He(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},He=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},$e=async(e,t,i,r)=>{let a=0;for(;;)try{return await e(t,i)}catch(s){a++;const e=r(a,s,t);if(null===e)throw s;if(console.error("Retrying failed fetch. Error:",s),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");e>0&&await new Promise(t=>setTimeout(t,1e3*e))}};class je{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let qe=null;const Ke=()=>null!==qe?qe:qe=!("undefined"==typeof navigator||!navigator.vendor?.match(/apple/i));let Qe=null;const Xe=()=>null!==Qe?Qe:Qe="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox");let Ge=null;const Ye=(e,t)=>-1!==e?e:t,Je=(e,t,i,r)=>e<=r&&i<=t,Ze=function*(e){for(const t in e){const i=e[t];void 0!==i&&(yield{key:t,value:i})}},et=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},tt=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i},it=e=>{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return btoa(t)},rt=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},at=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},st=e=>"number"==typeof e&&!Number.isNaN(e);class nt{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw new TypeError("mimeType must be a string.")}}class ot{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}}const ct={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},lt=["avc","hevc","vp9","av1","vp8"],ht=["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"],dt=["aac","opus","mp3","vorbis","flac"],ut=[...dt,...ht],mt=["webvtt"],pt=[{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}],ft=[{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}],gt=[{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}],kt=[{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}],yt=".01.01.01.01.00",wt=".0.110.01.01.01.0",bt=(e,t,i,r)=>{if("avc"===e){const e=100,a=Math.ceil(t/16)*Math.ceil(i/16),s=pt.find(e=>a<=e.maxMacroblocks&&r<=e.maxBitrate)??ae(pt),n=s?s.level:0;return`avc1.${e.toString(16).padStart(2,"0")}${"00"}${n.toString(16).padStart(2,"0")}`}if("hevc"===e){const e="",a=1,s="6",n=t*i,o=ft.find(e=>n<=e.maxPictureSize&&r<=e.maxBitrate)??ae(ft),c="B0";return`hev1.${e}${a}.${s}.${o.tier}${o.level}.${c}`}if("vp8"===e)return"vp8";if("vp9"===e){const e=t*i,a="08";return`vp09.${"00"}.${(gt.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??ae(gt)).level.toString().padStart(2,"0")}.${a}`}if("av1"===e){const e=0,a=t*i,s=kt.find(e=>a<=e.maxPictureSize&&r<=e.maxBitrate)??ae(kt),n="08";return`av01.${e}.${s.level.toString().padStart(2,"0")}${s.tier}.${n}`}throw new TypeError(`Unhandled codec '${e}'.`)},Tt=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},Ct=e=>{const t=e.split("."),i=Number(t[1]),r=t[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},St=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o}=e;if("avc"===t){if(ie(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${Se(t)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${Se(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=ve(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=he(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=ve(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=ae(gt).level;for(const e of gt)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(yt)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=ae(gt).level;for(const e of gt)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?pe[r.primaries]:1,h=r?.transfer?ge[r.transfer]:1,d=r?.matrix?ye[r.matrix]:1,u=r?.fullRange?1:0;let m=`av01.${t}.${i}${a}.${s}`;return m+=`.${n}.${c.toString().padStart(3,"0")}`,m+=`.${l.toString().padStart(2,"0")}`,m+=`.${h.toString().padStart(2,"0")}`,m+=`.${d.toString().padStart(2,"0")}`,m+=`.${u}`,m.endsWith(wt)&&(m=m.slice(0,-17)),m}throw new TypeError(`Unhandled codec '${t}'.`)},vt=(e,t,i)=>{if("aac"===e)return t>=2&&i<=24e3?"mp4a.40.29":i<=24e3?"mp4a.40.5":"mp4a.40.2";if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";if(ht.includes(e))return e;throw new TypeError(`Unhandled codec '${e}'.`)},xt=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";return`mp4a.40.${It(i).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&ht.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Pt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Et=[-1,1,2,3,4,5,6,8],It=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new ne(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let a=null;15===r?a=t.readBits(24):r<Pt.length&&(a=Pt[r]);const s=t.readBits(4);let n=null;return s>=1&&s<=7&&(n=Et[s]),{objectType:i,frequencyIndex:r,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},_t=48e3,At=/^pcm-([usf])(\d+)+(be)?$/,Bt=e=>{if(ie(ht.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=At.exec(e);let i;ie(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Ft=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":e.startsWith("mp4a.40")||"mp4a.67"===e?"aac":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e?"mp3":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ulaw"===e?"ulaw":"alaw"===e?"alaw":At.test(e)?e:"webvtt"===e?"webvtt":null,Mt=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Dt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ot=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Rt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,zt=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Nt=e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Mt.some(t=>e.decoderConfig.codec.startsWith(t)))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(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!Te(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(pe);if(null!=t.primaries&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(ge);if(null!=t.transfer&&!r.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const a=Object.keys(ye);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!Dt.test(e.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(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!Ot.test(e.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(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!Rt.test(e.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(e.decoderConfig.codec.startsWith("av01")&&!zt.test(e.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/.')},Ut=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Lt=e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Ut.some(t=>e.decoderConfig.codec.startsWith(t)))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(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!Te(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.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(!e.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(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.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(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.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(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)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((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!ht.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ht.join(", ")}).`)},Vt=e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")};class Wt{constructor(e){this.mutex=new Ce,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let r=this.trackTimestampInfo.get(e);if(!r){if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,r)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),t<r.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 ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,t),t}}var Ht,$t;!function(e){e[e.IDR=5]="IDR",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Ht||(Ht={})),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.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}($t||($t={}));const jt=e=>{const t=[];let i=0;for(;i<e.length;){let r=-1,a=0;for(let t=i;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){r=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){r=t,a=4;break}}if(-1===r)break;if(i>0&&r>i){const a=e.subarray(i,r);a.length>0&&t.push(a)}i=r+a}if(i<e.length){const r=e.subarray(i);r.length>0&&t.push(r)}return t},qt=(e,t)=>{const i=[];let r=0;const a=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+t<=e.length;){let s;1===t?s=a.getUint8(r):2===t?s=a.getUint16(r,!1):3===t?s=Fe(a,r,!1):4===t?s=a.getUint32(r,!1):(Be(t),ie(!1)),r+=t;const n=e.subarray(r,r+s);i.push(n),r+=s}return i},Kt=e=>{const t=[],i=e.length;for(let r=0;r<i;r++)r+2<i&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},Qt=e=>31&e[0],Xt=e=>{try{const t=jt(e),i=t.filter(e=>Qt(e)===Ht.SPS),r=t.filter(e=>Qt(e)===Ht.PPS),a=t.filter(e=>Qt(e)===Ht.SPS_EXT);if(0===i.length)return null;if(0===r.length)return null;const s=i[0],n=Gt(s);ie(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:i,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},Gt=e=>{try{const t=new ne(Kt(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const i=t.readAlignedByte(),r=t.readAlignedByte(),a=t.readAlignedByte();oe(t);let s=null,n=null,o=null;if(100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i){s=oe(t),3===s&&t.skipBits(1),n=oe(t),o=oe(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==s?8:12);e++){if(t.readBits(1)){const i=e<6?16:64;let r=8,a=8;for(let e=0;e<i;e++){if(0!==a){a=(r+ce(t)+256)%256}r=0===a?r:a}}}}oe(t);const c=oe(t);if(0===c)oe(t);else if(1===c){t.skipBits(1),ce(t),ce(t);const e=oe(t);for(let i=0;i<e;i++)ce(t)}oe(t),t.skipBits(1),oe(t),oe(t);return{profileIdc:i,constraintFlags:r,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:s,bitDepthLumaMinus8:n,bitDepthChromaMinus8:o}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},Yt=(e,t)=>{if(t.description){const i=3&le(t.description)[21];return qt(e,i+1)}return jt(e)},Jt=e=>e[0]>>1&63,Zt=e=>{try{const t=jt(e),i=t.filter(e=>Jt(e)===$t.VPS_NUT),r=t.filter(e=>Jt(e)===$t.SPS_NUT),a=t.filter(e=>Jt(e)===$t.PPS_NUT),s=t.filter(e=>Jt(e)===$t.PREFIX_SEI_NUT||Jt(e)===$t.SUFFIX_SEI_NUT);if(0===r.length||0===a.length)return null;const n=r[0],o=new ne(Kt(n));o.skipBits(16),o.readBits(4);const c=o.readBits(3),l=o.readBits(1),{general_profile_space:h,general_tier_flag:d,general_profile_idc:u,general_profile_compatibility_flags:m,general_constraint_indicator_flags:p,general_level_idc:f}=ei(o,c);oe(o);const g=oe(o);3===g&&o.skipBits(1),oe(o),oe(o),o.readBits(1)&&(oe(o),oe(o),oe(o),oe(o));const k=oe(o),y=oe(o);oe(o);const w=o.readBits(1);for(let e=w?0:c;e<=c;e++)oe(o),oe(o),oe(o);oe(o),oe(o),oe(o),oe(o),oe(o),oe(o),o.readBits(1)&&o.readBits(1)&&ti(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),oe(o),oe(o),o.skipBits(1));const b=oe(o);if(ii(o,b),o.readBits(1)){const e=oe(o);for(let t=0;t<e;t++)oe(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let T=0;o.readBits(1)&&(T=ai(o,c));let C=0;if(a.length>0){const e=a[0],t=new ne(Kt(e));t.skipBits(16),oe(t),oe(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),oe(t),oe(t),ce(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&oe(t),ce(t),ce(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),r=t.readBits(1);C=i||r?i&&!r?2:!i&&r?3:0:0}const S=[...i.length?[{arrayCompleteness:1,nalUnitType:$t.VPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:$t.SPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:$t.PPS_NUT,nalUnits:a}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Jt(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:h,generalTierFlag:d,generalProfileIdc:u,generalProfileCompatibilityFlags:m,generalConstraintIndicatorFlags:p,generalLevelIdc:f,minSpatialSegmentationIdc:T,parallelismType:C,chromaFormatIdc:g,bitDepthLumaMinus8:k,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:l,lengthSizeMinusOne:3,arrays:S}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},ei=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let h=0;h<32;h++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let h=0;h<6;h++)n[h]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let h=0;h<t;h++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let h=t;h<8;h++)e.skipBits(2);for(let h=0;h<t;h++)c[h]&&e.skipBits(88),l[h]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},ti=e=>{for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBits(1)){const i=Math.min(64,1<<4+(t<<1));t>1&&ce(e);for(let t=0;t<i;t++)ce(e)}else oe(e)}},ii=(e,t)=>{const i=[];for(let r=0;r<t;r++)i[r]=ri(e,r,t,i)},ri=(e,t,i,r)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-(oe(e)+1)}else n=t-1;e.readBits(1),oe(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=oe(e),i=oe(e);for(let r=0;r<t;r++)oe(e),e.readBits(1);for(let r=0;r<i;r++)oe(e),e.readBits(1);a=t+i}return a},ai=(e,t)=>{if(e.readBits(1)){255===e.readBits(8)&&(e.readBits(16),e.readBits(16))}if(e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(oe(e),oe(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(oe(e),oe(e),oe(e),oe(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&oe(e),e.readBits(1)&&si(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=oe(e);return oe(e),oe(e),oe(e),oe(e),t}return 0},si=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?oe(e):i=1===e.readBits(1);let n=1;if(!i){n=oe(e)+1}r&&ni(e,n,s),a&&ni(e,n,s)}},ni=(e,t,i)=>{for(let r=0;r<t;r++)oe(e),oe(e),i&&(oe(e),oe(e)),e.readBits(1)},oi=e=>{const t=new ne(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=ae(gt).level;for(const h of gt)if(c<=h.maxPictureSize){l=h.level;break}return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},ci=function*(e){const t=new ne(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);ie(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},li=e=>{for(const{type:t,data:i}of ci(e)){if(1!==t)continue;const e=new ne(i),r=e.readBits(3);e.readBits(1);let a=0,s=0,n=0;if(e.readBits(1))a=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(n=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(a=i),i>7){const t=e.readBits(1);0===r&&(s=t)}if(t){if(e.readBits(1)){const t=n+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const o=e.readBits(1);let c=8;if(2===r&&o){c=e.readBits(1)?12:10}else r<=2&&(c=o?10:8);let l=0;1!==r&&(l=e.readBits(1));let h=1,d=1,u=0;return l||(0===r?(h=1,d=1):1===r?(h=0,d=0):12===c&&(h=e.readBits(1),h&&(d=e.readBits(1))),h&&d&&(u=e.readBits(2))),{profile:r,level:a,tier:s,bitDepth:c,monochrome:l,chromaSubsamplingX:h,chromaSubsamplingY:d,chromaSamplePosition:u}}return null},hi=e=>{const t=he(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},di=[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],ui=e=>{if(e.length<7)throw new Error("Setup header is too s