sessiongraph 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ (function(){"use strict";function p(t){if(!t)throw new Error("Assertion failed.")}const cr=Math.PI/180,lr=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},zt=[1,0,0,0,1,0,0,0,1],dr=(t,e,i)=>{const[r,n,,s,o]=t,a=Math.abs(r)*e+Math.abs(s)*i,l=Math.abs(n)*e+Math.abs(o)*i;return Je(Je(Wt(-e/2,-i/2),t),Wt(a/2,l/2))},ur=t=>{const e=t*cr,i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},Wt=(t,e)=>[1,0,0,0,1,0,t,e,1],fr=(t,e)=>[t,0,0,0,e,0,0,0,1],Je=(t,e)=>{const i=new Array(9);for(let r=0;r<3;r++)for(let n=0;n<3;n++)i[3*r+n]=t[3*r]*e[n]+t[3*r+1]*e[3+n]+t[3*r+2]*e[6+n];return i},hr=(t,e,i,r)=>({rotation:lr(t+(e?-i:i)),flip:e!==r}),j=t=>t&&t[t.length-1],le=t=>t>=0&&t<2**32,mr=t=>t>=-2147483648&&t<2**31,y=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+t.readBits(e)},de=t=>{const e=y(t);return e%2===0?-(e/2):(e+1)/2},G=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),me=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),pr=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const i=new Uint8Array(3*e.length);let r=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s<128)i[r++]=s;else if(s<2048)i[r++]=192|s>>6,i[r++]=128|s&63;else if(s<55296||s>57343)i[r++]=224|s>>12,i[r++]=128|s>>6&63,i[r++]=128|s&63;else{const o=n+1<e.length?e.charCodeAt(n+1):0;s<56320&&o>=56320&&o<=57343?(s=65536+(s-55296<<10)+(o-56320),n++,i[r++]=240|s>>18,i[r++]=128|s>>12&63,i[r++]=128|s>>6&63,i[r++]=128|s&63):(i[r++]=239,i[r++]=191,i[r++]=189)}}return i.slice(0,r)}},ne=new pr,_e={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Pe={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},gr=t=>!t||t.primaries==null&&t.transfer==null&&t.matrix==null&&t.fullRange==null,et=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Lt{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const i=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),r=this.currentPromise;return this.currentPromise=i,this.pending++,await r,e}}const Vt=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Ut=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),Ht=(t,e,i)=>{let r=0,n=t.length-1,s=-1;for(;r<=n;){const o=r+(n-r+1)/2|0;i(t[o])<=e?(s=o,r=o+1):n=o-1}return s},Nt=()=>{let t,e;return{promise:new Promise((r,n)=>{t=r,e=n}),resolve:t,reject:e}},be=t=>{throw new Error(`Unexpected value: ${t}`)},wr=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),s=t.getUint8(e+2);return r<<16|n<<8|s},yr=(t,e,i,r)=>{i=i>>>0,i=i&16777215,t.setUint8(e,i>>>16&255),t.setUint8(e+1,i>>>8&255),t.setUint8(e+2,i&255)},qt=(t,e,i)=>Math.max(e,Math.min(i,t)),br=(t,e,i)=>t+(e-t)*i,Tr="und",Dt=(t,e)=>Math.round(t/e)*e,$t=(t,e)=>Math.floor(t*e)/e,Cr=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},vr=/^[a-z]{3}$/,Er=t=>vr.test(t),ke=1e6*(1+Number.EPSILON),Sr=(t,e)=>{const i=t<0?-1:1;t=Math.abs(t);let r=0,n=1,s=1,o=0,a=t;for(;;){const l=Math.floor(a),c=l*s+r,d=l*o+n;if(d>e)return{num:i*s,den:o};if(r=s,n=o,s=c,o=d,a=1/(a-l),!isFinite(a))break}return{num:i*s,den:o}};class xr{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let tt=null;const _r=()=>tt!==null?tt:tt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let it=null;const Ne=()=>it!==null?it:it=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let rt=null;const Br=()=>rt!==null?rt:rt=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));let nt=null;const Pr=()=>{if(nt!==null)return nt;if(typeof navigator>"u")return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?nt=Number(t[1]):null},kr=t=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${t} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${t} is not available in this environment.`,Ar=t=>t instanceof DOMException&&t.name==="QuotaExceededError"&&/reclaimed/i.test(t.message),Ir=(async()=>{})().constructor,Te=t=>t instanceof Ir||t instanceof Promise?!0:typeof t?.then=="function",jt=function*(t){for(const e in t){const i=t[e];i!==void 0&&(yield{key:e,value:i})}},Rr=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Mr=t=>typeof t=="number"&&!Number.isNaN(t),Fr=(t,e)=>{let i=-1,r=1/0;for(let n=0;n<t.length;n++){const s=e(t[n]);(i===-1||s<r)&&(r=s,i=n)}return i},Gt=t=>{p(Number.isInteger(t.num)),p(Number.isInteger(t.den)),p(t.den!==0);let e=Math.abs(t.num),i=Math.abs(t.den);for(;i!==0;){const n=e%i;e=i,i=n}const r=e||1;return{num:t.num/r,den:t.den/r}},st=(t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},Or=t=>new Promise(e=>setTimeout(e,t)),Qt=t=>Array.isArray(t)?t:[t];class ot{constructor(){this._listeners=new Map}on(e,i,r){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:i,once:r?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){const[i,r]=e,n=this._listeners.get(i);if(n)for(const s of n){try{s.fn(r)}catch(o){console.error(o)}s.once&&n.delete(s)}}}const zr=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(e=>typeof e=="string");var se;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(se||(se={}));class A{constructor(){}static get level(){return A._level}static set level(e){if(e!==se.Silent&&e!==se.Errors&&e!==se.Warnings&&e!==se.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");A._level=e}static get _emitter(){return A._emitterInstance??=new ot}static on(e,i,r){return A._emitter.on(e,i,r)}static _error(...e){A._emitter._emit("error",e),A._level>=se.Errors&&console.error(...e)}static _warn(...e){A._emitter._emit("warn",e),A._level>=se.Warnings&&console.warn(...e)}static _info(...e){A._emitter._emit("info",e),A._level>=se.Info&&console.info(...e)}}A._level=se.Info,A._emitterInstance=null;class Xt{constructor(e,i){if(this.data=e,this.mimeType=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof i!="string")throw new TypeError("mimeType must be a string.")}}class Wr{constructor(e,i,r,n){if(this.data=e,this.mimeType=i,this.name=r,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(i!==void 0&&typeof i!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const Lr=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.creationTime!==void 0&&t.creationTime!==null&&(!(t.creationTime instanceof Date)||Number.isNaN(t.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(t.beatsPerMinute!==void 0&&(!Number.isInteger(t.beatsPerMinute)||t.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");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(const 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(const e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(i=>typeof i=="string"))&&!(e instanceof Uint8Array)&&!(Array.isArray(e)&&e.every(i=>i instanceof Uint8Array))&&!(e instanceof Xt)&&!(e instanceof Wr)&&!zr(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Vr=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.primary!==void 0&&typeof t.primary!="boolean")throw new TypeError("disposition.primary 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.")};class F{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),i=this.bytes[e]??0,r=7-(this.pos&7),n=(i&1<<r)>>r;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let i=0;for(let r=0;r<e;r++)i<<=1,i|=this.readBit();return i}writeBits(e,i){const r=this.pos+e;for(let n=this.pos;n<r;n++){const s=Math.floor(n/8);let o=this.bytes[s];const a=7-(n&7);o&=~(1<<a),o|=(i&1<<r-n-1)>>r-n-1<<a,this.bytes[s]=o}this.pos=r}copyBits(e,i){let r=0;for(r;r<e-7;r+=8)this.writeBits(8,i.readBits(8));const n=e-r;n>0&&this.writeBits(n,i.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,i=this.bytes[e]??0;return this.pos+=8,i}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new F(this.bytes);return e.pos=this.pos,e}}const at=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Kt=[-1,1,2,3,4,5,6,8],Ur=t=>{const e=t.objectType===5||t.objectType===29,i=t.objectType===29,r=e?t.outputSampleRate/2:t.outputSampleRate,n=i?1:t.outputNumberOfChannels,s=Kt.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let o=16;t.objectType>=32&&(o+=6),ct(r)===15&&(o+=24),e&&(o+=9,ct(t.outputSampleRate)===15&&(o+=24));const a=Math.ceil(o/8),l=new Uint8Array(a),c=new F(l);return Yt(c,t.objectType),Zt(c,r),c.writeBits(4,s),e&&(Zt(c,t.outputSampleRate),Yt(c,2)),c.writeBits(3,0),l},Yt=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},Zt=(t,e)=>{const i=ct(e);t.writeBits(4,i),i===15&&t.writeBits(24,e)},ct=t=>{const e=at.indexOf(t);return e===-1?15:e};const Hr=[48e3,44100,32e3],Nr=[24e3,22050,16e3];const qr=4168249274;const lt="Mediabunny v1.65.0";var ue;(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(ue||(ue={}));var K;(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.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(K||(K={}));const Re=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(r===-1||r>=t.length-2)break;e=r;let n=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?n=4:t[e+1]===0&&t[e+2]===1&&(n=3),n===0){e++;continue}i!==-1&&e>i&&(yield{offset:i,length:e-i}),i=e+n,e=i}i!==-1&&i<t.length&&(yield{offset:i,length:t.length-i})},Jt=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let n;e===1?n=r.getUint8(i):e===2?n=r.getUint16(i,!1):e===3?n=wr(r,i):(p(e===4),n=r.getUint32(i,!1)),i+=e,yield{offset:i,length:n},i+=n}},Dr=(t,e)=>{if(e.description){const n=(G(e.description)[4]&3)+1;return Jt(t,n)}else return Re(t)},ei=t=>t&31,qe=t=>{const e=new Uint8Array(t.length),i=t.length;let r=0;for(let n=0;n<i;n++)n+2<i&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e[r++]=0,e[r++]=0,n+=2):e[r++]=t[n];return e.subarray(0,r)},$r=(t,e)=>{const i=t.reduce((s,o)=>s+e+o.byteLength,0),r=new Uint8Array(i);let n=0;for(const s of t){const o=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:o.setUint8(n,s.byteLength);break;case 2:o.setUint16(n,s.byteLength,!1);break;case 3:yr(o,n,s.byteLength);break;case 4:o.setUint32(n,s.byteLength,!1);break}n+=e,r.set(s,n),n+=s.byteLength}return r},ti=t=>{try{const e=[],i=[],r=[];for(const a of Re(t)){const l=t.subarray(a.offset,a.offset+a.length),c=ei(l[0]);c===ue.SPS&&e.length<31?e.push(l):c===ue.PPS&&i.length<255?i.push(l):c===ue.SPS_EXT&&r.length<255&&r.push(l)}if(e.length===0||i.length===0)return null;const n=e[0],s=Gr(n);if(!s)return null;const o=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return A._error("Error building AVC Decoder Configuration Record:",e),null}},ii=t=>{const 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(const i of t.sequenceParameterSets){const r=i.byteLength;e.push(r>>8),e.push(r&255);for(let n=0;n<r;n++)e.push(i[n])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const r=i.byteLength;e.push(r>>8),e.push(r&255);for(let n=0;n<r;n++)e.push(i[n])}if((t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144)&&t.chromaFormat!==null){p(t.bitDepthLumaMinus8!==null),p(t.bitDepthChromaMinus8!==null),p(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(const i of t.sequenceParameterSetExt){const r=i.byteLength;e.push(r>>8),e.push(r&255);for(let n=0;n<r;n++)e.push(i[n])}}return new Uint8Array(e)},jr=t=>{try{const e=me(t);let i=0;const r=e.getUint8(i++),n=e.getUint8(i++),s=e.getUint8(i++),o=e.getUint8(i++),a=e.getUint8(i++)&3,l=e.getUint8(i++)&31,c=[];for(let h=0;h<l;h++){const m=e.getUint16(i,!1);i+=2,c.push(t.subarray(i,i+m)),i+=m}const d=e.getUint8(i++),u=[];for(let h=0;h<d;h++){const m=e.getUint16(i,!1);i+=2,u.push(t.subarray(i,i+m)),i+=m}const f={configurationVersion:r,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:o,lengthSizeMinusOne:a,sequenceParameterSets:c,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&i+4<=t.length){const h=e.getUint8(i++)&3,m=e.getUint8(i++)&7,w=e.getUint8(i++)&7,T=e.getUint8(i++);f.chromaFormat=h,f.bitDepthLumaMinus8=m,f.bitDepthChromaMinus8=w;const b=[];for(let E=0;E<T;E++){const x=e.getUint16(i,!1);i+=2,b.push(t.subarray(i,i+x)),i+=x}f.sequenceParameterSetExt=b}return f}catch(e){return A._error("Error deserializing AVC Decoder Configuration Record:",e),null}},ri={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Gr=t=>{try{const e=qe(t),i=new F(e);if(i.skipBits(1),i.skipBits(2),i.readBits(5)!==7)return null;const n=i.readAlignedByte(),s=i.readAlignedByte(),o=i.readAlignedByte();y(i);let a=1,l=0,c=0,d=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=y(i),a===3&&(d=i.readBits(1)),l=y(i),c=y(i),i.skipBits(1),i.readBits(1))){for(let W=0;W<(a!==3?8:12);W++)if(i.readBits(1)){const ie=W<6?16:64;let re=8,$=8;for(let ye=0;ye<ie;ye++){if($!==0){const xe=de(i);$=(re+xe+256)%256}re=$===0?re:$}}}y(i);const u=y(i);if(u===0)y(i);else if(u===1){i.skipBits(1),de(i),de(i);const q=y(i);for(let W=0;W<q;W++)de(i)}y(i),i.skipBits(1);const f=y(i),h=y(i),m=16*(f+1),w=16*(h+1);let T=m,b=w;const E=i.readBits(1);if(E||i.skipBits(1),i.skipBits(1),i.readBits(1)){const q=y(i),W=y(i),te=y(i),ie=y(i);let re,$;if((d===0?a:0)===0)re=1,$=2-E;else{const xe=a===3?1:2,Ze=a===1?2:1;re=xe,$=Ze*(2-E)}T-=re*(q+W),b-=$*(te+ie)}if(T<=0||b<=0)return null;let k=2,M=2,O=2,z=0,H={num:1,den:1},L=null,V=null,U=null,R=null;const N=i.pos;if(i.readBits(1)){if(i.readBits(1)){const xe=i.readBits(8);if(xe===255)H={num:i.readBits(16),den:i.readBits(16)};else{const Ze=ri[xe];Ze&&(H=Ze)}}i.readBits(1)&&i.skipBits(1),i.readBits(1)&&(i.skipBits(3),z=i.readBits(1),i.readBits(1)&&(k=i.readBits(8),M=i.readBits(8),O=i.readBits(8))),i.readBits(1)&&(y(i),y(i)),i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const $=i.readBits(1);$&&ni(i);const ye=i.readBits(1);ye&&ni(i),($||ye)&&i.skipBits(1),i.skipBits(1),U=i.pos,R=i.readBits(1),R&&(i.skipBits(1),y(i),y(i),y(i),y(i),L=Math.min(y(i),16),V=Math.min(y(i),16))}if(L===null){p(V===null);const q=s&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&q)L=0,V=0;else{const W=f+1,te=h+1,ie=(2-E)*te,re=je.find(ye=>ye.level>=o)??j(je),$=Math.min(Math.floor(re.maxDpbMbs/(W*ie)),16);L=$,V=$}}return p(V!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:s,levelIdc:o,frameMbsOnlyFlag:E,chromaFormatIdc:a,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:w,displayWidth:T,displayHeight:b,pixelAspectRatio:H,colourPrimaries:k,matrixCoefficients:O,transferCharacteristics:M,fullRangeFlag:z,numReorderFrames:L,maxDecFrameBuffering:V,vuiParametersFlagBitOffset:N,bitstreamRestrictionFlagBitOffset:U,bitstreamRestrictionFlag:R}}catch(e){return A._error("Error parsing AVC SPS:",e),null}},ni=t=>{const e=y(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)y(t),y(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},Qr=(t,e)=>{if(e.description){const n=(G(e.description)[21]&3)+1;return Jt(t,n)}else return Re(t)},dt=t=>t>>1&63,Xr=t=>{try{const e=new F(qe(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:o,general_profile_compatibility_flags:a,general_constraint_indicator_flags:l,general_level_idc:c}=Kr(e,i);y(e);const d=y(e);let u=0;d===3&&(u=e.readBits(1));const f=y(e),h=y(e);let m=f,w=h;if(e.readBits(1)){const R=y(e),N=y(e),X=y(e),q=y(e);let W=1,te=1;const ie=u===0?d:0;ie===1?(W=2,te=2):ie===2&&(W=2,te=1),m-=(R+N)*W,w-=(X+q)*te}if(m<=0||w<=0)return null;const T=y(e),b=y(e);y(e);const x=e.readBits(1)?0:i;let k=0;for(let R=x;R<=i;R++)y(e),k=y(e),y(e);y(e),y(e),y(e),y(e),y(e),y(e),e.readBits(1)&&e.readBits(1)&&Yr(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),y(e),y(e),e.skipBits(1));const M=y(e);if(Zr(e,M),e.readBits(1)){const R=y(e);for(let N=0;N<R;N++)y(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let O=2,z=2,H=2,L=0,V=0,U={num:1,den:1};if(e.readBits(1)){const R=en(e,i);U=R.pixelAspectRatio,O=R.colourPrimaries,z=R.transferCharacteristics,H=R.matrixCoefficients,L=R.fullRangeFlag,V=R.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:w,pixelAspectRatio:U,colourPrimaries:O,transferCharacteristics:z,matrixCoefficients:H,fullRangeFlag:L,maxDecFrameBuffering:Math.min(k+1,16),spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:l,generalLevelIdc:c,chromaFormatIdc:d,bitDepthLumaMinus8:T,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:V}}catch(e){return A._error("Error parsing HEVC SPS:",e),null}},si=t=>{try{const e=[],i=[],r=[],n=[];for(const d of Re(t)){const u=t.subarray(d.offset,d.offset+d.length),f=dt(u[0]);f===K.VPS_NUT&&e.length<65535?e.push(u):f===K.SPS_NUT&&i.length<65535?i.push(u):f===K.PPS_NUT&&r.length<65535?r.push(u):(f===K.PREFIX_SEI_NUT||f===K.SUFFIX_SEI_NUT)&&n.length<65535&&n.push(u)}if(i.length===0||r.length===0)return null;const o=Xr(i[0]);if(!o)return null;let a=0;if(r.length>0){const d=r[0],u=new F(qe(d));u.skipBits(16),y(u),y(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),y(u),y(u),de(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&y(u),de(u),de(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const f=u.readBits(1),h=u.readBits(1);!f&&!h?a=0:f&&!h?a=2:!f&&h?a=3:a=0}const l=[...e.length?[{arrayCompleteness:1,nalUnitType:K.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:K.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:K.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:dt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(e){return A._error("Error building HEVC Decoder Configuration Record:",e),null}},Kr=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let s=0;for(let d=0;d<32;d++)s=s<<1|t.readBits(1);const o=new Uint8Array(6);for(let d=0;d<6;d++)o[d]=t.readBits(8);const a=t.readBits(8),l=[],c=[];for(let d=0;d<e;d++)l.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let d=e;d<8;d++)t.skipBits(2);for(let d=0;d<e;d++)l[d]&&t.skipBits(88),c[d]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:a}},Yr=t=>{for(let e=0;e<4;e++)for(let i=0;i<(e===3?2:6);i++)if(!t.readBits(1))y(t);else{const n=Math.min(64,1<<4+(e<<1));e>1&&de(t);for(let s=0;s<n;s++)de(t)}},Zr=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=Jr(t,r,e,i)},Jr=(t,e,i,r)=>{let n=0,s=0,o=0;if(e!==0&&(s=t.readBits(1)),s){if(e===i){const l=y(t);o=e-(l+1)}else o=e-1;t.readBits(1),y(t);const a=r[o]??0;for(let l=0;l<=a;l++)t.readBits(1)||t.readBits(1);n=r[o]}else{const a=y(t),l=y(t);for(let c=0;c<a;c++)y(t),t.readBits(1);for(let c=0;c<l;c++)y(t),t.readBits(1);n=a+l}return n},en=(t,e)=>{let i=2,r=2,n=2,s=0,o=0,a={num:1,den:1};if(t.readBits(1)){const l=t.readBits(8);if(l===255)a={num:t.readBits(16),den:t.readBits(16)};else{const c=ri[l];c&&(a=c)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(y(t),y(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(y(t),y(t),y(t),y(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&y(t),t.readBits(1)&&tn(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),o=y(t),y(t),y(t),y(t),y(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:o}},tn=(t,e,i)=>{let r=!1,n=!1,s=!1;r=t.readBits(1)===1,n=t.readBits(1)===1,(r||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let o=0;o<=i;o++){const a=t.readBits(1)===1;let l=!0;a||(l=t.readBits(1)===1);let c=!1;l?y(t):c=t.readBits(1)===1;let d=1;c||(d=y(t)+1),r&&oi(t,d,s),n&&oi(t,d,s)}},oi=(t,e,i)=>{for(let r=0;r<e;r++)y(t),y(t),i&&(y(t),y(t)),t.readBits(1)},rn=t=>{const e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(const i of t.arrays){e.push((i.arrayCompleteness&1)<<7|0|i.nalUnitType&63),e.push(i.nalUnits.length>>8&255),e.push(i.nalUnits.length&255);for(const r of i.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let n=0;n<r.length;n++)e.push(r[n])}}return new Uint8Array(e)};var ai;(function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"})(ai||(ai={}));const nn={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},sn=t=>{const e=new F(t);if(e.readBits(2)!==2)return null;const r=e.readBits(1),s=(e.readBits(1)<<1)+r;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let c=8;s>=2&&(c=e.readBits(1)?12:10);const d=e.readBits(3);let u=0,f=0;if(d!==7)if(f=e.readBits(1),s===1||s===3){const H=e.readBits(1),L=e.readBits(1);u=!H&&!L?3:H&&!L?2:1,e.skipBits(1)}else u=1;else u=3,f=1;const h=e.readBits(16),m=e.readBits(16),w=h+1,T=m+1,b=w*T;let E=j(ge).level;for(const z of ge)if(b<=z.maxPictureSize){E=z.level;break}const x=nn[d],k=x?.colourPrimaries??2,M=x?.transferCharacteristics??2,O=x?.matrixCoefficients??2;return{profile:s,level:E,bitDepth:c,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:k,transferCharacteristics:M,matrixCoefficients:O}},ci=function*(t){const e=new F(t),i=()=>{let r=0;for(let n=0;n<8;n++){const s=e.readAlignedByte();if(r+=(s&127)*2**(n*7),!(s&128))break;if(n===7&&s&128)return null}return r>2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let o;if(s){const a=i();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},on=t=>{for(const{type:e,data:i}of ci(t)){if(e!==1)continue;const r=new F(i),n=r.readBits(3);r.readBits(1);const s=r.readBits(1);let o=0,a=0,l=0;if(s)o=r.readBits(5);else{const L=r.readBits(1);let V=0;if(L){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let X=0;for(;X<32&&!r.readBits(1);)X++;X<32&&r.skipBits(X)}V=r.readBits(1),V&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}const U=r.readBits(1),R=r.readBits(5);for(let N=0;N<=R;N++){r.skipBits(12);const X=r.readBits(5);if(N===0&&(o=X),X>7){const q=r.readBits(1);N===0&&(a=q)}if(V&&r.readBits(1)){const W=l+1;r.skipBits(W),r.skipBits(W),r.skipBits(1)}U&&r.readBits(1)&&r.skipBits(4)}}const c=r.readBits(4),d=r.readBits(4),u=c+1;r.skipBits(u);const f=d+1;r.skipBits(f);let h=0;if(s?h=0:h=r.readBits(1),h&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const L=r.readBits(1);L&&(r.skipBits(1),r.skipBits(1));const V=r.readBits(1);let U=0;V?U=2:U=r.readBits(1),U>0&&(r.readBits(1)||r.skipBits(1)),L&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const m=r.readBits(1);let w=8;n===2&&m?w=r.readBits(1)?12:10:n<=2&&(w=m?10:8);let T=0;n!==1&&(T=r.readBits(1));let b=2,E=2,x=2;r.readBits(1)&&(b=r.readBits(8),E=r.readBits(8),x=r.readBits(8));let M=0,O=1,z=1,H=0;return T?M=r.readBits(1):b===1&&E===13&&x===0?(M=1,O=0,z=0):(M=r.readBits(1),n===0?(O=1,z=1):n===1?(O=0,z=0):w===12?(O=r.readBits(1),z=O?r.readBits(1):0):(O=1,z=0),O&&z&&(H=r.readBits(2))),{profile:n,level:o,tier:a,bitDepth:w,monochrome:T,chromaSubsamplingX:O,chromaSubsamplingY:z,chromaSamplePosition:H,videoFullRangeFlag:M,colourPrimaries:b,transferCharacteristics:E,matrixCoefficients:x}}return null},an=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,cn=t=>{if(t.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=me(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),o=e.getUint8(18);let a=null;return o&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:s,channelMappingFamily:o,channelMappingTable:a}},ln=[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],dn=t=>{const e=t[0]>>3,i=t[0]&3;let r;return i===0?r=1:i===1||i===2?r=2:r=t[1]&63,{durationInSamples:ln[e]*r}},un=(t,e,i)=>{switch(t){case"avc":{for(const r of Dr(i,e)){const n=i[r.offset],s=ei(n);if(s>=ue.NON_IDR_SLICE&&s<=ue.SLICE_DPC)return"delta";if(s===ue.IDR)return"key";if(s===ue.SEI&&!Br()){const o=i.subarray(r.offset,r.offset+r.length),a=qe(o);let l=1;do{let c=0;for(;;){const f=a[l++];if(f===void 0||(c+=f,f<255))break}let d=0;for(;;){const f=a[l++];if(f===void 0||(d+=f,f<255))break}if(c===6){const f=new F(a);f.pos=8*l;let h=-1;try{h=y(f)}catch{}const m=f.readBits(1);if(h===0&&m===1)return"key"}l+=d}while(l<a.length-1)}}return"delta"}case"hevc":{for(const r of Qr(i,e)){const n=dt(i[r.offset]);if(n<K.BLA_W_LP)return"delta";if(n<=K.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(i[0]&1)===0?"key":"delta";case"vp9":{const r=new F(i);if(r.readBits(2)!==2)return null;const n=r.readBits(1);return(r.readBits(1)<<1)+n===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:n,data:s}of ci(i))if(n===1){const o=new F(s);o.skipBits(4),r=!!o.readBits(1)}else if(n===3||n===6||n===7){if(r)return"key";const o=new F(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:be(t),p(!1)}},fn=(t,e)=>(e.byteLength>=8?me(e).getUint32(4):null)===qr?"key":"delta";var li;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(li||(li={}));const hn=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;const e=new F(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(i===3)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),o=e.readBits(3);(o&1)!==0&&o!==1&&e.skipBits(2),(o&4)!==0&&e.skipBits(2),o===2&&e.skipBits(2);const a=e.readBits(1),l=Math.floor(r/2);return{fscod:i,bsid:n,bsmod:s,acmod:o,lfeon:a,bitRateCode:l}},mn=[1,2,3,6],pn=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;const e=new F(t);e.skipBits(16);const i=e.readBits(2);if(e.skipBits(3),i!==0&&i!==2)return null;const r=e.readBits(11),n=e.readBits(2);let s=0,o;n===3?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),l=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const d=mn[o];let u;return n<3?u=Hr[n]/1e3:u=Nr[s]/1e3,{dataRate:Math.round((r+1)*u/(d*16)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:l,numDepSub:0,chanLoc:0}]}},gn=1683496997,wn=18,yn=10,di=32,bn=20,Tn=8,Cn=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],vn=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],En=[16,16,20,20,0,24,24,0],ui=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Sn=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],xn=8,_n=[32e3,44100,48e3,0],Bn=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Pn=[512,1024,2048,4096],kn=t=>{const e=An(t),i=me(t);let r=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;r+4<=t.length&&i.getUint32(r)===gn;){const o=In(t.subarray(r));if(!o)break;n??=o,r+=o.frameSize}if(e)return{frameSize:n?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!n?.asset)return null;const{asset:s}=n;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},An=t=>{if(t.length<wn||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;const e=new F(t);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==di-1)return null;const i=e.readBits(1),r=e.readBits(7)+1;if(r%Tn!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=ui.length)return null;const o=Cn[e.readBits(4)];if(o===0)return null;const a=vn[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const l=e.readBits(2);if(l===3)return null;e.skipBits(1),i&&e.skipBits(16),e.skipBits(7);const c=En[e.readBits(3)];if(c===0)return null;const d=l!==0;return{frameSize:n,sampleRate:o,numberOfChannels:ui[s]+(d?1:0),sampleCount:r*di,channelLayout:Sn[s]|(d?xn:0),amode:s,lfePresent:d,bitRate:a,pcmResolution:c}},In=t=>{if(t.length<yn||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;const e=new F(t);e.skipBits(32),e.skipBits(8);const i=e.readBits(2),r=e.readBits(1),n=8+4*r,s=16+4*r;e.skipBits(n);const o=e.readBits(s)+1,a={frameSize:o,asset:null};if(!e.readBits(1))return a;const l=_n[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const d=e.readBits(3)+1,u=e.readBits(3)+1,f=[];for(let b=0;b<d;b++)f.push(e.readBits(i+1));for(const b of f)e.skipBits(8*Cr(b));if(e.readBits(1)){e.skipBits(2);const b=e.readBits(2)+1<<2,E=e.readBits(2)+1;e.skipBits(E*b)}for(let b=0;b<u;b++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,m=Bn[e.readBits(4)],w=e.readBits(8)+1;let T=0;if(e.readBits(1)&&(w>2&&e.skipBits(1),w>6&&e.skipBits(1),e.readBits(1))){const b=e.readBits(2)+1<<2;T=e.readBits(b)}return l===0||e.getBitsLeft()<0?a:{frameSize:o,asset:{sampleRate:m,numberOfChannels:w,sampleCount:Math.round(c*m/l),channelLayout:T,pcmResolution:h}}},Rn=t=>{const e=new Uint8Array(bn),i=me(e);i.setUint32(0,t.sampleRate),i.setUint32(4,t.bitRate),i.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const r=t.core&&!t.hasExtensions?1:0,n=new F(e);return n.seekToByte(13),n.writeBits(2,Math.max(Pn.indexOf(t.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e};const fi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Mn=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%(3600*1e3)/(60*1e3)),r=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Fn=function(t,e,i){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},On=(function(t){return function(e){function i(o){e.error=e.hasError?new t(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var r,n=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&n===1)return n=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(s,function(a){return i(a),s()})}else n|=1}catch(a){i(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});Rr();let hi=-1/0,mi=-1/0,ut=null;typeof FinalizationRegistry<"u"&&(ut=new FinalizationRegistry(t=>{const e=performance.now();t.type==="video"?(e-hi>=1e3&&(A._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),hi=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-mi>=1e3&&(A._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),mi=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class Ce{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ft=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],zn=new Set(ft);class D{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ke*this.timestamp)}get microsecondDuration(){return Math.trunc(ke*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||typeof i!="object")throw new TypeError("init must be an object.");if(i.format===void 0||!zn.has(i.format))throw new TypeError("init.format must be one of: "+ft.join(", "));if(!Number.isInteger(i.codedWidth)||i.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(i.codedHeight)||i.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(i.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(i.duration!==void 0&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const s of i.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.visibleRect!==void 0&&st(i.visibleRect,"init.visibleRect"),i.displayWidth!==void 0&&(!Number.isInteger(i.displayWidth)||i.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(i.displayHeight!==void 0&&(!Number.isInteger(i.displayHeight)||i.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(i.displayWidth!==void 0!=(i.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=i.format,this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0;const r=i.layout??Vn(i.format,i.codedWidth,i.codedHeight);let n=i.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},i.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180===0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=i._doNotCopy?G(e):G(e).slice(),this._layout=r,this.colorSpace=new ht(n)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(i?.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(i?.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(i?.timestamp!==void 0&&!Number.isFinite(i?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(i?.duration!==void 0&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");i?.visibleRect!==void 0&&st(i.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.flip=i?.flip??!1,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6;const{primaries:r,transfer:n,matrix:s,fullRange:o}=e.colorSpace;this.colorSpace=new ht({primaries:r!==null&&r in _e?r:null,transfer:n!==null&&n in Be?n:null,matrix:s!==null&&s in Pe?s:null,fullRange:o})}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!i||typeof i!="object")throw new TypeError("init must be an object.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(i.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(i.duration!==void 0&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(i.visibleRect!==void 0&&st(i.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new D(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*ke),duration:Math.trunc((i.duration??0)*ke)||void 0,visibleRect:i.visibleRect&&{x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height}}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const s=i.visibleRect??{left:0,top:0,width:r,height:n},o=new OffscreenCanvas(s.width,s.height),a=o.getContext("2d",{alpha:Ne(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-s.left,-s.top),this._data=o,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:s.width,height:s.height},this.squarePixelWidth=s.width,this.squarePixelHeight=s.height,this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new ht({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Ce){if(!i||typeof i!="object")throw new TypeError("init must be an object.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(i.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(i.duration!==void 0&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!ft.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=i?.encodeOptions??{},this.pixelAspectRatio=Gt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),ut?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),this._data instanceof Ce?new D(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Fe(this._data)?new D(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(p(this._layout),new D(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new D(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(ut?.unregister(this),this._data instanceof Ce?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Fe(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(yi(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Fe(this._data)?this._data.allocationSize(e):bi(this,e).allocationSize}async copyTo(e,i={}){if(!et(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yi(i),this._closed)throw new Error("VideoSample is closed.");if((i.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(p(this._data!==null),Fe(this._data))return this._data.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format))if(this._data instanceof Ce){const c={stack:[],error:void 0,hasError:!1};try{const d=Fn(c,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},i.colorSpace??"srgb"),!1);if(!(d instanceof D))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(d.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${d.format}' instead.`);return await d.copyTo(e,i)}catch(d){c.error=d,c.hasError=!0}finally{On(c)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const c=this.toVideoFrame(),d=await c.copyTo(e,i);return c.close(),d}const r=bi(this,i);p(this.format);const n=G(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const s=De(this.format);let o;if(this._data instanceof Ce){let c=this._data.getDataPlanes();if(Te(c)&&(c=await c),!Array.isArray(c)||c.some(d=>!(d.data instanceof Uint8Array)||!Number.isInteger(d.stride)||d.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=c}else if(this._data instanceof Uint8Array)p(this._layout),p(this._layout.length===s.length),o=this._layout.map((c,d)=>{const u=Math.ceil(this.codedHeight/s[d].heightDivisor);return{data:this._data.subarray(c.offset,c.offset+c.stride*u),stride:c.stride}});else{const d=this._data.getContext("2d");p(d);const u=d.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:G(u.data),stride:4*this.codedWidth}]}const a=[],l=s.length;for(let c=0;c<l;c++){const d=r.computedLayouts[c],u=o[c].stride,f=o[c].data;let h=d.sourceTop*u;h+=d.sourceLeftBytes;let m=d.destinationOffset;const w=d.sourceWidthBytes,T={offset:m,stride:d.destinationStride};for(let b=0;b<d.sourceHeight;b++){if(h+w>f.byteLength)throw new Error("Source buffer OOB read.");if(m+w>n.byteLength)throw new Error("Destination buffer OOB write.");const E=f.subarray(h,h+w);n.set(E,m),h+=u,m+=d.destinationStride}a.push(T)}if(i.format!==void 0){const c=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),d=this.format.includes("X")&&i.format.includes("A");if(c||d)for(let u=0;u<r.allocationSize;u+=4){if(c){const f=n[u],h=n[u+2];n[u]=h,n[u+2]=f}d&&(n[u+3]=255)}}return a}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Ce){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(Te(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const i=e.reduce((o,a)=>o+a.data.byteLength,0),r=new Uint8Array(i);let n=0;const s=[];for(const o of e)r.set(o.data,n),s.push(n),n+=o.data.byteLength;return new VideoFrame(r,{format:this.format,layout:e.map((o,a)=>({offset:s[a],stride:o.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Fe(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(p(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,i,r,n,s,o,a,l,c){let d=0,u=0,f=this.displayWidth,h=this.displayHeight,m=0,w=0,T=this.displayWidth,b=this.displayHeight;if(o!==void 0?(d=i,u=r,f=n,h=s,m=o,w=a,l!==void 0?(T=l,b=c):(T=f,b=h)):(m=i,w=r,n!==void 0&&(T=n,b=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(w))throw new TypeError("dy must be a number.");if(!Number.isFinite(T)||T<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:f,sHeight:h}=this._unmapSourceRegion(d,u,f,h,this.rotation,this.flip));const E=this.toCanvasImageSource();e.save();const x=m+T/2,k=w+b/2;e.translate(x,k),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const M=this.rotation%180===0?1:T/b;e.scale(1/M,M),e.drawImage(E,d,u,f,h,-T/2,-b/2,T,b),e.restore()}drawWithFit(e,i){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(i.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");i.crop!==void 0&&mt(i.crop,"options.");const r=e.canvas.width,n=e.canvas.height,s=i.rotation??this.rotation,o=i.flip??this.flip,[a,l]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=i.crop;c&&(c=wi(c,a,l));let d,u,f,h;const{sx:m,sy:w,sWidth:T,sHeight:b}=this._unmapSourceRegion(i.crop?.left??0,i.crop?.top??0,i.crop?.width??a,i.crop?.height??l,s,o);if(i.fit==="fill")d=0,u=0,f=r,h=n;else{const[x,k]=i.crop?[i.crop.width,i.crop.height]:[a,l],M=i.fit==="contain"?Math.min(r/x,n/k):Math.max(r/x,n/k);f=x*M,h=k*M,d=(r-f)/2,u=(n-h)/2}e.save();const E=s%180===0?1:f/h;e.translate(r/2,n/2),o&&e.scale(-1,1),e.rotate(s*Math.PI/180),e.scale(1/E,E),e.translate(-r/2,-n/2),e.drawImage(this.toCanvasImageSource(),m,w,T,b,d,u,f,h),e.restore()}_unmapSourceRegion(e,i,r,n,s,o){return o&&(e=(s%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-r),s===90?[e,i,r,n]=[i,this.squarePixelHeight-e-r,n,r]:s===180?[e,i]=[this.squarePixelWidth-e-r,this.squarePixelHeight-i-n]:s===270&&([e,i,r,n]=[this.squarePixelWidth-i-n,e,n,r]),{sx:e,sy:i,sWidth:r,sHeight:n}}_drawWithFitAndMipmapping(e,i,r){const n=e.width,s=e.height,[o,a]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],l=r.crop?r.crop.width:o,c=r.crop?r.crop.height:a;let d=0;2*n<l&&2*s<c&&(d=Math.floor(Math.log2(Math.min(l/n,c/s))));const u=n*2**d,f=s*2**d,{canvas:h,context:m,isNew:w}=d>0?gi(u,f):{canvas:e,context:i,isNew:r.targetIsFresh};m.imageSmoothingQuality="high",r.fillBlack?(m.fillStyle="black",m.fillRect(0,0,u,f)):w||m.clearRect(0,0,u,f),this.drawWithFit(m,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),m.globalCompositeOperation="copy";for(let T=d;T>1;T--){const b=n*2**T,E=s*2**T;m.drawImage(h,0,0,b,E,0,0,b/2,E/2)}m.globalCompositeOperation="source-over",d>0&&(i.imageSmoothingQuality="high",i.globalCompositeOperation="copy",i.drawImage(h,0,0,2*n,2*s,0,0,n,s),i.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Ce||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&mt(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const{rotation:i,flip:r}=hr(this.rotation,this.flip,e.rotate??0,e.flip??!1),[n,s]=i%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=wi(o,n,s));const a=o?o.width:n,l=o?o.height:s,c=a/l;let d,u;e.width!==void 0&&e.height===void 0?(d=e.width,u=d/c):e.width===void 0&&e.height!==void 0?(u=e.height,d=u*c):e.width!==void 0&&e.height!==void 0?(d=e.width,u=e.height):(d=a,u=l),d=Dt(d,e.roundDimensionsTo??1),u=Dt(u,e.roundDimensionsTo??1);const f={width:d,height:u,fit:e.fit??"fill",rotation:i,flip:r,crop:o??{left:0,top:0,width:n,height:s},alpha:e.alpha??"keep"};for(const T of Wn){let b=T(this,f);if(Te(b)&&(b=await b),b!==null)return b}const{canvas:h,context:m,isNew:w}=gi(f.width,f.height);return this._drawWithFitAndMipmapping(h,m,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:w,fillBlack:f.alpha==="discard"}),new D(h,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setFlip(e){if(typeof e!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Wn=[],Ln=3,Me=[];let pi=0;const gi=(t,e)=>{for(const n of Me)if(n.canvas.width===t&&n.canvas.height===e)return n.age=pi++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if(typeof OffscreenCanvas<"u")i=new OffscreenCanvas(t,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=t,i.height=e}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Me.length>=Ln&&Me.splice(Fr(Me,n=>n.age),1),Me.push({canvas:i,context:r,age:pi++}),{canvas:i,context:r,isNew:!0}};class ht{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const i=Object.keys(_e);if(e.primaries!=null&&!i.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(Be);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const n=Object.keys(Pe);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Fe=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,wi=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),s=Math.min(t.width,e-r),o=Math.min(t.height,i-n);return p(s>=0),p(o>=0),{left:r,top:n,width:s,height:o}},mt=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},yi=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Vn=(t,e,i)=>{const r=De(t),n=[];let s=0;for(const o of r){const a=Math.ceil(e/o.widthDivisor),l=Math.ceil(i/o.heightDivisor),c=a*o.sampleBytes,d=c*l;n.push({offset:s,stride:c}),s+=d}return n},De=t=>{const e=(i,r,n,s,o)=>{const a=[{sampleBytes:i,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:n,heightDivisor:s},{sampleBytes:r,widthDivisor:n,heightDivisor:s}];return o&&a.push({sampleBytes:i,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:be(t),p(!1)}},bi=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Un(i,r,t.codedWidth,t.codedHeight,t.format),s=e.layout;let o;if(!e.format||e.format===t.format)o=t.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))o=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Nn(n,o,s)},Un=(t,e,i,r,n)=>{const s={...t};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!Hn(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Hn=(t,e)=>{if(t===null)return!0;const i=De(t);for(let r=0;r<i.length;r++){const n=i[r],s=n.widthDivisor,o=n.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%o!==0)return!1}return!0},Nn=(t,e,i)=>{const r=De(e),n=r.length;if(i!==void 0&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const o=[],a=[];for(let l=0;l<n;l++){const c=r[l],d=c.sampleBytes,u=c.widthDivisor,f=c.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(t.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(t.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/u)*d,h.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/u)*d,i!==void 0){const T=i[l];if(T.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${l} is too small.`);h.destinationOffset=T.offset,h.destinationStride=T.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const w=h.destinationStride*h.sourceHeight+h.destinationOffset;if(w>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(w),s=Math.max(s,w);for(let T=0;T<l;T++){const b=o[T];if(!(a[l]<=b.destinationOffset||a[T]<=h.destinationOffset))throw new TypeError("Planes overlap.")}o.push(h)}return{allocationSize:s,computedLayouts:o}};const Ti=new Map,qn=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!fe.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${fe.join(", ")}.`);const e=t.bitrate;if(t.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(t.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(t.quality!==void 0&&!(t.quality instanceof pe))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof pe)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.transform!==void 0){if(typeof t.transform!="object"||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(t.transform.width!==void 0&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(t.transform.height!==void 0&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(t.transform.fit!==void 0&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.transform.width!==void 0&&t.transform.height!==void 0&&t.transform.fit===void 0&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(t.transform.fit!==void 0&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(t.transform.rotate!==void 0&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(t.transform.flip!==void 0&&typeof t.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(t.transform.crop!==void 0&&mt(t.transform.crop,"config.transform."),t.transform.process!==void 0&&typeof t.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(t.transform.frameRate!==void 0&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(t.transform.force!==void 0&&typeof t.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(t.onEncodedSample!==void 0&&typeof t.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Ci(t.codec,t)},Ci=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const i=e.bitrateMode;if(i!==void 0&&!["constant","variable"].includes(i))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&vt(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},vi=t=>{const e=t.bitrateMode,i=t.quality._toVideoRateControl(t.codec,t.width,t.height,e),r=(s,o,a)=>({codec:t.fullCodecString??cs(t.codec,t.width,t.height,a,t.alpha==="keep"),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:s,bitrateMode:o,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...hs(t.codec)}),n=[];return i.quantizer!==null&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),i.bitrateMode!=="quantizer"&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),p(n.length>0),n};class pe{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in Ei):typeof e.quality!="number"||Number.isNaN(e.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(e.preferBitrate!==void 0&&typeof e.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?Ei[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,i,r,n){const s=Dn[e];let o=null,a=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(s)if(this._quantizer<s.min||this._quantizer>s.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${s.min} and ${s.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(a="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&s&&!this._preferBitrate&&(p(this._quality!==void 0),o=qt(Math.round(br(s.worst,s.best,this._quality)),s.min,s.max));let l;if(this._bitrate!==void 0)l=this._bitrate;else{let c=this._quality;c===void 0&&(p(o!==null&&s),c=qt((o-s.worst)/(s.best-s.worst),0,1)),l=Si(e,i,r,pt(c))}return{quantizer:o,bitrate:l,bitrateMode:a}}_toVideoBitrate(e,i,r){return this._bitrate!==void 0?this._bitrate:(p(this._quality!==void 0),Si(e,i,r,pt(this._quality)))}_toAudioBitrate(e){if(Ee.includes(e)||e==="flac"||e==="truehd")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const i=pt(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let s=n*i;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,l)=>Math.abs(l-s)<Math.abs(a-s)?l:a):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,l)=>Math.abs(l-s)<Math.abs(a-s)?l:a)),Math.round(s/1e3)*1e3}}const Ei={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Dn={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(Pr()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},pt=t=>.3*Math.exp(2.5538*t),Si=(t,e,i,r)=>{const n=e*i,s=1920*1080,o=3e6,a=Math.pow(n/s,.95),l=o*a,c={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/o},u=l*c[t]*r;return Math.ceil(u/1e3)*1e3},xi=(t,e)=>{if(t==="avc")return{avc:{quantizer:e}};if(t==="hevc")return{hevc:{quantizer:e}};if(t==="vp9")return{vp9:{quantizer:e}};if(t==="av1")return{av1:{quantizer:e}};p(!1)},$n=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:s,frameRate:o,...a}=e;if(!fe.includes(t))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof pe))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof pe)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Ci(t,a);const l=_i(n,s)??new pe("medium");let c;try{c=vi({codec:t,width:i,height:r,quality:l,framerate:o,...a,alpha:"discard"})}catch{return!1}const d=JSON.stringify(c),u=Ti.get(d);if(u)return u;const f=(async()=>{for(const{config:m}of c)if(Bi.some(w=>w.supports(t,m)))return!0;if(typeof VideoEncoder>"u"||(i%2===1||r%2===1)&&t==="avc")return!1;for(const{config:m,quantizer:w}of c){try{if(!(await VideoEncoder.isConfigSupported(m)).supported)continue}catch{continue}if(!Ne()||await new Promise(async b=>{try{const E=new VideoEncoder({output:()=>{},error:()=>b(!1)});E.configure(m);const x=new Uint8Array(i*r*4),k=new VideoFrame(x,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});E.encode(k,w!==null?xi(t,w):void 0),k.close(),await E.flush(),b(!0)}catch{b(!1)}}))return!0}return!1})();return Ti.set(d,f),f},_i=(t,e)=>{if(t!==void 0)return t;if(e!==void 0)return e instanceof pe?e:new pe({bitrate:e})};const Bi=[];const Pi=new Uint8Array(0);class ve{constructor(e,i,r,n,s=-1,o,a){if(this.data=e,this.type=i,this.timestamp=r,this.duration=n,this.sequenceNumber=s,e===Pi&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Pi}get microsecondTimestamp(){return Math.trunc(ke*this.timestamp)}get microsecondDuration(){return Math.trunc(ke*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new ve(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new ve(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const jn=2082844800,Gn=t=>{let i=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const r=[...new Set(t.codecStrings)];i+=`; codecs="${r.join(", ")}"`}return i};const gt=7,Qn=9,ki=t=>{const e=t.filePos;if(t.remainingLength<gt)return null;const i=Xn(t,gt),r=new F(i);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const o=r.readBits(1),a=r.readBits(2)+1,l=r.readBits(4);if(l>=at.length)return null;r.skipBits(1);const c=r.readBits(3);if(c===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const d=r.readBits(13);r.skipBits(11);const u=r.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;if(o===0){if(t.remainingLength<2)return null;f=Kn(t)}return d<t.filePos-e?null:{objectType:a,samplingFrequencyIndex:l,channelConfiguration:c,frameLength:d,numberOfAacFrames:u,crcCheck:f,startPos:e}};class Oe{constructor(e,i,r,n,s){this.bytes=e,this.view=i,this.offset=r,this.start=n,this.end=s,this.bufferPos=n-r}static tempFromBytes(e){return new Oe(e,me(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new Oe(this.bytes,this.view,this.offset,e,e+i)}}const Ai=(t,e)=>{if(e<0||t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Xn=(t,e)=>{Ai(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},Kn=t=>{Ai(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e};const wt=8,Ii=16;var Yn=function(t,e,i){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},Zn=(function(t){return function(e){function i(o){e.error=e.hasError?new t(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var r,n=0;function s(){for(;r=e.stack.pop();)try{if(!r.async&&n===1)return n=0,e.stack.push(r),Promise.resolve().then(s);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(s,function(a){return i(a),s()})}else n|=1}catch(a){i(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});class yt{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class Ri extends yt{constructor(e){if(super(),!fe.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${fe.join(", ")}.`);this._codec=e}}const Mi=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Jn{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,i){this.source=e,this.encodingConfig=i,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new xr,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,i,r){const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const s=this.encodingConfig,o=s.sizeChangeBehavior??"deny";let a=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(a=!0,o==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.flip!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||a&&o!=="passThrough"){let u=s.transform?.width,f=s.transform?.height,h=s.transform?.fit??"fill";a&&o!=="passThrough"&&(p(this.outputWidth),p(this.outputHeight),p(o!=="deny"),u=this.outputWidth,f=this.outputHeight,h=o);const m=await e.transform({width:u,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,flip:s.transform?.flip,fit:h,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=m.displayWidth,this.outputHeight=m.displayHeight),i&&e.close(),e=m,i=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const d=s.transform?.frameRate;if(d!==void 0){const u=e.timestamp+e.duration,f=$t(e.timestamp,d);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=u;return}else await this.padFrameRate(f,r);e===n&&(e=e.clone(),i=!0),e.setTimestamp(f),e.setDuration(1/d),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=u}await this.processAndEncode(e,r)}finally{i&&e.close()}}async processAndEncode(e,i){const r=this.encodingConfig;let n;if(r.transform?.process){let s=r.transform.process(e);if(Te(s)&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);const o=[];try{for(const a of s)a instanceof D?o.push(a):typeof VideoFrame<"u"&&a instanceof VideoFrame?o.push(new D(a)):o.push(new D(a,{timestamp:e.timestamp,duration:e.duration}))}catch(a){for(const l of o)l!==e&&l.close();for(const l of s)(l instanceof D&&l!==e||typeof VideoFrame<"u"&&l instanceof VideoFrame)&&l.close();throw a}n=o}else n=[e];try{for(const s of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();const o=this.encodingConfig.keyFrameInterval??2,a=Math.floor(s.timestamp/o),l={...this.defaultEncodeOptions,...s.encodeOptions,...i},c={...l,keyFrame:l.keyFrame!==void 0?l.keyFrame:o===0||a!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=a,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;const d=s.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(d,c)).catch(f=>this.setError(f)).finally(()=>{this.customEncoderQueueSize--,d.close()});this.customEncoderQueueSize>=4&&await u}else{p(this.encoder);const d=s.toVideoFrame(),u=Ht(this.preciseTimings,d.timestamp,h=>h.microsecondTimestamp),f=u!==-1?this.preciseTimings[u]:null;if(f&&f.microsecondTimestamp===d.timestamp?(f.timestamp!==s.timestamp&&(f.timestampIsValid=!1),f.duration!==s.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(u+1,0,{microsecondTimestamp:d.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!d.format&&!d.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(d,c)}finally{d.close()}}else{this.splitter||(this.splitter=new is);const{colorFrame:m,alphaFrame:w}=await this.splitter.split(d);this.alphaFrameQueue.push(w);try{this.encoder.encode(m,c)}finally{m.close()}}else try{this.encoder.encode(d,c)}finally{d.close()}this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const s of n)s!==e&&s.close()}}async padFrameRate(e,i){const r=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*r);for(let s=1;s<n;s++){const o={stack:[],error:void 0,hasError:!1};try{const a=Yn(o,this.frameRateLastSample.clone(),!1);a.setTimestamp(this.frameRateLastTimestamp+s/r),a.setDuration(1/r),await this.processAndEncode(a,i)}catch(a){o.error=a,o.hasError=!0}finally{Zn(o)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const i=_i(this.encodingConfig.quality,this.encodingConfig.bitrate);p(i!==void 0);const r=vi({...this.encodingConfig,quality:i,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});let n=null,s;for(const a of r){const l=a.config;if(this.encodingConfig.onEncoderConfig?.(l),s=Bi.find(d=>d.supports(this.encodingConfig.codec,l)),s){n=a;break}if(typeof VideoEncoder>"u")continue;if(l.alpha="discard",this.encodingConfig.alpha==="keep"&&(l.latencyMode="quality"),(l.width%2===1||l.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${l.width}x${l.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(l)).supported){n=a;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(kr("VideoEncoder"));const a=r[0].config,l=r.map(({config:c,quantizer:d})=>d!==null?`quantizer ${d}`:`${c.bitrate} bps`);throw new Error(`This specific encoder configuration (${a.codec}, ${l.join(" / ")}, ${a.width}x${a.height}, hardware acceleration: ${a.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const o=n.config;n.quantizer!==null?this.defaultEncodeOptions=xi(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=o.bitrate??null,s?(this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(a,l)=>{if(!(a instanceof ve))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Mi(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,l),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,l).catch(c=>{this.setError(c)})},this.customEncoder.onError=a=>{this.setError(a)},await this.customEncoder.init()):(this.encoderConfig=o,this.encodingConfig.codec==="avc"&&Ne()&&(this.chunkTimestampsAreShiftedByDuration=await ts()),this.createWebCodecsEncoders()),p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const e=this.encoderConfig;p(e);const i=[],r=[];let n=0,s=0;const o=(l,c)=>{if(Ar(l)){this.encodersReclaimed=!0;return}l.stack=c,this.setError(l)},a=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(l,c)=>{if(!this.alphaEncoder){this.addPacket(l,null,c);return}const d=this.alphaFrameQueue.shift();p(d!==void 0),d?(this.alphaEncoder.encode(d,{...this.defaultEncodeOptions,keyFrame:l.type==="key"}),s++,d.close(),i.push({chunk:l,meta:c})):s===0?this.addPacket(l,null,c):(r.push(n+s),i.push({chunk:l,meta:c}))},error:l=>o(l,a)}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const l=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(c,d)=>{s--;const u=i.shift();for(p(u!==void 0),this.addPacket(u.chunk,c,u.meta),n++;r.length>0&&r[0]===n;){r.shift();const f=i.shift();p(f!==void 0),this.addPacket(f.chunk,null,f.meta)}},error:c=>o(c,l)}),this.alphaEncoder.configure(e)}}addPacket(e,i,r){const n={};if(i){const u=new Uint8Array(i.byteLength);i.copyTo(u),n.alpha=u}let s=ve.fromEncodedChunk(e,n);const o=this.encoderConfig;if(p(o),r?.decoderConfig&&(r.decoderConfig.codec=ds({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?G(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:o.codec.includes("avc1.")?1:o.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?ti(s.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?si(s.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?sn(s.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?on(s.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&Ne())){const u=jr(G(r.decoderConfig.description));let f=u?.sequenceParameterSets[0];if(f&&f[0]===f[1]){p(u),f=f.subarray(1);let h=u.pictureParameterSets[0];h&&(h=h.subarray(1));const m=ii({...u,sequenceParameterSets:[f],pictureParameterSets:h?[h]:[]});r.decoderConfig.description=m}}let a=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(a-=e.duration??0,s=s.clone({timestamp:a/1e6}));const l=Ht(this.preciseTimings,a,u=>u.microsecondTimestamp),c=l!==-1?this.preciseTimings[l]:null;let d=null;this.emittedEncoderPackets===0&&s.type==="delta"&&r?.decoderConfig&&(d=un(this.encodingConfig.codec,r.decoderConfig,s.data)),(c&&c.microsecondTimestamp===a||d!==null)&&(s=s.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:d??void 0})),Mi(this.source._connectedTrack,s),this.encodingConfig.onEncodedPacket?.(s,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,r).catch(u=>{this.setError(u)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){p(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){const i=this.encodingConfig.transform.frameRate,r=$t(this.frameRateLastEndTimestamp,i);await this.padFrameRate(r)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Or(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(i=>this.setError(i)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(i=>i?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let es=null;const ts=()=>es??=(async()=>{let t=null;const e=new VideoEncoder({output:i=>{t??=i.timestamp},error:()=>{}});try{e.configure({codec:"avc1.64001f",width:1280,height:720});const i=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});e.encode(i,{keyFrame:!0}),i.close(),await e.flush()}catch{return!1}finally{e.state!=="closed"&&e.close()}return t===500})();let bt=null;class is{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!bt){const n=new Blob([`(${rs.toString()})()`],{type:"application/javascript"});bt=URL.createObjectURL(n)}this.worker=new Worker(bt),this.worker.addEventListener("message",n=>{const s=n.data,o=this.pendingRequests.get(s.id);o&&(this.pendingRequests.delete(s.id),"error"in s?o.reject(new Error(s.error)):o.resolve({colorFrame:s.colorFrame,alphaFrame:s.alphaFrame}))}),this.worker.addEventListener("error",n=>{const s=new Error(n.message||"Color/alpha splitter worker error.");for(const o of this.pendingRequests.values())o.reject(s);this.pendingRequests.clear()})}const i=this.nextRequestId++,r=Nt();return this.pendingRequests.set(i,r),this.worker.postMessage({id:i,sourceFrame:e},{transfer:[e]}),r.promise}close(){this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()}}const rs=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:o,sourceFrame:a}=s.data;e=e.then(async()=>{try{const{colorFrame:l,alphaFrame:c}=await i(a);self.postMessage({id:o,colorFrame:l,alphaFrame:c},{transfer:[l,c]})}catch(l){self.postMessage({id:o,error:l.message})}finally{a.close()}})});const i=async s=>{const o=s.format;if(!o)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const a=s.allocationSize();if((!t||t.byteLength!==a)&&(t=new Uint8Array(a)),await s.copyTo(t),o==="RGBA"||o==="BGRA")return r(t,o,s);if(o==="I420A"||o==="I420AP10"||o==="I420AP12"||o==="I422A"||o==="I422AP10"||o==="I422AP12"||o==="I444A"||o==="I444AP10"||o==="I444AP12")return n(t,o,s);throw new Error(`CPU color/alpha splitting does not support format '${o}'.`)},r=(s,o,a)=>{const l=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,d=l*c,u=Math.ceil(l/2),f=Math.ceil(c/2),h=d+u*f*2,m=new Uint8Array(h);for(let E=0,x=3;E<d;E++,x+=4)m[E]=s[x];m.fill(128,d);const w=new VideoFrame(s,{format:o==="RGBA"?"RGBX":"BGRX",codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),T={format:"I420",codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[m.buffer]},b=new VideoFrame(m,T);return{colorFrame:w,alphaFrame:b}},n=(s,o,a)=>{const l=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,d=o.includes("P10"),u=o.includes("P12"),f=d||u?2:1;let h,m;o.startsWith("I420")?(h=Math.ceil(l/2),m=Math.ceil(c/2)):o.startsWith("I422")?(h=Math.ceil(l/2),m=c):(h=l,m=c);const w=l*c,T=h*m,b=w*f,E=T*f,x=w*f,k=b+E*2,M=o.replace("A",""),O=Math.ceil(l/2),z=Math.ceil(c/2),H=O*z,L=H*f,V=x+2*L,U=new Uint8Array(V),R=k;U.set(s.subarray(R,R+x),0);const N=x,X=d?512:u?2048:128;f===1?U.fill(X,N):new Uint16Array(U.buffer,N,2*H).fill(X);const q=d?"I420P10":u?"I420P12":"I420",W=new VideoFrame(s.subarray(0,k),{format:M,codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),te={format:q,codedWidth:l,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[U.buffer]},ie=new VideoFrame(U,te);return{colorFrame:W,alphaFrame:ie}}};class ns extends Ri{constructor(e){qn(e),super(e.codec),this._encoder=new Jn(this,e)}add(e,i){if(!(e instanceof D))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class ss extends yt{constructor(e){if(super(),!$e.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${$e.join(", ")}.`);this._codec=e}}class os extends yt{constructor(e){if(super(),!ze.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ze.join(", ")}.`);this._codec=e}}const fe=["avc","hevc","vp9","av1","vp8","prores"],Ee=["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"],Tt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],$e=[...Tt,...Ee],ze=["webvtt"],je=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Fi=[{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}],ge=[{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}],Oi=[{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}],zi=".01.01.01.01.00",Wi=".0.110.01.01.01.0",We=["ap4x","ap4h","apch","apcn","apcs","apco"],Ct=["dtsc","dtsh","dtsl","dtse"],as=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],cs=(t,e,i,r,n)=>{if(t==="avc"){const s=_r(),o=s?66:100,a=Math.ceil(e/16)*Math.ceil(i/16),l=je.find(h=>a<=h.maxMacroblocks&&r<=h.maxBitrate)??j(je),c=l?l.level:0,d=o.toString(16).padStart(2,"0"),u=s?"40":"00",f=c.toString(16).padStart(2,"0");return`avc1.${d}${u}${f}`}else if(t==="hevc"){const l=e*i,c=Fi.find(u=>l<=u.maxPictureSize&&r<=u.maxBitrate)??j(Fi);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const o=e*i;return`vp09.00.${(ge.find(c=>o<=c.maxPictureSize&&r<=c.maxBitrate)??j(ge)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){const o=e*i,a=Oi.find(d=>o<=d.maxPictureSize&&r<=d.maxBitrate)??j(Oi);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}else if(t==="prores"){const o=Math.pow(e*i/2073600,.95),a=as.filter(d=>d.alpha===n);let l=a[0].fourCc,c=1/0;for(const{fourCc:d,bitrate:u}of a){const f=Math.abs(u*o-r);f<c&&(c=f,l=d)}return l}else be(t)}throw new TypeError(`Unhandled codec '${String(t)}'.`)},ls=t=>{const e=t.split("."),n=(1<<7)+1,s=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),l=(s<<5)+a,c=o.slice(-1)==="H"?1:0,d=Number(e[3]),u=d===8?0:1,f=d===12?1:0,h=e[4]?Number(e[4]):0,m=e[5]?Number(e[5][0]):1,w=e[5]?Number(e[5][1]):1,T=e[5]?Number(e[5][2]):0,b=(c<<7)+(u<<6)+(f<<5)+(h<<4)+(m<<3)+(w<<2)+T;return[n,l,b,0]},ds=t=>{const{codec:e,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:a,proresFormat:l}=t;if(e==="avc"){if(p(t.avcType!==null),n){const c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Vt(c)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Vt(i.subarray(1,4))}`}else if(e==="hevc"){let c,d,u,f,h,m;if(s)c=s.generalProfileSpace,d=s.generalProfileIdc,u=Ut(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,m=[...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 T=me(i),b=T.getUint8(1);c=b>>6&3,d=b&31,u=Ut(T.getUint32(2)),f=b>>5&1,h=T.getUint8(12),m=[];for(let E=0;E<6;E++)m.push(T.getUint8(6+E))}let w="hev1.";for(w+=["","A","B","C"][c]+d,w+=".",w+=u.toString(16).toUpperCase(),w+=".",w+=f===0?"L":"H",w+=h;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(w+=".",w+=m.map(T=>T.toString(16).toUpperCase()).join(".")),w}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){const E=t.width*t.height;let x=j(ge).level;for(const k of ge)if(E<=k.maxPictureSize){x=k.level;break}return`vp09.00.${x.toString().padStart(2,"0")}.08`}const c=o.profile.toString().padStart(2,"0"),d=o.level.toString().padStart(2,"0"),u=o.bitDepth.toString().padStart(2,"0"),f=o.chromaSubsampling.toString().padStart(2,"0"),h=o.colourPrimaries.toString().padStart(2,"0"),m=o.transferCharacteristics.toString().padStart(2,"0"),w=o.matrixCoefficients.toString().padStart(2,"0"),T=o.videoFullRangeFlag.toString().padStart(2,"0");let b=`vp09.${c}.${d}.${u}.${f}`;return b+=`.${h}.${m}.${w}.${T}`,b.endsWith(zi)&&(b=b.slice(0,-zi.length)),b}else if(e==="av1"){if(!a){const k=t.width*t.height;let M=j(ge).level;for(const O of ge)if(k<=O.maxPictureSize){M=O.level;break}return`av01.0.${M.toString().padStart(2,"0")}M.08`}const c=a.profile,d=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",f=a.bitDepth.toString().padStart(2,"0"),h=a.monochrome?"1":"0",m=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0);let w,T,b,E;an(a)?(w=a.colourPrimaries,T=a.transferCharacteristics,b=a.matrixCoefficients,E=a.videoFullRangeFlag):(w=r?.primaries?_e[r.primaries]:1,T=r?.transfer?Be[r.transfer]:1,b=r?.matrix?Pe[r.matrix]:1,E=r?.fullRange?1:0);let x=`av01.${c}.${d}${u}.${f}`;return x+=`.${h}.${m.toString().padStart(3,"0")}`,x+=`.${w.toString().padStart(2,"0")}`,x+=`.${T.toString().padStart(2,"0")}`,x+=`.${b.toString().padStart(2,"0")}`,x+=`.${E}`,x.endsWith(Wi)&&(x=x.slice(0,-Wi.length)),x}else{if(e==="prores")return l??"apch";e!==null&&be(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},us=48e3,fs=.4,Li=/^pcm-([usf])(\d+)(be)?$/,Ae=t=>{if(p(Ee.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};const e=Li.exec(t);p(e);let i;e[1]==="u"?i="unsigned":e[1]==="s"?i="signed":i="float";const r=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:i,sampleSize:r,littleEndian:n,silentValue:s}},vt=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":We.includes(t)?"prores":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"||t==="mp4a.40.34"?"mp3":t.startsWith("mp4a.40.")||t==="mp4a.67"?"aac":t==="opus"||t==="Opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":Ct.includes(t)?"dts":t==="mlpa"?"truehd":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Li.test(t)?t:t==="webvtt"?"webvtt":null,hs=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},ms=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...We],ps=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,gs=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ws=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ys=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Vi=(t,e)=>{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(!ms.some(i=>t.decoderConfig.codec.startsWith(i)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny 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.displayAspectWidth!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectWidth!==void 0!=(t.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(t.decoderConfig.description!==void 0&&!et(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){const{colorSpace:i}=t.decoderConfig;if(typeof i!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(_e);if(i.primaries!=null&&!r.includes(i.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(Be);if(i.transfer!=null&&!n.includes(i.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const s=Object.keys(Pe);if(i.matrix!=null&&!s.includes(i.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(i.fullRange!=null&&typeof i.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(!ps.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(!gs.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(!ws.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")){if(!ys.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/.')}else if(We.some(i=>t.decoderConfig.codec.startsWith(i))&&!We.some(i=>t.decoderConfig.codec===i))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${We.join(", ")}.`);if(e!==null&&vt(t.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},bs=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],Ui=(t,e)=>{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(!bs.some(i=>t.decoderConfig.codec.startsWith(i)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny 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&&!et(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/.")}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("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if(t.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if(t.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Ct.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Ct.join(", ")}.`)}else if(t.decoderConfig.codec.startsWith("mlpa")){if(t.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Ee.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ee.join(", ")}).`);if(e!==null&&vt(t.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},Ts=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.")};class Cs{constructor(e){this.mutex=new Lt,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,i,r){let n=this.trackTimestampInfo.get(e);if(n){if(r&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&i<n.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 ${i}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,i)}else{if(!r)throw new Error("First packet must be a key packet.");n={maxTimestamp:i,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}}class Ge{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let i=0;i<e.length;i++)this.helperView.setUint8(i%8,e.charCodeAt(i)),i%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const i=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const r=this.writer.getPos(),n=e.size??r-i;this.writer.seek(i),this.writeBoxHeader(e,n),this.writer.seek(r)}}writeBoxHeader(e,i){this.writeU32(e.largeSize?1:i),this.writeAscii(e.type),e.largeSize&&this.writeU64(i)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const i=this.offsets.get(e);p(i!==void 0);const r=this.writer.getPos();this.writer.seek(i),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let i=this.measureBoxHeader(e);if(e.contents&&(i+=e.contents.byteLength),e.children)for(const r of e.children)r&&(i+=this.measureBox(r));return i}}}const S=new Uint8Array(8),Y=new DataView(S.buffer),I=t=>[(t%256+256)%256],v=t=>(Y.setUint16(0,t,!1),[S[0],S[1]]),Qe=t=>(Y.setInt16(0,t,!1),[S[0],S[1]]),Hi=t=>(Y.setUint32(0,t,!1),[S[1],S[2],S[3]]),g=t=>(Y.setUint32(0,t,!1),[S[0],S[1],S[2],S[3]]),oe=t=>(Y.setInt32(0,t,!1),[S[0],S[1],S[2],S[3]]),J=t=>(Y.setUint32(0,Math.floor(t/2**32),!1),Y.setUint32(4,t,!1),[S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7]]),Ni=t=>(Y.setInt32(0,Math.floor(t/2**32),!1),Y.setUint32(4,t,!1),[S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7]]),qi=t=>(Y.setInt16(0,2**8*t,!1),[S[0],S[1]]),Z=t=>(Y.setInt32(0,2**16*t,!1),[S[0],S[1],S[2],S[3]]),Et=t=>(Y.setInt32(0,2**30*t,!1),[S[0],S[1],S[2],S[3]]),St=(t,e)=>{const i=[];let r=t;do{let n=r&127;r>>=7,i.length>0&&(n|=128),i.push(n)}while(r>0||e);return i.reverse()},B=(t,e=!1)=>{const i=Array(t.length).fill(null).map((r,n)=>t.charCodeAt(n));return e&&i.push(0),i},Di=t=>[Z(t[0]),Z(t[1]),Et(t[2]),Z(t[3]),Z(t[4]),Et(t[5]),Z(t[6]),Z(t[7]),Et(t[8])],C=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),_=(t,e,i,r,n)=>C(t,[I(e),Hi(i),r??[]],n),vs=t=>t.isQuickTime?C("ftyp",[B("qt "),g(512),B("qt ")]):t.fragmented?t.cmaf?C("ftyp",[B("iso5"),g(512),B("iso5"),B("iso6"),B("mp41"),B("cmfc"),B("dash")]):C("ftyp",[B("iso5"),g(512),B("iso5"),B("iso6"),B("mp41")]):C("ftyp",[B("isom"),g(512),B("isom"),t.holdsAvc?B("avc1"):[],B("mp41")]),$i=()=>C("styp",[B("iso5"),g(0),B("iso5"),B("iso6"),B("mp41"),B("cmfc"),B("dash")]),ji=(t,e)=>{const i=Math.max(0,t.minWrittenTimestamp);let r=Math.max(0,t.maxWrittenEndTimestamp-i);return Number.isFinite(r)||(r=0),_("sidx",1,0,[g(1),g(Q),J(P(i,Q)),J(0),v(0),v(1),g(e&2147483647),g(P(r,Q)),g(0)])},Xe=t=>({type:"mdat",largeSize:t}),Es=t=>({type:"free",size:t}),Le=t=>C("moov",void 0,[Ss(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>xs(e,t.creationTime)),t.isFragmented?lo(t.trackDatas):null,Eo(t)]),Ss=(t,e)=>{const i=Math.max(0,...e.map(o=>Math.max(0,P(Ie(o),Q)+P(o.startTimestampOffset??0,Q)))),r=Math.max(0,...e.map(o=>o.track.id))+1,n=!le(t)||!le(i),s=n?J:g;return _("mvhd",+n,0,[s(t),s(t),g(Q),s(i),Z(1),qi(1),Array(10).fill(0),Di(zt),Array(24).fill(0),g(r)])},xs=(t,e)=>{const i=Fo(t),r=t.startTimestampOffset!==null&&t.startTimestampOffset!==0;return C("trak",void 0,[_s(t,e),r?Bs(t):null,Ps(t,e),i.name!==void 0?C("udta",void 0,[C("name",[...ne.encode(i.name)])]):null])},_s=(t,e)=>{const i=Math.max(0,P(Ie(t),Q)+P(t.startTimestampOffset??0,Q)),r=!le(e)||!le(i),n=r?J:g;let s;if(t.type==="video"&&t.track.metadata.transformationMatrix)s=t.track.metadata.transformationMatrix;else if(t.type==="video"){const{rotation:l,flip:c}=t.track.metadata,d=Je(ur(l??0),fr(c?-1:1,1));s=dr(d,t.info.width,t.info.height)}else s=zt;let o=2;t.track.metadata.disposition?.default!==!1&&(o|=1);const a=t.type==="video"?0:t.type==="audio"?1:t.type==="subtitle"?2:be(t);return _("tkhd",+r,o,[n(e),n(e),g(t.track.id),g(0),n(i),Array(8).fill(0),v(0),v(a),qi(t.type==="audio"?1:0),v(0),Di(s),Z(t.type==="video"?t.info.width:0),Z(t.type==="video"?t.info.height:0)])},Bs=t=>{const e=t.startTimestampOffset;if(p(e!==null),e>0){const i=P(e,Q),r=P(Ie(t),Q),n=!le(i)||!le(r),s=n?J:g,o=n?Ni:oe;return C("edts",void 0,[_("elst",n?1:0,0,[g(2),s(i),o(-1),Z(1),s(r),o(0),Z(1)])])}else{const i=P(-e,t.timescale),r=Math.max(0,P(Ie(t),Q)+P(e,Q)),n=!mr(i)||!le(r),s=n?J:g,o=n?Ni:oe;return C("edts",void 0,[_("elst",n?1:0,0,[g(1),s(r),o(i),Z(1)])])}},Ps=(t,e)=>C("mdia",void 0,[ks(t,e),xt(!0,As[t.type],Is[t.type]),Rs(t)]),ks=(t,e)=>{const i=P(Ie(t),t.timescale),r=!le(e)||!le(i),n=r?J:g;return _("mdhd",+r,0,[n(e),n(e),g(t.timescale),n(i),v(er(t.track.metadata.languageCode??Tr)),v(0)])},As={video:"vide",audio:"soun",subtitle:"text"},Is={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},xt=(t,e,i,r="\0\0\0\0")=>_("hdlr",0,0,[t?B("mhlr"):g(0),B(e),B(r),g(0),g(0),B(i,!0)]),Rs=t=>C("minf",void 0,[Ms[t.type](),Fs(),Ws(t)]),Ms={video:()=>_("vmhd",0,1,[v(0),v(0),v(0),v(0)]),audio:()=>_("smhd",0,0,[v(0),v(0)]),subtitle:()=>_("nmhd",0,0)},Fs=()=>C("dinf",void 0,[Os()]),Os=()=>_("dref",0,0,[g(1)],[zs()]),zs=()=>_("url ",0,1),Ws=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(i=>i.sampleCompositionTimeOffset!==0);return C("stbl",void 0,[Ls(t),io(t),e?ao(t):null,e?co(t):null,no(t),so(t),oo(t),ro(t),...Qi(t.samples,!1)])},Ls=t=>{let e;if(t.type==="video")e=Vs(Po(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const i=Ji(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime);p(i),e=$s(i,t)}else t.type==="subtitle"&&(e=eo(Io[t.track.source._codec],t));return p(e),_("stsd",0,0,[g(1)],[e])},Vs=(t,e)=>C(t,[Array(6).fill(0),v(1),v(0),v(0),Array(12).fill(0),v(e.info.width),v(e.info.height),g(4718592),g(4718592),g(0),v(1),I(lt.length),B(lt),Array(31-lt.length).fill(0),v(e.info.hasAlphaChannel?32:24),Qe(65535)],[ko[e.track.source._codec]?.(e)??null,Us(e),gr(e.info.decoderConfig.colorSpace)?null:Hs(e),_t(e)]),_t=t=>t.avgBitrate===0&&t.maxBitrate===0?null:C("btrt",[g(0),g(t.maxBitrate),g(t.avgBitrate)]),Us=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:C("pasp",[g(t.info.pixelAspectRatio.num),g(t.info.pixelAspectRatio.den)]),Hs=t=>{const e=t.info.decoderConfig.colorSpace;return C("colr",[B(t.muxer.isQuickTime?"nclc":"nclx"),v(e?.primaries!=null?_e[e.primaries]:2),v(e?.transfer!=null?Be[e.transfer]:2),v(e?.matrix!=null?Pe[e.matrix]:2),t.muxer.isQuickTime?[]:I((e?.fullRange?1:0)<<7)])},Ns=t=>t.info.decoderConfig&&C("avcC",[...G(t.info.decoderConfig.description)]),qs=t=>t.info.decoderConfig&&C("hvcC",[...G(t.info.decoderConfig.description)]),Gi=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),s=Number(i[3]),o=i[4]?Number(i[4]):1,a=i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0),l=(s<<4)+(o<<1)+a,c=i[5]?Number(i[5]):e.colorSpace?.primaries?_e[e.colorSpace.primaries]:1,d=i[6]?Number(i[6]):e.colorSpace?.transfer?Be[e.colorSpace.transfer]:1,u=i[7]?Number(i[7]):e.colorSpace?.matrix?Pe[e.colorSpace.matrix]:1;return _("vpcC",1,0,[I(r),I(n),I(l),I(c),I(d),I(u),v(0)])},Ds=t=>C("av1C",ls(t.info.decoderConfig.codec)),$s=(t,e)=>{let i=0,r,n=16;const s=Ee.includes(e.track.source._codec);if(s){const o=e.track.source._codec,{sampleSize:a}=Ae(o);n=8*a,n>16&&(i=1)}if(e.muxer.isQuickTime&&e.track.source._codec!=="truehd"&&(i=1),i===0)r=[Array(6).fill(0),v(1),v(i),v(0),g(0),v(e.info.numberOfChannels),v(n),v(0),v(0),e.track.source._codec==="truehd"?g(e.info.sampleRate):[v(e.info.sampleRate<2**16?e.info.sampleRate:0),v(0)]];else{const o=s?0:-2;r=[Array(6).fill(0),v(1),v(i),v(0),g(0),v(e.info.numberOfChannels),v(Math.min(n,16)),Qe(o),v(0),v(e.info.sampleRate<2**16?e.info.sampleRate:0),v(0),s?[g(1),g(n/8),g(e.info.numberOfChannels*n/8)]:[g(0),g(0),g(0)],g(2)]}return C(t,r,[Ao(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null,_t(e)])},Bt=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let i=[...I(e),...I(21),...Hi(0),...g(t.maxBitrate),...g(t.avgBitrate)];if(t.info.decoderConfig.description){const r=G(t.info.decoderConfig.description);i=[...i,...I(5),...St(r.byteLength),...r]}return i=[...v(1),...I(0),...I(4),...St(i.length),...i,...I(6),...I(1),...I(2)],i=[...I(3),...St(i.length),...i],_("esds",0,0,i)},we=t=>C("wave",void 0,[js(t),Gs(t),C("\0\0\0\0")]),js=t=>C("frma",[B(Ji(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),Gs=t=>{const{littleEndian:e}=Ae(t.track.source._codec);return C("enda",[v(+e)])},Qs=t=>{let e=t.info.numberOfChannels,i=312,r=t.info.sampleRate,n=0,s=0,o=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){p(a.byteLength>=18);const l=G(a),c=cn(l);e=c.outputChannelCount,i=c.preSkip,r=c.inputSampleRate,n=c.outputGain,s=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return C("dOps",[I(0),I(e),v(i),g(r),Qe(n),I(s),...o])},Xs=t=>{const e=t.info.decoderConfig?.description;p(e);const i=G(e);return _("dfLa",0,0,[...i.subarray(4)])},ae=t=>{const{littleEndian:e,sampleSize:i}=Ae(t.track.source._codec),r=+e;return _("pcmC",0,0,[I(r),I(8*i)])},Ks=t=>{p(t.info.primingPacket);const e=hn(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=new Uint8Array(3),r=new F(i);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),C("dac3",[...i])},Ys=t=>{p(t.info.primingPacket);const e=pn(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let i=16;for(const o of e.substreams)i+=23,o.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),n=new Uint8Array(r),s=new F(n);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(const o of e.substreams)s.writeBits(2,o.fscod),s.writeBits(5,o.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,o.bsmod),s.writeBits(3,o.acmod),s.writeBits(1,o.lfeon),s.writeBits(3,0),s.writeBits(4,o.numDepSub),o.numDepSub>0?s.writeBits(9,o.chanLoc):s.writeBits(1,0);return C("dec3",[...n])},Zs=t=>{p(t.info.primingPacket);const e=kn(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return C("ddts",[...Rn(e)])},Js=t=>{p(t.info.primingPacket);const e=t.info.primingPacket.data;if(fn("truehd",e)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");const i=me(e),r=i.getUint32(8),n=i.getUint16(18)&32767;return C("dmlp",[g(r),v(n<<1),g(0)])},eo=(t,e)=>C(t,[Array(6).fill(0),v(1)],[Ro[e.track.source._codec](e),_t(e)]),to=t=>C("vttC",[...ne.encode(t.info.config.description)]),io=t=>_("stts",0,0,[g(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[g(e.sampleCount),g(e.sampleDelta)])]),ro=t=>{if(t.samples.every(i=>i.type==="key"))return null;const e=[...t.samples.entries()].filter(([,i])=>i.type==="key");return _("stss",0,0,[g(e.length),e.map(([i])=>g(i+1))])},no=t=>_("stsc",0,0,[g(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[g(e.firstChunk),g(e.samplesPerChunk),g(1)])]),so=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=Ae(t.track.source._codec);return _("stsz",0,0,[g(e*t.info.numberOfChannels),g(t.samples.reduce((i,r)=>i+P(r.duration,t.timescale),0))])}return _("stsz",0,0,[g(0),g(t.samples.length),t.samples.map(e=>g(e.size))])},oo=t=>t.finalizedChunks.length>0&&j(t.finalizedChunks).offset>=2**32?_("co64",0,0,[g(t.finalizedChunks.length),t.finalizedChunks.map(e=>J(e.offset))]):_("stco",0,0,[g(t.finalizedChunks.length),t.finalizedChunks.map(e=>g(e.offset))]),ao=t=>_("ctts",1,0,[g(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[g(e.sampleCount),oe(e.sampleCompositionTimeOffset)])]),co=t=>{if(p(t.compositionTimeOffsetTable.length>0),t.samples.length===0)return null;let e=1/0,i=-1/0,r=1/0,n=-1/0;for(let o=0;o<t.compositionTimeOffsetTable.length;o++){const a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),i=Math.max(i,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){const a=t.samples[o];r=Math.min(r,P(a.timestamp,t.timescale)),n=Math.max(n,P(a.timestamp+a.duration,t.timescale))}const s=Math.max(-e,0);return n>=2**31?null:_("cslg",0,0,[oe(s),oe(e),oe(i),oe(r),oe(n)])},Qi=(t,e)=>{const i=[];for(const s of t)if(i.length===0)i.push({sampleCount:1,prerollSamples:s.prerollSamples});else{const o=i[i.length-1];o.prerollSamples===s.prerollSamples?o.sampleCount++:i.push({sampleCount:1,prerollSamples:s.prerollSamples})}const r=i.filter(s=>s.prerollSamples!==0);if(r.length===0)return[];let n=e?65537:1;return[_("sgpd",1,0,[B("roll"),g(2),g(r.length),...r.map(s=>Qe(s.prerollSamples))]),_("sbgp",0,0,[B("roll"),g(i.length),...i.map(s=>[g(s.sampleCount),g(s.prerollSamples!==0?n++:0)])])]},lo=t=>C("mvex",void 0,t.map(uo)),uo=t=>_("trex",0,0,[g(t.track.id),g(1),g(0),g(0),g(0)]),Xi=(t,e)=>C("moof",void 0,[fo(t),...e.map(ho)]),fo=t=>_("mfhd",0,0,[g(t)]),Ki=t=>{let e=0,i=0;const r=0,n=0,s=t.type==="delta";return i|=+s,s?e|=1:e|=2,e<<24|i<<16|r<<8|n},ho=t=>C("traf",void 0,[mo(t),po(t),go(t),...Qi(t.currentChunk.samples,!0)]),mo=t=>{p(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Ki(i)};return _("tfhd",0,e,[g(t.track.id),g(r.duration),g(r.size),g(r.flags)])},po=t=>(p(t.currentChunk),_("tfdt",1,0,[J(P(t.currentChunk.startTimestamp,t.timescale))])),go=t=>{p(t.currentChunk);const e=t.currentChunk.samples.map(w=>w.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(w=>w.size),r=t.currentChunk.samples.map(Ki),n=t.currentChunk.samples.map(w=>P(w.timestamp-w.decodeTimestamp,t.timescale)),s=new Set(e),o=new Set(i),a=new Set(r),l=new Set(n),c=a.size===2&&r[0]!==r[1],d=s.size>1,u=o.size>1,f=!c&&a.size>1,h=l.size>1||[...l].some(w=>w!==0);let m=0;return m|=1,m|=4*+c,m|=256*+d,m|=512*+u,m|=1024*+f,m|=2048*+h,_("trun",1,m,[g(t.currentChunk.samples.length),g(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?g(r[0]):[],t.currentChunk.samples.map((w,T)=>[d?g(e[T]):[],u?g(i[T]):[],f?g(r[T]):[],h?oe(n[T]):[]])])},wo=t=>C("mfra",void 0,[...t.map(yo),bo()]),yo=t=>{const i=[];for(const r of t.finalizedChunks){const n=r.samples.findIndex(o=>o.type==="key");if(n===-1)continue;const s=r.samples[n];i.push([J(P(s.timestamp,t.timescale)),J(r.moofOffset),g(r.trafIndex+1),g(1),g(n+1)])}return _("tfra",1,0,[g(t.track.id),g(63),g(i.length),i])},bo=()=>_("mfro",0,0,[g(0)]),To=()=>C("vtte"),Co=(t,e,i,r,n)=>C("vttc",void 0,[n!==null?C("vsid",[oe(n)]):null,i!==null?C("iden",[...ne.encode(i)]):null,e!==null?C("ctim",[...ne.encode(Mn(e))]):null,r!==null?C("sttg",[...ne.encode(r)]):null,C("payl",[...ne.encode(t)])]),vo=t=>C("vtta",[...ne.encode(t)]),Eo=t=>{const e=[],i=t.format._options.metadataFormat??"auto",r=t.output._metadataTags;if(i==="mdir"||i==="auto"&&!t.isQuickTime){const n=_o(r);n&&e.push(n)}else if(i==="mdta"){const n=Bo(r);n&&e.push(n)}else(i==="udta"||i==="auto"&&t.isQuickTime)&&So(e,t.output._metadataTags);return e.length===0?null:C("udta",void 0,e)},So=(t,e)=>{for(const{key:i,value:r}of jt(e))switch(i){case"title":t.push(ce("©nam",r));break;case"description":t.push(ce("©des",r));break;case"artist":t.push(ce("©ART",r));break;case"album":t.push(ce("©alb",r));break;case"albumArtist":t.push(ce("albr",r));break;case"genre":t.push(ce("©gen",r));break;case"date":t.push(ce("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(ce("©cmt",r));break;case"lyrics":t.push(ce("©lyr",r));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:be(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];r==null||i.length!==4||t.some(n=>n.type===i)||(typeof r=="string"?t.push(ce(i,r)):r instanceof Uint8Array&&t.push(C(i,Array.from(r))))}},ce=(t,e)=>{const i=ne.encode(e);return C(t,[v(i.length),v(er("und")),Array.from(i)])},Yi={"image/jpeg":13,"image/png":14,"image/bmp":27},xo=new Set(["HMMT","loci","chpl"]),Zi=(t,e)=>{const i=[];for(const{key:r,value:n}of jt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:ee(n)});break;case"description":i.push({key:e?"description":"©des",value:ee(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:ee(n)});break;case"album":i.push({key:e?"album":"©alb",value:ee(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:ee(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:ee(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:ee(n)});break;case"beatsPerMinute":e||i.push({key:"tmpo",value:C("data",[g(21),g(0),v(n)])});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:ee(n)});break;case"date":i.push({key:e?"date":"©day",value:ee(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&i.push({key:"covr",value:C("data",[g(Yi[s.mimeType]??0),g(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:ee(s)})}else i.push({key:"trkn",value:C("data",[g(0),g(0),v(0),v(n),v(t.tracksTotal??0),v(0)])});break;case"discNumber":e||i.push({key:"disc",value:C("data",[g(0),g(0),v(0),v(n),v(t.discsTotal??0),v(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:be(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];n==null||!e&&(r.length!==4||xo.has(r))||i.some(s=>s.key===r)||(typeof n=="string"?i.push({key:r,value:ee(n)}):n instanceof Uint8Array?i.push({key:r,value:C("data",[g(0),g(0),Array.from(n)])}):n instanceof Xt&&i.push({key:r,value:C("data",[g(Yi[n.mimeType]??0),g(0),Array.from(n.data)])}))}return i},_o=t=>{const e=Zi(t,!1);return e.length===0?null:_("meta",0,0,void 0,[xt(!1,"mdir","","appl"),C("ilst",void 0,e.map(i=>C(i.key,void 0,[i.value])))])},Bo=t=>{const e=Zi(t,!0);return e.length===0?null:C("meta",void 0,[xt(!1,"mdta",""),_("keys",0,0,[g(e.length)],e.map(i=>C("mdta",[...ne.encode(i.key)]))),C("ilst",void 0,e.map((i,r)=>{const n=String.fromCharCode(...g(r+1));return C(n,void 0,[i.value])}))])},ee=t=>C("data",[g(1),g(0),...ne.encode(t)]),Po=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},ko={avc:Ns,hevc:qs,vp8:Gi,vp9:Gi,av1:Ds,prores:null},Ji=(t,e,i)=>{switch(t){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e;case"truehd":return"mlpa"}if(i)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Ao=(t,e)=>{switch(t){case"aac":return Bt;case"mp3":return Bt;case"opus":return Qs;case"vorbis":return Bt;case"flac":return Xs;case"ac3":return Ks;case"eac3":return Ys;case"dts":return Zs;case"truehd":return Js}if(e)switch(t){case"pcm-s24":return we;case"pcm-s24be":return we;case"pcm-s32":return we;case"pcm-s32be":return we;case"pcm-f32":return we;case"pcm-f32be":return we;case"pcm-f64":return we;case"pcm-f64be":return we}else switch(t){case"pcm-s16":return ae;case"pcm-s16be":return ae;case"pcm-s24":return ae;case"pcm-s24be":return ae;case"pcm-s32":return ae;case"pcm-s32be":return ae;case"pcm-f32":return ae;case"pcm-f32be":return ae;case"pcm-f64":return ae;case"pcm-f64be":return ae}return null},Io={webvtt:"wvtt"},Ro={webvtt:to},er=t=>{p(t.length===3);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e};class Pt{constructor(e,i){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(i),e._writerAcquired=!0}start(){p(!this.started),this.target._start(),this.started=!0}write(e){p(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let i=this.getPos();if(i<this.trackedStart){if(i+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-i),i=0}const r=i+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<r;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,i-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,i+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const i={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,i}}class he extends ot{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,i){this.onwrite?.(e,i),this._emit("write",{start:e,end:i})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Mo(this,e)}}const kt=2**16,At=2**32;class Ke extends he{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(kt,{maxByteLength:At})}catch{this._buffer=new ArrayBuffer(kt),this._supportsResize=!1}else this._buffer=new ArrayBuffer(kt);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){p(this._buffer),p(this._bytes);let i=this._buffer.byteLength;for(;i<e;)i*=2;if(i!==this._buffer.byteLength){if(i>At)throw new Error(`ArrayBuffer exceeded maximum size of ${At} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(i);else{const r=new ArrayBuffer(i),n=new Uint8Array(r);n.set(this._bytes,0),this._buffer=r,this._bytes=n}}}_start(){}_write(e,i){p(this._bytes),this._ensureSize(i+e.byteLength),this._bytes.set(e,i),this._maxPos=Math.max(this._maxPos,i+e.byteLength),this._dispatchWrite(i,i+e.byteLength)}async _flush(){}async _finalize(){p(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,i){return p(this._bytes),this._bytes.slice(e,i)}}class Mo extends he{constructor(e,i){super(),this._baseTarget=e,this._offset=i}_start(){}_write(e,i){this._baseTarget._write(e,this._offset+i),this._dispatchWrite(i,i+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class It{constructor(e,i){if(this.rootPath=e,this.getTarget=i,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof i!="function")throw new TypeError("getTarget must be a function.")}}const Q=57600,tr=.5,Fo=t=>{const e={},i=t.track;return i.metadata.name!==void 0&&(e.name=i.metadata.name),e},P=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},Ie=t=>{if(t.samples.length===0)return 0;let e=1/0,i=-1/0;for(let r=0;r<t.samples.length;r++){const n=t.samples[r];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>i&&(i=n.timestamp+n.duration)}return e===1/0?0:i-e};class Oo extends Cs{constructor(e,i){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Ke,this.auxWriter=new Pt(this.auxTarget,!1),this.auxBoxWriter=new Ge(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Nt(),this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=i,this.formatOptions={...i._options},this.isQuickTime=i instanceof sr,this.isCmaf=i instanceof nr,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(i instanceof nr?1/0:1),this.auxWriter.start()}async start(){const e=await this.mutex.acquire(),i=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=i?Math.floor(i.getTime()/1e3)+jn:0,i&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof Ke),this.boxWriter=new Ge(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Ke?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const n=await this.output._getInitTarget(),s=new Pt(n,!0);s.start(),this.initWriter=s,this.initBoxWriter=new Ge(s)}const r=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{const n=this.initBoxWriter??this.boxWriter;if(p(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(vs({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:s,start:o}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(s,o)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(const n of this.output.tracks){if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(n.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${n.id} has a maximumPacketCount of ${n.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(p(this.writer),p(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xe(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(const n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(i=>i.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(i=>i.type==="video"||i.type==="audio"?i.info.decoderConfig.codec:{webvtt:"wvtt"}[i.track.source._codec]);return Gn({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(i=>i.type==="video"),hasAudio:this.trackDatas.some(i=>i.type==="audio"),codecStrings:e})}getVideoTrackData(e,i,r){const n=this.trackDatas.find(h=>h.track===e);if(n)return n;Vi(r,e.source._codec),p(r),p(r.decoderConfig);const s={...r.decoderConfig};p(s.codedWidth!==void 0),p(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!i)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const h=ti(i.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=ii(h),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!i)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const h=si(i.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=rn(h),o=!0}const a=Sr(1/(e.metadata.frameRate??Q),1e6).den,l=s.displayAspectWidth,c=s.displayAspectHeight,d=l===void 0||c===void 0?{num:1,den:1}:Gt({num:l*s.codedHeight,den:c*s.codedWidth}),u=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:u},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((h,m)=>h.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,i,r){const n=this.trackDatas.find(l=>l.track===e);if(n)return n;Ui(r,e.source._codec),p(r),p(r.decoderConfig);const s={...r.decoderConfig};let o=!1;if(e.source._codec==="aac"&&!s.description){if(!i)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const l=ki(Oe.tempFromBytes(i.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const c=at[l.samplingFrequencyIndex],d=Kt[l.channelConfiguration];if(c===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=Ur({objectType:l.objectType,outputSampleRate:c,outputNumberOfChannels:d}),o=!0}if(!i){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&Ee.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:i,preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(a),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,i){const r=this.trackDatas.find(s=>s.track===e);if(r)return r;Ts(i),p(i),p(i.config);const n={muxer:this,track:e,type:"subtitle",info:{config:i.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,i,r){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,i,r);let o=i.data;if(s.info.requiresAnnexBTransformation){const l=[...Re(o)].map(c=>o.subarray(c.offset,c.offset+c.length));if(l.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=$r(l,4)}this.validateTimestamp(s.track,i.timestamp,i.type==="key");const a=this.createSampleForTrack(s,o,i.timestamp,i.duration,i.type,0);await this.registerSample(s,a)}finally{n()}}async addEncodedAudioPacket(e,i,r){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,i,r);let o=i.data;if(s.info.requiresAdtsStripping){const f=ki(Oe.tempFromBytes(o));if(!f)throw new Error("Expected ADTS frame, didn't get one.");const h=f.crcCheck===null?gt:Qn;o=o.subarray(h)}this.validateTimestamp(s.track,i.timestamp,i.type==="key");let a=i.timestamp,l=i.duration;if(s.info.requiresPcmTransformation){const h=Ae(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(l=o.byteLength/h/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const m=a-s.info.expectedNextPcmPacketTimestamp;if(m<.01)a=s.info.expectedNextPcmPacketTimestamp;else{const w=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,m);a=s.info.expectedNextPcmPacketTimestamp+w}}s.info.expectedNextPcmPacketTimestamp=a+l}const{preroll:c}=s.info;let d=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")d=-Math.min(1,c.packetCount);else if(e.source._codec==="mp3")d=-Math.min(2,c.packetCount);else if(e.source._codec==="opus"){const f=Math.round(fs*us);d=-c.audioSampleDurationHistory.length;const h=dn(o);for(c.accumulatedAudioSamples+=h.durationInSamples,c.audioSampleDurationHistory.push(h.durationInSamples);c.accumulatedAudioSamples-c.audioSampleDurationHistory[0]>=f;)c.accumulatedAudioSamples-=c.audioSampleDurationHistory.shift(),p(c.audioSampleDurationHistory.length>0)}c.packetCount++;const u=this.createSampleForTrack(s,o,a,l,i.type,d);await this.registerSample(s,u)}finally{n()}}async padWithSilence(e,i,r){const n=P(r,e.timescale);if(r=n/e.timescale,n>0){const{sampleSize:s,silentValue:o}=Ae(e.info.decoderConfig.codec),a=n*e.info.numberOfChannels,l=new Uint8Array(s*a).fill(o),c=this.createSampleForTrack(e,new Uint8Array(l.buffer),i,r,"key",0);await this.registerSample(e,c)}return r}async addSubtitleCue(e,i,r){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,r);this.validateTimestamp(s.track,i.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(i),await this.processWebVTTCues(s,i.timestamp))}finally{n()}}async processWebVTTCues(e,i){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);const r=new Set([]);for(const c of e.cueQueue)p(c.timestamp<=i),p(e.lastCueEndTimestamp<=c.timestamp+c.duration),r.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),r.add(c.timestamp+c.duration);const n=[...r].sort((c,d)=>c-d),s=n[0],o=n[1]??s;if(i<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=To();this.auxBoxWriter.writeBox(c);const d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,u),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const d=e.cueQueue[c];if(d.timestamp>=o)break;fi.lastIndex=0;const u=fi.test(d.text),f=d.timestamp+d.duration;let h=e.cueToSourceId.get(d);if(h===void 0&&o<f&&(h=e.nextSourceId++,e.cueToSourceId.set(d,h)),d.notes){const w=vo(d.notes);this.auxBoxWriter.writeBox(w)}const m=Co(d.text,u?s:null,d.identifier??null,d.settings??null,h??null);this.auxBoxWriter.writeBox(m),f===o&&e.cueQueue.splice(c--,1)}const a=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,a,s,o-s,"key",0);await this.registerSample(e,l),e.lastCueEndTimestamp=o}}createSampleForTrack(e,i,r,n,s,o){return{timestamp:r,decodeTimestamp:r,duration:n,data:i,size:i.byteLength,type:s,timescaleUnitsToNextSample:P(n,e.timescale),prerollSamples:o}}processTimestamps(e,i){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){p(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const o=e.timestampProcessingQueue[s],a=P(o.duration,e.timescale);n+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const s=j(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const r=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);this.isFragmented?e.startTimestampOffset??=Math.min(r[0],0):e.startTimestampOffset??=r[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=r[n];const o=P(s.timestamp-s.decodeTimestamp,e.timescale),a=P(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const l=P(s.decodeTimestamp,e.timescale,!1),c=Math.round(l-e.lastTimescaleUnits);if(p(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let d=j(e.timeToSampleTable);if(p(d),d.sampleCount===1){d.sampleDelta=c;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===c&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==c&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:c}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const u=j(e.compositionTimeOffsetTable);p(u),u.sampleCompositionTimeOffset===o?u.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=P(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),i!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(i.type==="key");const n=P(i.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,i){i.type==="key"&&this.processTimestamps(e,i),e.timestampProcessingQueue.push(i),e.sampleQueue.push(i),await this.interleaveSamples()}async addSampleToTrack(e,i){if(!this.isFragmented&&(e.samples.push(i),this.fastStart==="reserve")){const n=e.track.metadata.maximumPacketCount;if(p(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,i.timestamp);const n=i.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(o=>{if(e===o)return i.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.closed});n>=this.minimumFragmentDuration&&s&&i.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=n>=tr}if(r){if(!this.isFragmented){const n=this.trackDatas.filter(s=>s.currentChunk&&i.timestamp-s.currentChunk.startTimestamp>=tr).sort((s,o)=>s.currentChunk.startTimestamp-o.currentChunk.startTimestamp);for(const s of n)await this.finalizeCurrentChunk(s)}e.currentChunk={startTimestamp:i.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}}p(e.currentChunk),e.currentChunk.samples.push(i),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,i.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,i.timestamp+i.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,i.timestamp))}async finalizeCurrentChunk(e){p(!this.isFragmented),p(this.writer);const i=e.currentChunk;p(i),e.currentChunk=null,e.finalizedChunks.push(i),this.finalizedChunks.push(i);let r=i.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=i.samples.reduce((n,s)=>n+P(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||j(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){i.offset=0;return}i.offset=this.writer.getPos();for(const n of i.samples)p(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let i=null,r=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<r&&(i=s,r=s.sampleQueue[0].timestamp)}if(!i)break;const n=i.sampleQueue.shift();await this.addSampleToTrack(i,n)}}}async finalizeFragment(e=!this.isCmaf){if(p(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const h=this.initBoxWriter??this.boxWriter;p(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const m=Le(this);if(h.writeBox(m),this.formatOptions.onMoov){const{data:w,start:T}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(w,T)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Ge(this.writer);const w=this.boxWriter.measureBox($i()),T=this.boxWriter.measureBox(ji(this,0));this.segmentHeaderSize=w+T,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(this.boxWriter);const i=this.trackDatas.filter(h=>h.currentChunk);if(i.length===0){e&&await this.writer.flush();return}const r=this.nextFragmentNumber++,n=Xi(r,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n);let a=o+wt,l=1/0;for(let h=0;h<i.length;h++){const m=i[h];p(m.currentChunk),p(m.startTimestampOffset!==null),m.currentChunk.offset=a,m.currentChunk.moofOffset=s,m.currentChunk.trafIndex=h,m.currentChunk.startTimestamp-=m.startTimestampOffset;for(const w of m.currentChunk.samples)a+=w.size,w.timestamp-=m.startTimestampOffset,w.decodeTimestamp-=m.startTimestampOffset;l=Math.min(l,m.currentChunk.startTimestamp)}const c=a-o,d=c>=2**32;if(d)for(const h of i)h.currentChunk.offset+=Ii-wt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const u=Xi(r,i);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){const{data:h,start:m}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,m,l)}p(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=Xe(d);f.size=c,this.boxWriter.writeBox(f),this.writer.seek(o+(d?Ii:wt));for(const h of i)for(const m of h.currentChunk.samples)this.writer.write(m.data),m.data=null;if(this.formatOptions.onMdat){const{data:h,start:m}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,m)}for(const h of i)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async createFastStartReserveMdat(){p(this.writer),p(this.boxWriter),this.ensureOneEnabledTrack();const e=Le(this),r=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+r),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xe(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(const i of this.trackDatas){const r=i.track.metadata.maximumPacketCount;p(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r,i.type==="audio"&&(e+=2*r,e+=8*r)}return e}async onTrackClose(e){const i=await this.mutex.acquire(),r=this.trackDatas.find(n=>n.track===e);r&&(r.closed=!0,r.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples(),i()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const i=this.trackDatas.filter(n=>n.type===e);if(i.length===0)continue;if(!i.some(n=>n.track.metadata.disposition?.default!==!1)){const n=i[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){p(this.isFragmented);const e=await this.mutex.acquire();try{for(const i of this.trackDatas)i.type==="subtitle"&&i.track.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(const i of this.trackDatas)i.closed=!0,i.type==="subtitle"&&i.track.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{const i=this.trackDatas.filter(r=>r.currentChunk).sort((r,n)=>r.currentChunk.startTimestamp-n.currentChunk.startTimestamp);for(const r of i)await this.finalizeCurrentChunk(r);for(const r of this.trackDatas){const n=Ie(r);if(n>0){let l=0;for(const c of r.samples)l+=c.size;r.avgBitrate=Math.round(8*l/n)}else r.avgBitrate=0;let s=0,o=0,a=0;for(let l=0;l<r.samples.length;l++){const c=r.samples[l];for(o+=c.size;c.decodeTimestamp-r.samples[s].decodeTimestamp>=1;)o-=r.samples[s].size,s++;a=Math.max(a,o)}if(r.maxBitrate=8*a,r.startTimestampOffset!==null)for(let l=0;l<r.samples.length;l++){const c=r.samples[l];c.timestamp-=r.startTimestampOffset,c.decodeTimestamp-=r.startTimestampOffset}}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Xe(!1);let i;for(let n=0;n<2;n++){const s=Le(this),o=this.boxWriter.measureBox(s);i=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+i;for(const l of this.finalizedChunks){l.offset=a;for(const{data:c}of l.samples)p(c),a+=c.byteLength,i+=c.byteLength}if(a<2**32)break;i>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const r=Le(this);if(this.boxWriter.writeBox(r),this.formatOptions.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=i,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const s of n.samples)p(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,s)}}else if(this.isFragmented)if(this.isCmaf){const i=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox($i()),this.boxWriter.writeBox(ji(this,i))}else{const i=this.writer.getPos(),r=wo(this.trackDatas);this.boxWriter.writeBox(r);const n=this.writer.getPos()-i;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{p(this.mdat);const i=this.boxWriter.offsets.get(this.mdat);p(i!==void 0);const r=this.writer.getPos()-i;if(this.mdat.size=r,this.mdat.largeSize=r>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}const n=Le(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null);const s=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,o=this.boxWriter.measureBox(n);if(o+8>s)throw new Error(`The moov box (${o} bytes) plus a free box (8 bytes) exceed the space reserved for them (${s} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n),this.boxWriter.writeBox(Es(s-o))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){const{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}}class ir{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>fe.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>$e.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ze.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class Rt extends ir{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Mr(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new Oo(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class rr extends Rt{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...fe,...Tt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ze]}_codecUnsupportedHint(e){return new sr().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class nr extends Rt{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...fe,...Tt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ze]}}class sr extends Rt{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...fe,...$e]}_codecUnsupportedHint(e){return new rr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const or=["video","audio","subtitle"];class Ve{constructor(e,i,r,n,s){this.id=e,this.output=i,this.type=r,this.source=n,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Ve))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=Qt(this.metadata.group),r=Qt(e.metadata.group);for(const n of i)if(this.type!==e.type&&r.some(a=>n===a)||r.some(a=>n._pairedGroups.has(a)))return!0;return!1}}class zo extends Ve{constructor(e,i,r,n){super(e,i,"video",r,n)}}class Wo extends Ve{constructor(e,i,r,n){super(e,i,"audio",r,n)}}class Lo extends Ve{constructor(e,i,r,n){super(e,i,"subtitle",r,n)}}class Ue{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Ue))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const Mt=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!Er(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&Vr(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(t.bitrate!==void 0&&(!Number.isFinite(t.bitrate)||t.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(t.averageBitrate!==void 0&&(!Number.isFinite(t.averageBitrate)||t.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(t.group!==void 0&&!(t.group instanceof Ue)&&(!Array.isArray(t.group)||t.group.some(e=>!(e instanceof Ue))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Vo extends ot{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const i=this._getRootTarget();if(Te(i))throw new TypeError(e);return i}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Ue,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Lt,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ir))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof he||e.target instanceof It))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof he&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof he)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof he&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){p(this._target instanceof It);const i=this._target.getTarget(e),r=n=>{if(!(n instanceof he))throw new TypeError("getTarget must return a Target.");return n};return Te(i)?i.then(r):r(i)}async _getTarget(e){p(this._target instanceof It);const i=await this._getTargetValidated(e);return this._emit("target",{target:i,request:e,isRoot:e.isRoot}),this.state==="canceled"?await i._close():this._rememberTarget(i),i}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(p(this._initTarget!==null),this._initTarget instanceof he)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof he)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},i=this._getTargetValidated(e),r=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return Te(i)?this._rootTargetPromise=i.then(r):r(i)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const i=await this._getRootTarget(),r=new Pt(i,typeof e=="boolean"?e:e(i));return r.start(),r})()}addVideoTrack(e,i={}){if(!(e instanceof Ri))throw new TypeError("source must be a VideoSource.");if(Mt(i),i.rotation!==void 0&&![0,90,180,270].includes(i.rotation))throw new TypeError(`Invalid video rotation: ${i.rotation}. Has to be 0, 90, 180 or 270.`);if(i.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(i.transformationMatrix!==void 0&&(!Array.isArray(i.transformationMatrix)||i.transformationMatrix.length!==9||!i.transformationMatrix.every(n=>Number.isFinite(n))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(i.frameRate!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${i.frameRate}. Must be a positive number.`);if(i.hasOnlyKeyPackets!==void 0&&typeof i.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(i.canBeTransparent!==void 0&&typeof i.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(i.decoderConfig!==void 0&&Vi({decoderConfig:i.decoderConfig},e._codec),i.primingPacket!==void 0){if(!(i.primingPacket instanceof ve))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(i.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const r={...i};return r.group??=this.defaultTrackGroup,this._addTrack(new zo(this.tracks.length+1,this,e,r))}addAudioTrack(e,i={}){if(!(e instanceof ss))throw new TypeError("source must be an AudioSource.");if(Mt(i),i.decoderConfig!==void 0&&Ui({decoderConfig:i.decoderConfig},e._codec),i.primingPacket!==void 0){if(!(i.primingPacket instanceof ve))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(i.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const r={...i};return r.group??=this.defaultTrackGroup,this._addTrack(new Wo(this.tracks.length+1,this,e,r))}addSubtitleTrack(e,i={}){if(!(e instanceof os))throw new TypeError("source must be a SubtitleSource.");Mt(i);const r={...i};return r.group??=this.defaultTrackGroup,this._addTrack(new Lo(this.tracks.length+1,this,e,r))}setMetadataTags(e){if(Lr(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const i=this.format.getSupportedTrackCounts(),r=this.tracks.reduce((o,a)=>o+(a.type===e.type?1:0),0),n=i[e.type].max;if(r===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const s=i.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const r of or){const n=this.tracks.reduce((o,a)=>o+(a.type===r?1:0),0),s=e[r].min;if(n<s)return!1}const i=e.total.min;return!(this.tracks.length<i)}async start(){const e=this.format.getSupportedTrackCounts();for(const r of or){const n=this.tracks.reduce((o,a)=>o+(a.type===r?1:0),0),s=e[r].min;if(n<s)throw new Error(s===e[r].max?`${this.format._name} requires exactly ${s} ${r} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${r} track${s===1?"":"s"}.`)}const i=e.total.min;if(this.tracks.length<i)throw new Error(i===e.total.max?`${this.format._name} requires exactly ${i} track${i===1?"":"s"}.`:`${this.format._name} requires at least ${i} track${i===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(A._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const r=this._mutex.acquire();try{await this._muxer.start();const n=this.tracks.map(s=>s.source._start());await Promise.all(n)}finally{(await r)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&A._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const i=this.tracks.map(r=>r.source._flushOrWaitForOngoingClose(!0));await Promise.all(i),await Promise.all([...this._unfinalizedTargets].map(r=>r._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(A._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const i=this.tracks.map(r=>r.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(i),await this._muxer.finalize(),this._rootWriterPromise){const r=await this._rootWriterPromise;r.finalized||(await r.flush(),await r.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(i){throw this.state="canceled",i}finally{await Promise.all([...this._unfinalizedTargets].map(i=>i._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}const Uo=15e3,Ho=5e3,No=1e3,He=30,ar=(Uo+Ho+No)/1e3*He;let Se,Ye,Ft=0;const Ot="MP4 encoding is unavailable here. Choose GIF or try an up-to-date browser.";self.onmessage=async t=>{try{const{width:e,height:i,rgba:r}=t.data;if(t.data.init){const n={codec:"avc",fullCodecString:"avc1.42001f",quality:new pe({bitrate:6e6}),latencyMode:"quality"};if(!await $n("avc",{...n,width:e,height:i,frameRate:He}))throw new Error(Ot);Se=new Vo({format:new rr({fastStart:"reserve"}),target:new Ke}),Ye=new ns(n),Se.addVideoTrack(Ye,{frameRate:He,maximumPacketCount:ar}),await Se.start(),self.postMessage({ready:!0})}else if(t.data.finish){if(!Se||Ft!==ar)throw new Error("Incomplete MP4 animation.");await Se.finalize();const n=Se.target.buffer;if(!n)throw new Error("MP4 encoding produced no video.");self.postMessage({bytes:n},{transfer:[n]})}else{if(!Ye||!r||r.byteLength!==e*i*4)throw new Error("Incomplete MP4 frame.");const n=new D(r,{format:"RGBA",codedWidth:e,codedHeight:i,timestamp:Ft/He,duration:1/He,colorSpace:{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}});try{await Ye.add(n)}finally{n.close()}Ft++,self.postMessage({ready:!0})}}catch(e){self.postMessage({error:e instanceof Error&&e.message===Ot?Ot:"MP4 encoding failed. Try again or choose GIF."}),await Se?.cancel().catch(()=>{})}}})();