polotno-node 2.14.5 → 2.14.6
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as qt}from"./index-DaKdVCD3.js";function p(t){if(!t)throw new Error("Assertion failed.")}const V=t=>t&&t[t.length-1],ue=t=>t>=0&&t<2**32;class se{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let a=this.bytes[s];const o=7-(n&7);a&=~(1<<o),a|=(r&1<<i-n-1)>>i-n-1<<o,this.bytes[s]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new se(this.bytes);return e.pos=this.pos,e}}const g=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},G=t=>{const e=g(t);return(e&1)===0?-(e>>1):e+1>>1},q=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Re=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),j=new TextEncoder,$e={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},je={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},De={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Xt=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,Ee=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class ft{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const r=new Promise(n=>{e=n}),i=this.currentPromise;return this.currentPromise=r,await i,e}}const Kt=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}},ve=t=>{throw new Error(`Unexpected value: ${t}`)},mt=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},Yt=(t,e,r,i)=>{r=M(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),mt(t,e,r,i)},M=(t,e,r)=>Math.max(e,Math.min(r,t)),Zt="und",Jt=/^[a-z]{3}$/,er=t=>Jt.test(t),Z=1e6*(1+Number.EPSILON),tr=(t,e)=>{const r=t<0?-1:1;t=Math.abs(t);let i=0,n=1,s=1,a=0,o=t;for(;;){const d=Math.floor(o),c=d*s+i,u=d*a+n;if(u>e)return{numerator:r*s,denominator:a};if(i=s,n=a,s=c,a=u,o=1/(o-d),!isFinite(o))break}return{numerator:r*s,denominator:a}};class pt{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let xe=null;const Te=()=>xe!==null?xe:xe=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),gt=function*(t){for(const e in t){const r=t[e];r!==void 0&&(yield{key:e,value:r})}},rr=()=>{Symbol.dispose??=Symbol("Symbol.dispose")};class wt{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}}class ir{constructor(e,r,i,n){if(this.data=e,this.mimeType=r,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const nr=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(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"&&!(e instanceof Uint8Array)&&!(e instanceof wt)&&!(e instanceof ir))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},sr=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};const ee=["avc","hevc","vp9","av1","vp8"],N=["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"],yt=["aac","opus","mp3","vorbis","flac"],oe=[...yt,...N],Ce=["webvtt"],Ke=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],Ye=[{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}],Ze=[{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}],Je=[{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}],or=(t,e,r,i)=>{if(t==="avc"){const s=Math.ceil(e/16)*Math.ceil(r/16),a=Ke.find(h=>s<=h.maxMacroblocks&&i<=h.maxBitrate)??V(Ke),o=a?a.level:0,d="64".padStart(2,"0"),c="00",u=o.toString(16).padStart(2,"0");return`avc1.${d}${c}${u}`}else if(t==="hevc"){const o=e*r,d=Ye.find(u=>o<=u.maxPictureSize&&i<=u.maxBitrate)??V(Ye);return`hev1.1.6.${d.tier}${d.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const s=e*r;return`vp09.00.${(Ze.find(d=>s<=d.maxPictureSize&&i<=d.maxBitrate)??V(Ze)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){const s=e*r,a=Je.find(c=>s<=c.maxPictureSize&&i<=c.maxBitrate)??V(Je);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)},ar=t=>{const e=t.split("."),n=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),d=(s<<5)+o,c=a.slice(-1)==="H"?1:0,h=Number(e[3])===8?0:1,l=0,f=e[4]?Number(e[4]):0,w=e[5]?Number(e[5][0]):1,T=e[5]?Number(e[5][1]):1,C=e[5]?Number(e[5][2]):0,E=(c<<7)+(h<<6)+(l<<5)+(f<<4)+(w<<3)+(T<<2)+C;return[n,d,E,0]},cr=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(N.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ze=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],bt=[-1,1,2,3,4,5,6,8],dr=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new se(t);let r=e.readBits(5);r===31&&(r=32+e.readBits(6));const i=e.readBits(4);let n=null;i===15?n=e.readBits(24):i<ze.length&&(n=ze[i]);const s=e.readBits(4);let a=null;return s>=1&&s<=7&&(a=bt[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},ur=t=>{let e=ze.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);const i=bt.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),e===15&&(n+=24);const s=Math.ceil(n/8),a=new Uint8Array(s),o=new se(a);return t.objectType<32?o.writeBits(5,t.objectType):(o.writeBits(5,31),o.writeBits(6,t.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,r),o.writeBits(4,i),a},Tt=/^pcm-([usf])(\d+)+(be)?$/,le=t=>{if(p(N.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=Tt.exec(t);p(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";const i=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:n,silentValue:s}},Ct=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Tt.test(t)?t:t==="webvtt"?"webvtt":null,lr=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},hr=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},fr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],mr=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,pr=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,gr=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,wr=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,yr=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!fr.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!Ee(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:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys($e);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(je);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(De);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!mr.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(!pr.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(!gr.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")&&!wr.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/.')},br=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Tr=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!br.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!Ee(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!N.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${N.join(", ")}).`)},Cr=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 Er{constructor(e){this.mutex=new ft,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,n)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),r<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 ${r}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);return n.maxTimestamp=Math.max(n.maxTimestamp,r),r}}var ge;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(ge||(ge={}));var $;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})($||($={}));const Qe=t=>{const e=[];let r=0;for(;r<t.length;){let i=-1,n=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){i=s,n=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){i=s,n=4;break}}if(i===-1)break;if(r>0&&i>r){const s=t.subarray(r,i);s.length>0&&e.push(s)}r=i+n}if(r<t.length){const i=t.subarray(r);i.length>0&&e.push(i)}return e},Ve=t=>{const e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},vr=t=>{const r=Qe(t);if(r.length===0)return null;let i=0;for(const o of r)i+=4+o.byteLength;const n=new Uint8Array(i),s=new DataView(n.buffer);let a=0;for(const o of r){const d=o.byteLength;s.setUint32(a,d,!1),a+=4,n.set(o,a),a+=o.byteLength}return n},_e=t=>t[0]&31,xr=t=>{try{const e=Qe(t),r=e.filter(d=>_e(d)===ge.SPS),i=e.filter(d=>_e(d)===ge.PPS),n=e.filter(d=>_e(d)===ge.SPS_EXT);if(r.length===0||i.length===0)return null;const s=r[0],a=Sr(s);p(a!==null);const o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},_r=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 r of t.sequenceParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(const r of t.pictureParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){p(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 r of t.sequenceParameterSetExt){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)},Sr=t=>{try{const e=new se(Ve(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();g(e);let a=null,o=null,d=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=g(e),a===3&&e.skipBits(1),o=g(e),d=g(e),e.skipBits(1),e.readBits(1))){for(let l=0;l<(a!==3?8:12);l++)if(e.readBits(1)){const w=l<6?16:64;let T=8,C=8;for(let E=0;E<w;E++){if(C!==0){const _=G(e);C=(T+_+256)%256}T=C===0?T:C}}}g(e);const c=g(e);if(c===0)g(e);else if(c===1){e.skipBits(1),G(e),G(e);const h=g(e);for(let l=0;l<h;l++)G(e)}g(e),e.skipBits(1),g(e),g(e);const u=e.readBits(1);return{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:u,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:d}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},de=t=>t[0]>>1&63,Ar=t=>{try{const e=Qe(t),r=e.filter(B=>de(B)===$.VPS_NUT),i=e.filter(B=>de(B)===$.SPS_NUT),n=e.filter(B=>de(B)===$.PPS_NUT),s=e.filter(B=>de(B)===$.PREFIX_SEI_NUT||de(B)===$.SUFFIX_SEI_NUT);if(i.length===0||n.length===0)return null;const a=i[0],o=new se(Ve(a));o.skipBits(16),o.readBits(4);const d=o.readBits(3),c=o.readBits(1),{general_profile_space:u,general_tier_flag:h,general_profile_idc:l,general_profile_compatibility_flags:f,general_constraint_indicator_flags:w,general_level_idc:T}=kr(o,d);g(o);const C=g(o);C===3&&o.skipBits(1),g(o),g(o),o.readBits(1)&&(g(o),g(o),g(o),g(o));const E=g(o),_=g(o);g(o);const F=o.readBits(1)?0:d;for(let B=F;B<=d;B++)g(o),g(o),g(o);g(o),g(o),g(o),g(o),g(o),g(o),o.readBits(1)&&o.readBits(1)&&Br(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),g(o),g(o),o.skipBits(1));const P=g(o);if(Pr(o,P),o.readBits(1)){const B=g(o);for(let S=0;S<B;S++)g(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let U=0;o.readBits(1)&&(U=Fr(o,d));let R=0;if(n.length>0){const B=n[0],S=new se(Ve(B));S.skipBits(16),g(S),g(S),S.skipBits(1),S.skipBits(1),S.skipBits(3),S.skipBits(1),S.skipBits(1),g(S),g(S),G(S),S.skipBits(1),S.skipBits(1),S.readBits(1)&&g(S),G(S),G(S),S.skipBits(1),S.skipBits(1),S.skipBits(1),S.skipBits(1);const te=S.readBits(1),he=S.readBits(1);!te&&!he?R=0:te&&!he?R=2:!te&&he?R=3:R=0}const W=[...r.length?[{arrayCompleteness:1,nalUnitType:$.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:$.SPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:$.PPS_NUT,nalUnits:n}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:de(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:h,generalProfileIdc:l,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:w,generalLevelIdc:T,minSpatialSegmentationIdc:U,parallelismType:R,chromaFormatIdc:C,bitDepthLumaMinus8:E,bitDepthChromaMinus8:_,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:d+1,temporalIdNested:c,lengthSizeMinusOne:3,arrays:W}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},kr=(t,e)=>{const r=t.readBits(2),i=t.readBits(1),n=t.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|t.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=t.readBits(8);const o=t.readBits(8),d=[],c=[];for(let u=0;u<e;u++)d.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let u=e;u<8;u++)t.skipBits(2);for(let u=0;u<e;u++)d[u]&&t.skipBits(88),c[u]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Br=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))g(t);else{const n=Math.min(64,1<<4+(e<<1));e>1&&G(t);for(let s=0;s<n;s++)G(t)}},Pr=(t,e)=>{const r=[];for(let i=0;i<e;i++)r[i]=Ir(t,i,e,r)},Ir=(t,e,r,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){const d=g(t);a=e-(d+1)}else a=e-1;t.readBits(1),g(t);const o=i[a]??0;for(let d=0;d<=o;d++)t.readBits(1)||t.readBits(1);n=i[a]}else{const o=g(t),d=g(t);for(let c=0;c<o;c++)g(t),t.readBits(1);for(let c=0;c<d;c++)g(t),t.readBits(1);n=o+d}return n},Fr=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(g(t),g(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(g(t),g(t),g(t),g(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&g(t),t.readBits(1)&&Or(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);const r=g(t);return g(t),g(t),g(t),g(t),r}return 0},Or=(t,e,r)=>{let i=!1,n=!1,s=!1;i=t.readBits(1)===1,n=t.readBits(1)===1,(i||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 a=0;a<=r;a++){const o=t.readBits(1)===1;let d=!0;o||(d=t.readBits(1)===1);let c=!1;d?g(t):c=t.readBits(1)===1;let u=1;c||(u=g(t)+1),i&&et(t,u,s),n&&et(t,u,s)}},et=(t,e,r)=>{for(let i=0;i<e;i++)g(t),g(t),r&&(g(t),g(t)),t.readBits(1)},Mr=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 r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(const i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},Rr=t=>{const e=Re(t),r=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}};var tt;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(tt||(tt={}));const Ne=[],Ue=[];const rt=new Uint8Array(0);class J{constructor(e,r,i,n,s=-1,a,o){if(this.data=e,this.type=r,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===rt&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))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(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rt}get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new J(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");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.");return new J(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}const zr=t=>{let i=t,n=4096,s=0,a=12,o=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(s|a-5<<4|o)&255},Vr=t=>{let r=2048,i=0,n=11,s=0,a=t;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&r)!==r&&n>=5;)r>>=1,n--;return s=a>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85};rr();let it=-1/0,nt=-1/0,we=null;typeof FinalizationRegistry<"u"&&(we=new FinalizationRegistry(t=>{const e=Date.now();t.type==="video"?(e-it>=1e3&&(console.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."),it=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-nt>=1e3&&(console.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."),nt=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));const Et=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Nr=new Set(Et);class ie{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!Nr.has(r.format))throw new TypeError("init.format must be one of: "+Et.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=q(e).slice(),this._layout=r.layout??Lr(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Se(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Se(e.colorSpace)}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(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new ie(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Z),duration:Math.trunc((r.duration??0)*Z)||void 0}),r);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(i,n),a=s.getContext("2d",{alpha:Te(),willReadFrequently:!0});p(a),a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=n,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Se({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");we?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),re(this._data)?new ie(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(p(this._layout),new ie(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})):new ie(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(we?.unregister(this),re(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(st(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. Please manually provide an RGB pixel format in the options instead.");if(p(this._data!==null),!re(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const r=this.toVideoFrame(),i=r.allocationSize(e);return r.close(),i}return re(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!Ee(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(st(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(p(this._data!==null),!re(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){const i=this.toVideoFrame(),n=await i.copyTo(e,r);return i.close(),n}if(re(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return p(this._layout),q(e).set(this._data),this._layout;{const n=this._data.getContext("2d");p(n);const s=n.getImageData(0,0,this.codedWidth,this.codedHeight);return q(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),re(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,i,n,s,a,o,d,c){let u=0,h=0,l=this.displayWidth,f=this.displayHeight,w=0,T=0,C=this.displayWidth,E=this.displayHeight;if(a!==void 0?(u=r,h=i,l=n,f=s,w=a,T=o,d!==void 0?(C=d,E=c):(C=l,E=f)):(w=r,T=i,n!==void 0&&(C=n,E=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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(h))throw new TypeError("sy must be a number.");if(!Number.isFinite(l)||l<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(w))throw new TypeError("dx must be a number.");if(!Number.isFinite(T))throw new TypeError("dy must be a number.");if(!Number.isFinite(C)||C<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(E)||E<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:h,sWidth:l,sHeight:f}=this._rotateSourceRegion(u,h,l,f,this.rotation));const _=this.toCanvasImageSource();e.save();const A=w+C/2,F=T+E/2;e.translate(A,F),e.rotate(this.rotation*Math.PI/180);const P=this.rotation%180===0?1:C/E;e.scale(1/P,P),e.drawImage(_,u,h,l,f,-C/2,-E/2,C,E),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&Wr(r.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=r.rotation??this.rotation,[a,o]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&Ur(r.crop,a,o);let d,c,u,h;const{sx:l,sy:f,sWidth:w,sHeight:T}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??o,s);if(r.fit==="fill")d=0,c=0,u=i,h=n;else{const[E,_]=r.crop?[r.crop.width,r.crop.height]:[a,o],A=r.fit==="contain"?Math.min(i/E,n/_):Math.max(i/E,n/_);u=E*A,h=_*A,d=(i-u)/2,c=(n-h)/2}e.save();const C=s%180===0?1:u/h;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/C,C),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),l,f,w,T,d,c,u,h),e.restore()}_rotateSourceRegion(e,r,i,n,s){return s===90?[e,r,i,n]=[r,this.codedHeight-e-i,n,i]:s===180?[e,r]=[this.codedWidth-e-i,this.codedHeight-r-n]:s===270&&([e,r,i,n]=[this.codedWidth-r-n,e,n,i]),{sx:e,sy:r,sWidth:i,sHeight:n}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=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}[Symbol.dispose](){this.close()}}class Se{constructor(e){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 re=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Ur=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),p(t.width>=0),p(t.height>=0)},Wr=(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.")},st=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.")}},Lr=(t,e,r)=>{const i=Hr(t),n=[];let s=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),d=Math.ceil(r/a.heightDivisor),c=o*a.sampleBytes,u=c*d;n.push({offset:s,stride:c}),s+=u}return n},Hr=t=>{const e=(r,i,n,s,a)=>{const o=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return a&&o.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),o};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:ve(t),p(!1)}},Ae=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ne{get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*this.duration)}constructor(e){if(this._closed=!1,me(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ae.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const r=e.data.byteLength/(fe(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*fe(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}we?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ae.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=fe(r),a=ye(r);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*s}copyTo(e,r){if(!Ee(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ae.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:n,frameCount:s,frameOffset:a}=r,o=n??this.format;if(!o)throw new Error("Destination format not determined");const d=this.numberOfFrames,c=this.numberOfChannels,u=a??0;if(u>=d)throw new RangeError("frameOffset out of range");const h=s!==void 0?s:d-u;if(h>d-u)throw new RangeError("frameCount out of range");const l=fe(o),f=ye(o);if(f&&i>=c)throw new RangeError("planeIndex out of range");if(!f&&i!==0)throw new RangeError("planeIndex out of range");const T=(f?h:h*c)*l;if(e.byteLength<T)throw new RangeError("Destination buffer is too small");const C=Re(e),E=jr(o);if(me(this._data))if(f)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:h,format:"f32-planar"});else{const _=new ArrayBuffer(h*4),A=new Float32Array(_);this._data.copyTo(A,{planeIndex:i,frameOffset:u,frameCount:h,format:"f32-planar"});const F=new DataView(_);for(let P=0;P<h;P++){const U=P*l,R=F.getFloat32(P*4,!0);E(C,U,R)}}else{const _=c,A=new Float32Array(h);for(let F=0;F<_;F++){this._data.copyTo(A,{planeIndex:F,frameOffset:u,frameCount:h,format:"f32-planar"});for(let P=0;P<h;P++){const R=(P*_+F)*l;E(C,R,A[P])}}}else{const _=this._data,A=Re(_),F=this.format,P=$r(F),U=fe(F),R=ye(F);for(let W=0;W<h;W++)if(f){const X=W*l;let B;R?B=(i*d+(W+u))*U:B=((W+u)*c+i)*U;const S=P(A,B);E(C,X,S)}else for(let X=0;X<c;X++){const S=(W*c+X)*l;let te;R?te=(X*d+(W+u))*U:te=((W+u)*c+X)*U;const he=P(A,te);E(C,S,he)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(me(this._data)){const e=new ne(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new ne({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(we?.unregister(this),me(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(me(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ye(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let d=0,c=a;for(;c>0;){const u=Math.min(o,c),h=new Float32Array(n*u);for(let l=0;l<n;l++)e.copyFromChannel(h.subarray(l*u,(l+1)*u),l,d);yield new ne({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:r+d/s,data:h}),d+=u,c-=u}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let d=0,c=a;const u=[];for(;c>0;){const h=Math.min(o,c),l=new Float32Array(n*h);for(let w=0;w<n;w++)e.copyFromChannel(l.subarray(w*h,(w+1)*h),w,d);const f=new ne({format:"f32-planar",sampleRate:s,numberOfFrames:h,numberOfChannels:n,timestamp:r+d/s,data:l});u.push(f),d+=h,c-=h}return u}}const fe=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ye=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},$r=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},jr=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,M((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,M(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,M(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},me=t=>typeof AudioData<"u"&&t instanceof AudioData;const Dr=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};const ke=8,ot=16;const at=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Qr=t=>{const e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};class ct{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 r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%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 r=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 i=this.writer.getPos(),n=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const r=this.offsets.get(e);p(r!==void 0);const i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(const i of e.children)i&&(r+=this.measureBox(i));return r}}}const v=new Uint8Array(8),D=new DataView(v.buffer),k=t=>[(t%256+256)%256],y=t=>(D.setUint16(0,t,!1),[v[0],v[1]]),vt=t=>(D.setInt16(0,t,!1),[v[0],v[1]]),xt=t=>(D.setUint32(0,t,!1),[v[1],v[2],v[3]]),m=t=>(D.setUint32(0,t,!1),[v[0],v[1],v[2],v[3]]),Y=t=>(D.setInt32(0,t,!1),[v[0],v[1],v[2],v[3]]),ae=t=>(D.setUint32(0,Math.floor(t/2**32),!1),D.setUint32(4,t,!1),[v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]]),_t=t=>(D.setInt16(0,2**8*t,!1),[v[0],v[1]]),Q=t=>(D.setInt32(0,2**16*t,!1),[v[0],v[1],v[2],v[3]]),Be=t=>(D.setInt32(0,2**30*t,!1),[v[0],v[1],v[2],v[3]]),Pe=(t,e)=>{const r=[];let i=t;do{let n=i&127;i>>=7,r.length>0&&(n|=128),r.push(n)}while(i>0||e);return r.reverse()},O=(t,e=!1)=>{const r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},Ge=t=>{let e=null;for(const r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},St=t=>{const e=t*(Math.PI/180),r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},At=St(0),kt=t=>[Q(t[0]),Q(t[1]),Be(t[2]),Q(t[3]),Q(t[4]),Be(t[5]),Q(t[6]),Q(t[7]),Be(t[8])],b=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),x=(t,e,r,i,n)=>b(t,[k(e),xt(r),i??[]],n),Gr=t=>t.isQuickTime?b("ftyp",[O("qt "),m(512),O("qt ")]):t.fragmented?b("ftyp",[O("iso5"),m(512),O("iso5"),O("iso6"),O("mp41")]):b("ftyp",[O("isom"),m(512),O("isom"),t.holdsAvc?O("avc1"):[],O("mp41")]),be=t=>({type:"mdat",largeSize:t}),qr=t=>({type:"free",size:t}),pe=t=>b("moov",void 0,[Xr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Kr(e,t.creationTime)),t.isFragmented?Ii(t.trackDatas):null,ji(t)]),Xr=(t,e)=>{const r=I(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=Ge(a.samples);return o.timestamp+o.duration})),We),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!ue(t)||!ue(r),s=n?ae:m;return x("mvhd",+n,0,[s(t),s(t),m(We),s(r),Q(1),_t(1),Array(10).fill(0),kt(At),Array(24).fill(0),m(i)])},Kr=(t,e)=>{const r=tn(t);return b("trak",void 0,[Yr(t,e),Zr(t,e),r.name!==void 0?b("udta",void 0,[b("name",[...j.encode(r.name)])]):null])},Yr=(t,e)=>{const r=Ge(t.samples),i=I(r?r.timestamp+r.duration:0,We),n=!ue(e)||!ue(i),s=n?ae:m;let a;if(t.type==="video"){const d=t.track.metadata.rotation;a=St(d??0)}else a=At;let o=2;return t.track.metadata.disposition?.default!==!1&&(o|=1),x("tkhd",+n,o,[s(e),s(e),m(t.track.id),m(0),s(i),Array(8).fill(0),y(0),y(t.track.id),_t(t.type==="audio"?1:0),y(0),kt(a),Q(t.type==="video"?t.info.width:0),Q(t.type==="video"?t.info.height:0)])},Zr=(t,e)=>b("mdia",void 0,[Jr(t,e),qe(!0,ei[t.type],ti[t.type]),ri(t)]),Jr=(t,e)=>{const r=Ge(t.samples),i=I(r?r.timestamp+r.duration:0,t.timescale),n=!ue(e)||!ue(i),s=n?ae:m;return x("mdhd",+n,0,[s(e),s(e),m(t.timescale),s(i),y(Ft(t.track.metadata.languageCode??Zt)),y(0)])},ei={video:"vide",audio:"soun",subtitle:"text"},ti={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},qe=(t,e,r,i="\0\0\0\0")=>x("hdlr",0,0,[t?O("mhlr"):m(0),O(e),O(i),m(0),m(0),O(r,!0)]),ri=t=>b("minf",void 0,[oi[t.type](),ai(),ui(t)]),ii=()=>x("vmhd",0,1,[y(0),y(0),y(0),y(0)]),ni=()=>x("smhd",0,0,[y(0),y(0)]),si=()=>x("nmhd",0,0),oi={video:ii,audio:ni,subtitle:si},ai=()=>b("dinf",void 0,[ci()]),ci=()=>x("dref",0,0,[m(1)],[di()]),di=()=>x("url ",0,1),ui=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return b("stbl",void 0,[li(t),xi(t),e?Bi(t):null,e?Pi(t):null,Si(t),Ai(t),ki(t),_i(t)])},li=t=>{let e;if(t.type==="video")e=hi(qi(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const r=It(t.track.source._codec,t.muxer.isQuickTime);p(r),e=wi(r,t)}else t.type==="subtitle"&&(e=Ei(Yi[t.track.source._codec],t));return p(e),x("stsd",0,0,[m(1)],[e])},hi=(t,e)=>b(t,[Array(6).fill(0),y(1),y(0),y(0),Array(12).fill(0),y(e.info.width),y(e.info.height),m(4718592),m(4718592),m(0),y(1),Array(32).fill(0),y(24),vt(65535)],[Xi[e.track.source._codec](e),Xt(e.info.decoderConfig.colorSpace)?fi(e):null]),fi=t=>b("colr",[O("nclx"),y($e[t.info.decoderConfig.colorSpace.primaries]),y(je[t.info.decoderConfig.colorSpace.transfer]),y(De[t.info.decoderConfig.colorSpace.matrix]),k((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),mi=t=>t.info.decoderConfig&&b("avcC",[...q(t.info.decoderConfig.description)]),pi=t=>t.info.decoderConfig&&b("hvcC",[...q(t.info.decoderConfig.description)]),dt=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),n=Number(r[2]),s=Number(r[3]),a=r[4]?Number(r[4]):1,o=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),d=(s<<4)+(a<<1)+o,c=r[5]?Number(r[5]):e.colorSpace?.primaries?$e[e.colorSpace.primaries]:2,u=r[6]?Number(r[6]):e.colorSpace?.transfer?je[e.colorSpace.transfer]:2,h=r[7]?Number(r[7]):e.colorSpace?.matrix?De[e.colorSpace.matrix]:2;return x("vpcC",1,0,[k(i),k(n),k(d),k(c),k(u),k(h),y(0)])},gi=t=>b("av1C",ar(t.info.decoderConfig.codec)),wi=(t,e)=>{let r=0,i,n=16;if(N.includes(e.track.source._codec)){const s=e.track.source._codec,{sampleSize:a}=le(s);n=8*a,n>16&&(r=1)}return r===0?i=[Array(6).fill(0),y(1),y(r),y(0),m(0),y(e.info.numberOfChannels),y(n),y(0),y(0),y(e.info.sampleRate<2**16?e.info.sampleRate:0),y(0)]:i=[Array(6).fill(0),y(1),y(r),y(0),m(0),y(e.info.numberOfChannels),y(Math.min(n,16)),y(0),y(0),y(e.info.sampleRate<2**16?e.info.sampleRate:0),y(0),m(1),m(n/8),m(e.info.numberOfChannels*n/8),m(2)],b(t,i,[Ki(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ie=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 r=[...k(e),...k(21),...xt(0),...m(0),...m(0)];if(t.info.decoderConfig.description){const i=q(t.info.decoderConfig.description);r=[...r,...k(5),...Pe(i.byteLength),...i]}return r=[...y(1),...k(0),...k(4),...Pe(r.length),...r,...k(6),...k(1),...k(2)],r=[...k(3),...Pe(r.length),...r],x("esds",0,0,r)},K=t=>b("wave",void 0,[yi(t),bi(t),b("\0\0\0\0")]),yi=t=>b("frma",[O(It(t.track.source._codec,t.muxer.isQuickTime))]),bi=t=>{const{littleEndian:e}=le(t.track.source._codec);return b("enda",[y(+e)])},Ti=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,n=0,s=0,a=new Uint8Array(0);const o=t.info.decoderConfig?.description;if(o){p(o.byteLength>=18);const d=q(o),c=Rr(d);e=c.outputChannelCount,r=c.preSkip,i=c.inputSampleRate,n=c.outputGain,s=c.channelMappingFamily,c.channelMappingTable&&(a=c.channelMappingTable)}return b("dOps",[k(0),k(e),y(r),m(i),vt(n),k(s),...a])},Ci=t=>{const e=t.info.decoderConfig?.description;p(e);const r=q(e);return x("dfLa",0,0,[...r.subarray(4)])},L=t=>{const{littleEndian:e,sampleSize:r}=le(t.track.source._codec),i=+e;return x("pcmC",0,0,[k(i),k(8*r)])},Ei=(t,e)=>b(t,[Array(6).fill(0),y(1)],[Zi[e.track.source._codec](e)]),vi=t=>b("vttC",[...j.encode(t.info.config.description)]),xi=t=>x("stts",0,0,[m(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[m(e.sampleCount),m(e.sampleDelta)])]),_i=t=>{if(t.samples.every(r=>r.type==="key"))return null;const e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return x("stss",0,0,[m(e.length),e.map(([r])=>m(r+1))])},Si=t=>x("stsc",0,0,[m(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[m(e.firstChunk),m(e.samplesPerChunk),m(1)])]),Ai=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=le(t.track.source._codec);return x("stsz",0,0,[m(e*t.info.numberOfChannels),m(t.samples.reduce((r,i)=>r+I(i.duration,t.timescale),0))])}return x("stsz",0,0,[m(0),m(t.samples.length),t.samples.map(e=>m(e.size))])},ki=t=>t.finalizedChunks.length>0&&V(t.finalizedChunks).offset>=2**32?x("co64",0,0,[m(t.finalizedChunks.length),t.finalizedChunks.map(e=>ae(e.offset))]):x("stco",0,0,[m(t.finalizedChunks.length),t.finalizedChunks.map(e=>m(e.offset))]),Bi=t=>x("ctts",1,0,[m(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[m(e.sampleCount),Y(e.sampleCompositionTimeOffset)])]),Pi=t=>{let e=1/0,r=-1/0,i=1/0,n=-1/0;p(t.compositionTimeOffsetTable.length>0),p(t.samples.length>0);for(let a=0;a<t.compositionTimeOffsetTable.length;a++){const o=t.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),r=Math.max(r,o.sampleCompositionTimeOffset)}for(let a=0;a<t.samples.length;a++){const o=t.samples[a];i=Math.min(i,I(o.timestamp,t.timescale)),n=Math.max(n,I(o.timestamp+o.duration,t.timescale))}const s=Math.max(-e,0);return n>=2**31?null:x("cslg",0,0,[Y(s),Y(e),Y(r),Y(i),Y(n)])},Ii=t=>b("mvex",void 0,t.map(Fi)),Fi=t=>x("trex",0,0,[m(t.track.id),m(1),m(0),m(0),m(0)]),ut=(t,e)=>b("moof",void 0,[Oi(t),...e.map(Mi)]),Oi=t=>x("mfhd",0,0,[m(t)]),Bt=t=>{let e=0,r=0;const i=0,n=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|i<<8|n},Mi=t=>b("traf",void 0,[Ri(t),zi(t),Vi(t)]),Ri=t=>{p(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Bt(r)};return x("tfhd",0,e,[m(t.track.id),m(i.duration),m(i.size),m(i.flags)])},zi=t=>(p(t.currentChunk),x("tfdt",1,0,[ae(I(t.currentChunk.startTimestamp,t.timescale))])),Vi=t=>{p(t.currentChunk);const e=t.currentChunk.samples.map(T=>T.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(T=>T.size),i=t.currentChunk.samples.map(Bt),n=t.currentChunk.samples.map(T=>I(T.timestamp-T.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(r),o=new Set(i),d=new Set(n),c=o.size===2&&i[0]!==i[1],u=s.size>1,h=a.size>1,l=!c&&o.size>1,f=d.size>1||[...d].some(T=>T!==0);let w=0;return w|=1,w|=4*+c,w|=256*+u,w|=512*+h,w|=1024*+l,w|=2048*+f,x("trun",1,w,[m(t.currentChunk.samples.length),m(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?m(i[0]):[],t.currentChunk.samples.map((T,C)=>[u?m(e[C]):[],h?m(r[C]):[],l?m(i[C]):[],f?Y(n[C]):[]])])},Ni=t=>b("mfra",void 0,[...t.map(Ui),Wi()]),Ui=(t,e)=>x("tfra",1,0,[m(t.track.id),m(63),m(t.finalizedChunks.length),t.finalizedChunks.map(i=>[ae(I(i.samples[0].timestamp,t.timescale)),ae(i.moofOffset),m(e+1),m(1),m(1)])]),Wi=()=>x("mfro",0,0,[m(0)]),Li=()=>b("vtte"),Hi=(t,e,r,i,n)=>b("vttc",void 0,[n!==null?b("vsid",[Y(n)]):null,r!==null?b("iden",[...j.encode(r)]):null,e!==null?b("ctim",[...j.encode(Qr(e))]):null,i!==null?b("sttg",[...j.encode(i)]):null,b("payl",[...j.encode(t)])]),$i=t=>b("vtta",[...j.encode(t)]),ji=t=>{const e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){const n=Qi(i);n&&e.push(n)}else if(r==="mdta"){const n=Gi(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Di(e,t.output._metadataTags);return e.length===0?null:b("udta",void 0,e)},Di=(t,e)=>{for(const{key:r,value:i}of gt(e))switch(r){case"title":t.push(H("©nam",i));break;case"description":t.push(H("©des",i));break;case"artist":t.push(H("©ART",i));break;case"album":t.push(H("©alb",i));break;case"albumArtist":t.push(H("albr",i));break;case"genre":t.push(H("©gen",i));break;case"date":t.push(H("©day",i.toISOString().slice(0,10)));break;case"comment":t.push(H("©cmt",i));break;case"lyrics":t.push(H("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ve(r)}if(e.raw)for(const r in e.raw){const i=e.raw[r];i==null||r.length!==4||t.some(n=>n.type===r)||(typeof i=="string"?t.push(H(r,i)):i instanceof Uint8Array&&t.push(b(r,Array.from(i))))}},H=(t,e)=>{const r=j.encode(e);return b(t,[y(r.length),y(Ft("und")),Array.from(r)])},lt={"image/jpeg":13,"image/png":14,"image/bmp":27},Pt=(t,e)=>{const r=[];for(const{key:i,value:n}of gt(t))switch(i){case"title":r.push({key:e?"title":"©nam",value:z(n)});break;case"description":r.push({key:e?"description":"©des",value:z(n)});break;case"artist":r.push({key:e?"artist":"©ART",value:z(n)});break;case"album":r.push({key:e?"album":"©alb",value:z(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:z(n)});break;case"comment":r.push({key:e?"comment":"©cmt",value:z(n)});break;case"genre":r.push({key:e?"genre":"©gen",value:z(n)});break;case"lyrics":r.push({key:e?"lyrics":"©lyr",value:z(n)});break;case"date":r.push({key:e?"date":"©day",value:z(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&r.push({key:"covr",value:b("data",[m(lt[s.mimeType]??0),m(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();r.push({key:"track",value:z(s)})}else r.push({key:"trkn",value:b("data",[m(0),m(0),y(0),y(n),y(t.tracksTotal??0),y(0)])});break;case"discNumber":e||r.push({key:"disc",value:b("data",[m(0),m(0),y(0),y(n),y(t.discsTotal??0),y(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ve(i)}if(t.raw)for(const i in t.raw){const n=t.raw[i];n==null||!e&&i.length!==4||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:z(n)}):n instanceof Uint8Array?r.push({key:i,value:b("data",[m(0),m(0),Array.from(n)])}):n instanceof wt&&r.push({key:i,value:b("data",[m(lt[n.mimeType]??0),m(0),Array.from(n.data)])}))}return r},Qi=t=>{const e=Pt(t,!1);return e.length===0?null:x("meta",0,0,void 0,[qe(!1,"mdir","","appl"),b("ilst",void 0,e.map(r=>b(r.key,void 0,[r.value])))])},Gi=t=>{const e=Pt(t,!0);return e.length===0?null:b("meta",void 0,[qe(!1,"mdta",""),x("keys",0,0,[m(e.length)],e.map(r=>b("mdta",[...j.encode(r.key)]))),b("ilst",void 0,e.map((r,i)=>{const n=String.fromCharCode(...m(i+1));return b(n,void 0,[r.value])}))])},z=t=>b("data",[m(1),m(0),...j.encode(t)]),qi=(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"}},Xi={avc:mi,hevc:pi,vp8:dt,vp9:dt,av1:gi},It=(t,e)=>{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"}if(e)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"}},Ki=(t,e)=>{switch(t){case"aac":return Ie;case"mp3":return Ie;case"opus":return Ti;case"vorbis":return Ie;case"flac":return Ci}if(e)switch(t){case"pcm-s24":return K;case"pcm-s24be":return K;case"pcm-s32":return K;case"pcm-s32be":return K;case"pcm-f32":return K;case"pcm-f32be":return K;case"pcm-f64":return K;case"pcm-f64be":return K}else switch(t){case"pcm-s16":return L;case"pcm-s16be":return L;case"pcm-s24":return L;case"pcm-s24be":return L;case"pcm-s32":return L;case"pcm-s32be":return L;case"pcm-f32":return L;case"pcm-f32be":return L;case"pcm-f64":return L;case"pcm-f64be":return L}return null},Yi={webvtt:"wvtt"},Zi={webvtt:vi},Ft=t=>{p(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};class Ji{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}const i=r+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+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 r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}}const Fe=2**16,Oe=2**32;class Ot extends Ji{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Fe,{maxByteLength:Oe})}catch{this.buffer=new ArrayBuffer(Fe),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Fe);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>Oe)throw new Error(`ArrayBuffer exceeded maximum size of ${Oe} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{const i=new ArrayBuffer(r),n=new Uint8Array(i);n.set(this.bytes,0),this.buffer=i,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}}class Mt{constructor(){this._output=null,this.onwrite=null}}class Rt extends Mt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Ot(this)}}const We=1e3,en=2082844800,tn=t=>{const e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},I=(t,e,r=!0)=>{const i=t*e;return r?Math.round(i):i};class rn extends Er{constructor(e,r){super(e),this.auxTarget=new Rt,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ct(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Kt(),this.creationTime=Math.floor(Date.now()/1e3)+en,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new ct(this.writer),this.isQuickTime=r instanceof Ut;const i=this.writer instanceof Ot?"in-memory":!1;this.fastStart=r._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),r=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Gr({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=be(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Dr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;yr(i),p(i),p(i.decoderConfig);const s={...i.decoderConfig};p(s.codedWidth!==void 0),p(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){const c=xr(r.data);if(!c)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=_r(c),a=!0}else if(e.source._codec==="hevc"&&!s.description){const c=Ar(r.data);if(!c)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=Mr(c),a=!0}const o=tr(1/(e.metadata.frameRate??57600),1e6).denominator,d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;Tr(r),p(r),p(r.decoderConfig);const n={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&N.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(e,r){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;Cr(r),p(r),p(r.config);const n={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,r,i);let a=r.data;if(s.info.requiresAnnexBTransformation){const c=vr(a);if(!c)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.");a=c}const o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),d=this.createSampleForTrack(s,a,o,r.duration,r.type);await this.registerSample(s,d)}finally{n()}}async addEncodedAudioPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),o=this.createSampleForTrack(s,r.data,a,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,a),await this.registerSample(s,o)}finally{n()}}async maybePadWithSilence(e,r){const i=V(e.samples),n=i?i.timestamp+i.duration:0,s=r-n,a=I(s,e.timescale);if(a>0){const{sampleSize:o,silentValue:d}=le(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(o*c).fill(d),h=this.createSampleForTrack(e,new Uint8Array(u.buffer),n,s,"key");await this.registerSample(e,h)}}async addSubtitleCue(e,r,i){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)p(c.timestamp<=r),p(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,u)=>c-u),s=n[0],a=n[1]??s;if(r<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=Li();this.auxBoxWriter.writeBox(c);const u=this.auxWriter.getSlice(0,this.auxWriter.getPos()),h=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,h),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const u=e.cueQueue[c];if(u.timestamp>=a)break;at.lastIndex=0;const h=at.test(u.text),l=u.timestamp+u.duration;let f=e.cueToSourceId.get(u);if(f===void 0&&a<l&&(f=e.nextSourceId++,e.cueToSourceId.set(u,f)),u.notes){const T=$i(u.notes);this.auxBoxWriter.writeBox(T)}const w=Hi(u.text,h?s:null,u.identifier??null,u.settings??null,f??null);this.auxBoxWriter.writeBox(w),l===a&&e.cueQueue.splice(c--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=a}}createSampleForTrack(e,r,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:I(n,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const a=e.timestampProcessingQueue[s],o=I(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const s=V(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);const a=I(s.timestamp-s.decodeTimestamp,e.timescale),o=I(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const d=I(s.decodeTimestamp,e.timescale,!1),c=Math.round(d-e.lastTimescaleUnits);if(p(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let u=V(e.timeToSampleTable);if(p(u),u.sampleCount===1){u.sampleDelta=c;const l=e.timeToSampleTable[e.timeToSampleTable.length-2];l&&l.sampleDelta===c&&(l.sampleCount++,e.timeToSampleTable.pop(),u=l)}else u.sampleDelta!==c&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:c}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const h=V(e.compositionTimeOffsetTable);p(h),h.sampleCompositionTimeOffset===a?h.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=I(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(r.type==="key");const n=I(r.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),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 i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);const n=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(a=>{if(e===a)return r.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),p(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(p(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,n)=>i+I(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||V(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;const n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(e=!0){p(this.isFragmented);const r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const f=pe(this);if(this.boxWriter.writeBox(f),this.format._options.onMoov){const{data:w,start:T}=this.writer.stopTrackingWrites();this.format._options.onMoov(w,T)}}const i=this.trackDatas.filter(f=>f.currentChunk),n=ut(r,i),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+ke,d=1/0;for(const f of i){f.currentChunk.offset=o,f.currentChunk.moofOffset=s;for(const w of f.currentChunk.samples)o+=w.size;d=Math.min(d,f.currentChunk.startTimestamp)}const c=o-a,u=c>=2**32;if(u)for(const f of i)f.currentChunk.offset+=ot-ke;this.format._options.onMoof&&this.writer.startTrackingWrites();const h=ut(r,i);if(this.boxWriter.writeBox(h),this.format._options.onMoof){const{data:f,start:w}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,w,d)}p(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const l=be(u);l.size=c,this.boxWriter.writeBox(l),this.writer.seek(a+(u?ot:ke));for(const f of i)for(const w of f.currentChunk.samples)this.writer.write(w.data),w.data=null;if(this.format._options.onMdat){const{data:f,start:w}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,w)}for(const f of i)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){const i=pe(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=be(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(const r of this.trackDatas){const i=r.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const r=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(n=>n.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(const r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=be(!1);let r;for(let n=0;n<2;n++){const s=pe(this),a=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+r;for(const d of this.finalizedChunks){d.offset=o;for(const{data:c}of d.samples)p(c),o+=c.byteLength,r+=c.byteLength}if(o<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=pe(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,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.format._options.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){const r=this.writer.getPos(),i=Ni(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{p(this.mdat);const r=this.boxWriter.offsets.get(this.mdat);p(r!==void 0);const i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}const n=pe(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(qr(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}class zt{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ee.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>oe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ce.includes(e))}_codecUnsupportedHint(e){return""}}class Vt extends zt{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&&(!Number.isFinite(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:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new rn(e,this)}}class Nt extends Vt{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ee,...yt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ce]}_codecUnsupportedHint(e){return new Ut().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Ut extends Vt{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ee,...oe]}_codecUnsupportedHint(e){return new Nt().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const nn=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!ee.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${ee.join(", ")}.`);if(!(t.bitrate instanceof ce)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate 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.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, 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.");Wt(t.codec,t)},Wt=(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'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))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&&Ct(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.")},Le=t=>{const e=t.bitrate instanceof ce?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??or(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...lr(t.codec)}},sn=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!oe.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${oe.join(", ")}.`);if(t.bitrate===void 0&&(!N.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof ce)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, 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.");Lt(t.codec,t)},Lt=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Ct(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},He=t=>{const e=t.bitrate instanceof ce?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??cr(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...hr(t.codec)}};class ce{constructor(e){this._factor=e}_toVideoBitrate(e,r,i){const n=r*i,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,d=Math.pow(n/a,.95),h=o*d*s[e]*this._factor;return Math.ceil(h/1e3)*1e3}_toAudioBitrate(e){if(N.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a)),Math.round(n/1e3)*1e3}}const Ht=new ce(2),on=async(t,e={})=>{const{width:r=1280,height:i=720,bitrate:n=1e6,...s}=e;if(!ee.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(n instanceof ce)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Wt(t,s);let a=null;return Ne.length>0&&(a??=Le({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s}),Ne.some(c=>c.supports(t,a)))?!0:typeof VideoEncoder>"u"||(r%2===1||i%2===1)&&(t==="avc"||t==="hevc")||(a??=Le({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(a)).supported)?!1:Te()?new Promise(async c=>{try{const u=new VideoEncoder({output:()=>{},error:()=>c(!1)});u.configure(a);const h=new Uint8Array(r*i*4),l=new VideoFrame(h,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});u.encode(l),l.close(),await u.flush(),c(!0)}catch{c(!1)}}):!0},an=async(t,e={})=>{const{numberOfChannels:r=2,sampleRate:i=48e3,bitrate:n=128e3,...s}=e;if(!oe.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(n instanceof ce)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");Lt(t,s);let a=null;return Ue.length>0&&(a??=He({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s}),Ue.some(d=>d.supports(t,a)))||N.includes(t)?!0:typeof AudioEncoder>"u"?!1:(a??=He({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s}),(await AudioEncoder.isConfigSupported(a)).supported===!0)},cn=async(t,e)=>{for(const r of t)if(await on(r,e))return r;return null},dn=async(t,e)=>{for(const r of t)if(await an(r,e))return r;return null};class Xe{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_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?this._closingPromise:this._flushAndClose(e)}}class $t extends Xe{constructor(e){if(super(),this._connectedTrack=null,!ee.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ee.join(", ")}.`);this._codec=e}}class un{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new pt,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(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 'strict' in the encoding options.`);{let d=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),d=!0);const c=this.resizeCanvas.getContext("2d",{alpha:Te()});p(c),d||(Te()?(c.fillStyle="black",c.fillRect(0,0,this.codedWidth,this.codedHeight)):c.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(c,{fit:o}),r&&e.close(),e=new ie(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/n),a={...i,keyFrame:i?.keyFrame||n===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(c=>this.error??=c).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await d}else{p(this.encoder);const o=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(o,a),o.close();else if(!!o.format&&!o.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close();else{const c=o.displayWidth,u=o.displayHeight;if(!this.splitter)try{this.splitter=new ln(c,u)}catch(h){console.error("Due to an error, only color data will be encoded.",h),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close()}if(this.splitter){const h=this.splitter.extractColor(o),l=this.splitter.extractAlpha(o);this.alphaFrameQueue.push(l),this.encoder.encode(h,a),h.close(),o.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(d=>this.encoder.addEventListener("dequeue",d,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const i=Le({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const n=Ne.find(s=>s.supports(this.encodingConfig.codec,i));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(s,a)=>{if(!(s instanceof J))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,a).catch(o=>{this.error??=o,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.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.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const o=[],d=[];let c=0,u=0;const h=(l,f,w)=>{const T={};if(f){const E=new Uint8Array(f.byteLength);f.copyTo(E),T.alpha=E}const C=J.fromEncodedChunk(l,T);this.encodingConfig.onEncodedPacket?.(C,w),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,C,w).catch(E=>{this.error??=E,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(l,f)=>{if(!this.alphaEncoder){h(l,null,f);return}const w=this.alphaFrameQueue.shift();p(w!==void 0),w?(this.alphaEncoder.encode(w,{keyFrame:l.type==="key"}),u++,w.close(),o.push({chunk:l,meta:f})):u===0?h(l,null,f):(d.push(c+u),o.push({chunk:l,meta:f}))},error:l=>{l.stack=r.stack,this.error??=l}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(l,f)=>{u--;const w=o.shift();for(p(w!==void 0),h(w.chunk,l,w.meta),c++;d.length>0&&d[0]===c;){d.shift();const T=o.shift();p(T!==void 0),h(T.chunk,null,T.meta)}},error:l=>{l.stack=r.stack,this.error??=l}}),this.alphaEncoder.configure(i))}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class ln{constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
1
|
+
import{c as qt}from"./index-DwC8Pbug.js";function p(t){if(!t)throw new Error("Assertion failed.")}const V=t=>t&&t[t.length-1],ue=t=>t>=0&&t<2**32;class se{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let a=this.bytes[s];const o=7-(n&7);a&=~(1<<o),a|=(r&1<<i-n-1)>>i-n-1<<o,this.bytes[s]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new se(this.bytes);return e.pos=this.pos,e}}const g=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},G=t=>{const e=g(t);return(e&1)===0?-(e>>1):e+1>>1},q=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Re=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),j=new TextEncoder,$e={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},je={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},De={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Xt=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,Ee=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class ft{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const r=new Promise(n=>{e=n}),i=this.currentPromise;return this.currentPromise=r,await i,e}}const Kt=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}},ve=t=>{throw new Error(`Unexpected value: ${t}`)},mt=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},Yt=(t,e,r,i)=>{r=M(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),mt(t,e,r,i)},M=(t,e,r)=>Math.max(e,Math.min(r,t)),Zt="und",Jt=/^[a-z]{3}$/,er=t=>Jt.test(t),Z=1e6*(1+Number.EPSILON),tr=(t,e)=>{const r=t<0?-1:1;t=Math.abs(t);let i=0,n=1,s=1,a=0,o=t;for(;;){const d=Math.floor(o),c=d*s+i,u=d*a+n;if(u>e)return{numerator:r*s,denominator:a};if(i=s,n=a,s=c,a=u,o=1/(o-d),!isFinite(o))break}return{numerator:r*s,denominator:a}};class pt{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let xe=null;const Te=()=>xe!==null?xe:xe=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),gt=function*(t){for(const e in t){const r=t[e];r!==void 0&&(yield{key:e,value:r})}},rr=()=>{Symbol.dispose??=Symbol("Symbol.dispose")};class wt{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}}class ir{constructor(e,r,i,n){if(this.data=e,this.mimeType=r,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const nr=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(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"&&!(e instanceof Uint8Array)&&!(e instanceof wt)&&!(e instanceof ir))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},sr=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};const ee=["avc","hevc","vp9","av1","vp8"],N=["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"],yt=["aac","opus","mp3","vorbis","flac"],oe=[...yt,...N],Ce=["webvtt"],Ke=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],Ye=[{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}],Ze=[{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}],Je=[{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}],or=(t,e,r,i)=>{if(t==="avc"){const s=Math.ceil(e/16)*Math.ceil(r/16),a=Ke.find(h=>s<=h.maxMacroblocks&&i<=h.maxBitrate)??V(Ke),o=a?a.level:0,d="64".padStart(2,"0"),c="00",u=o.toString(16).padStart(2,"0");return`avc1.${d}${c}${u}`}else if(t==="hevc"){const o=e*r,d=Ye.find(u=>o<=u.maxPictureSize&&i<=u.maxBitrate)??V(Ye);return`hev1.1.6.${d.tier}${d.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const s=e*r;return`vp09.00.${(Ze.find(d=>s<=d.maxPictureSize&&i<=d.maxBitrate)??V(Ze)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){const s=e*r,a=Je.find(c=>s<=c.maxPictureSize&&i<=c.maxBitrate)??V(Je);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${t}'.`)},ar=t=>{const e=t.split("."),n=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),d=(s<<5)+o,c=a.slice(-1)==="H"?1:0,h=Number(e[3])===8?0:1,l=0,f=e[4]?Number(e[4]):0,w=e[5]?Number(e[5][0]):1,T=e[5]?Number(e[5][1]):1,C=e[5]?Number(e[5][2]):0,E=(c<<7)+(h<<6)+(l<<5)+(f<<4)+(w<<3)+(T<<2)+C;return[n,d,E,0]},cr=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(N.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ze=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],bt=[-1,1,2,3,4,5,6,8],dr=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new se(t);let r=e.readBits(5);r===31&&(r=32+e.readBits(6));const i=e.readBits(4);let n=null;i===15?n=e.readBits(24):i<ze.length&&(n=ze[i]);const s=e.readBits(4);let a=null;return s>=1&&s<=7&&(a=bt[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},ur=t=>{let e=ze.indexOf(t.sampleRate),r=null;e===-1&&(e=15,r=t.sampleRate);const i=bt.indexOf(t.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),e===15&&(n+=24);const s=Math.ceil(n/8),a=new Uint8Array(s),o=new se(a);return t.objectType<32?o.writeBits(5,t.objectType):(o.writeBits(5,31),o.writeBits(6,t.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,r),o.writeBits(4,i),a},Tt=/^pcm-([usf])(\d+)+(be)?$/,le=t=>{if(p(N.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=Tt.exec(t);p(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";const i=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:n,silentValue:s}},Ct=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":Tt.test(t)?t:t==="webvtt"?"webvtt":null,lr=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},hr=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},fr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],mr=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,pr=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,gr=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,wr=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,yr=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!fr.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!Ee(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:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys($e);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(je);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(De);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!mr.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(!pr.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(!gr.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")&&!wr.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/.')},br=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Tr=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!br.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!Ee(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!N.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${N.join(", ")}).`)},Cr=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 Er{constructor(e){this.mutex=new ft,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,r,i){r+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:r},this.trackTimestampInfo.set(e,n)}if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),r<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 ${r}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);return n.maxTimestamp=Math.max(n.maxTimestamp,r),r}}var ge;(function(t){t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.SPS_EXT=13]="SPS_EXT"})(ge||(ge={}));var $;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})($||($={}));const Qe=t=>{const e=[];let r=0;for(;r<t.length;){let i=-1,n=0;for(let s=r;s<t.length-3;s++){if(t[s]===0&&t[s+1]===0&&t[s+2]===1){i=s,n=3;break}if(s<t.length-4&&t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1){i=s,n=4;break}}if(i===-1)break;if(r>0&&i>r){const s=t.subarray(r,i);s.length>0&&e.push(s)}r=i+n}if(r<t.length){const i=t.subarray(r);i.length>0&&e.push(i)}return e},Ve=t=>{const e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},vr=t=>{const r=Qe(t);if(r.length===0)return null;let i=0;for(const o of r)i+=4+o.byteLength;const n=new Uint8Array(i),s=new DataView(n.buffer);let a=0;for(const o of r){const d=o.byteLength;s.setUint32(a,d,!1),a+=4,n.set(o,a),a+=o.byteLength}return n},_e=t=>t[0]&31,xr=t=>{try{const e=Qe(t),r=e.filter(d=>_e(d)===ge.SPS),i=e.filter(d=>_e(d)===ge.PPS),n=e.filter(d=>_e(d)===ge.SPS_EXT);if(r.length===0||i.length===0)return null;const s=r[0],a=Sr(s);p(a!==null);const o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:r,pictureParameterSets:i,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},_r=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 r of t.sequenceParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(const r of t.pictureParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){p(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 r of t.sequenceParameterSetExt){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)},Sr=t=>{try{const e=new se(Ve(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();g(e);let a=null,o=null,d=null;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=g(e),a===3&&e.skipBits(1),o=g(e),d=g(e),e.skipBits(1),e.readBits(1))){for(let l=0;l<(a!==3?8:12);l++)if(e.readBits(1)){const w=l<6?16:64;let T=8,C=8;for(let E=0;E<w;E++){if(C!==0){const _=G(e);C=(T+_+256)%256}T=C===0?T:C}}}g(e);const c=g(e);if(c===0)g(e);else if(c===1){e.skipBits(1),G(e),G(e);const h=g(e);for(let l=0;l<h;l++)G(e)}g(e),e.skipBits(1),g(e),g(e);const u=e.readBits(1);return{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:u,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:d}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},de=t=>t[0]>>1&63,Ar=t=>{try{const e=Qe(t),r=e.filter(B=>de(B)===$.VPS_NUT),i=e.filter(B=>de(B)===$.SPS_NUT),n=e.filter(B=>de(B)===$.PPS_NUT),s=e.filter(B=>de(B)===$.PREFIX_SEI_NUT||de(B)===$.SUFFIX_SEI_NUT);if(i.length===0||n.length===0)return null;const a=i[0],o=new se(Ve(a));o.skipBits(16),o.readBits(4);const d=o.readBits(3),c=o.readBits(1),{general_profile_space:u,general_tier_flag:h,general_profile_idc:l,general_profile_compatibility_flags:f,general_constraint_indicator_flags:w,general_level_idc:T}=kr(o,d);g(o);const C=g(o);C===3&&o.skipBits(1),g(o),g(o),o.readBits(1)&&(g(o),g(o),g(o),g(o));const E=g(o),_=g(o);g(o);const F=o.readBits(1)?0:d;for(let B=F;B<=d;B++)g(o),g(o),g(o);g(o),g(o),g(o),g(o),g(o),g(o),o.readBits(1)&&o.readBits(1)&&Br(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),g(o),g(o),o.skipBits(1));const P=g(o);if(Pr(o,P),o.readBits(1)){const B=g(o);for(let S=0;S<B;S++)g(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let U=0;o.readBits(1)&&(U=Fr(o,d));let R=0;if(n.length>0){const B=n[0],S=new se(Ve(B));S.skipBits(16),g(S),g(S),S.skipBits(1),S.skipBits(1),S.skipBits(3),S.skipBits(1),S.skipBits(1),g(S),g(S),G(S),S.skipBits(1),S.skipBits(1),S.readBits(1)&&g(S),G(S),G(S),S.skipBits(1),S.skipBits(1),S.skipBits(1),S.skipBits(1);const te=S.readBits(1),he=S.readBits(1);!te&&!he?R=0:te&&!he?R=2:!te&&he?R=3:R=0}const W=[...r.length?[{arrayCompleteness:1,nalUnitType:$.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:$.SPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:$.PPS_NUT,nalUnits:n}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:de(s[0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:u,generalTierFlag:h,generalProfileIdc:l,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:w,generalLevelIdc:T,minSpatialSegmentationIdc:U,parallelismType:R,chromaFormatIdc:C,bitDepthLumaMinus8:E,bitDepthChromaMinus8:_,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:d+1,temporalIdNested:c,lengthSizeMinusOne:3,arrays:W}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},kr=(t,e)=>{const r=t.readBits(2),i=t.readBits(1),n=t.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|t.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=t.readBits(8);const o=t.readBits(8),d=[],c=[];for(let u=0;u<e;u++)d.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let u=e;u<8;u++)t.skipBits(2);for(let u=0;u<e;u++)d[u]&&t.skipBits(88),c[u]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Br=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))g(t);else{const n=Math.min(64,1<<4+(e<<1));e>1&&G(t);for(let s=0;s<n;s++)G(t)}},Pr=(t,e)=>{const r=[];for(let i=0;i<e;i++)r[i]=Ir(t,i,e,r)},Ir=(t,e,r,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){const d=g(t);a=e-(d+1)}else a=e-1;t.readBits(1),g(t);const o=i[a]??0;for(let d=0;d<=o;d++)t.readBits(1)||t.readBits(1);n=i[a]}else{const o=g(t),d=g(t);for(let c=0;c<o;c++)g(t),t.readBits(1);for(let c=0;c<d;c++)g(t),t.readBits(1);n=o+d}return n},Fr=(t,e)=>{if(t.readBits(1)&&t.readBits(8)===255&&(t.readBits(16),t.readBits(16)),t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),t.readBits(1),t.readBits(1)&&(t.readBits(8),t.readBits(8),t.readBits(8))),t.readBits(1)&&(g(t),g(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(g(t),g(t),g(t),g(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&g(t),t.readBits(1)&&Or(t,!0,e)),t.readBits(1)){t.readBits(1),t.readBits(1),t.readBits(1);const r=g(t);return g(t),g(t),g(t),g(t),r}return 0},Or=(t,e,r)=>{let i=!1,n=!1,s=!1;i=t.readBits(1)===1,n=t.readBits(1)===1,(i||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 a=0;a<=r;a++){const o=t.readBits(1)===1;let d=!0;o||(d=t.readBits(1)===1);let c=!1;d?g(t):c=t.readBits(1)===1;let u=1;c||(u=g(t)+1),i&&et(t,u,s),n&&et(t,u,s)}},et=(t,e,r)=>{for(let i=0;i<e;i++)g(t),g(t),r&&(g(t),g(t)),t.readBits(1)},Mr=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 r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(const i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},Rr=t=>{const e=Re(t),r=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}};var tt;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(tt||(tt={}));const Ne=[],Ue=[];const rt=new Uint8Array(0);class J{constructor(e,r,i,n,s=-1,a,o){if(this.data=e,this.type=r,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===rt&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))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(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rt}get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedVideoChunk.");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("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new J(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");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.");return new J(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}const zr=t=>{let i=t,n=4096,s=0,a=12,o=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(s|a-5<<4|o)&255},Vr=t=>{let r=2048,i=0,n=11,s=0,a=t;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&r)!==r&&n>=5;)r>>=1,n--;return s=a>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85};rr();let it=-1/0,nt=-1/0,we=null;typeof FinalizationRegistry<"u"&&(we=new FinalizationRegistry(t=>{const e=Date.now();t.type==="video"?(e-it>=1e3&&(console.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."),it=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-nt>=1e3&&(console.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."),nt=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));const Et=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Nr=new Set(Et);class ie{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!Nr.has(r.format))throw new TypeError("init.format must be one of: "+Et.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=q(e).slice(),this._layout=r.layout??Lr(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Se(r.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new Se(e.colorSpace)}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(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new ie(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Z),duration:Math.trunc((r.duration??0)*Z)||void 0}),r);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(i,n),a=s.getContext("2d",{alpha:Te(),willReadFrequently:!0});p(a),a.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=n,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Se({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");we?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),re(this._data)?new ie(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(p(this._layout),new ie(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})):new ie(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(we?.unregister(this),re(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(st(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. Please manually provide an RGB pixel format in the options instead.");if(p(this._data!==null),!re(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const r=this.toVideoFrame(),i=r.allocationSize(e);return r.close(),i}return re(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!Ee(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(st(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)===null)throw new Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(p(this._data!==null),!re(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){const i=this.toVideoFrame(),n=await i.copyTo(e,r);return i.close(),n}if(re(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array)return p(this._layout),q(e).set(this._data),this._layout;{const n=this._data.getContext("2d");p(n);const s=n.getImageData(0,0,this.codedWidth,this.codedHeight);return q(e).set(s.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),re(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,r,i,n,s,a,o,d,c){let u=0,h=0,l=this.displayWidth,f=this.displayHeight,w=0,T=0,C=this.displayWidth,E=this.displayHeight;if(a!==void 0?(u=r,h=i,l=n,f=s,w=a,T=o,d!==void 0?(C=d,E=c):(C=l,E=f)):(w=r,T=i,n!==void 0&&(C=n,E=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(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(h))throw new TypeError("sy must be a number.");if(!Number.isFinite(l)||l<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(w))throw new TypeError("dx must be a number.");if(!Number.isFinite(T))throw new TypeError("dy must be a number.");if(!Number.isFinite(C)||C<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(E)||E<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:h,sWidth:l,sHeight:f}=this._rotateSourceRegion(u,h,l,f,this.rotation));const _=this.toCanvasImageSource();e.save();const A=w+C/2,F=T+E/2;e.translate(A,F),e.rotate(this.rotation*Math.PI/180);const P=this.rotation%180===0?1:C/E;e.scale(1/P,P),e.drawImage(_,u,h,l,f,-C/2,-E/2,C,E),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");r.crop!==void 0&&Wr(r.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=r.rotation??this.rotation,[a,o]=s%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];r.crop&&Ur(r.crop,a,o);let d,c,u,h;const{sx:l,sy:f,sWidth:w,sHeight:T}=this._rotateSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??o,s);if(r.fit==="fill")d=0,c=0,u=i,h=n;else{const[E,_]=r.crop?[r.crop.width,r.crop.height]:[a,o],A=r.fit==="contain"?Math.min(i/E,n/_):Math.max(i/E,n/_);u=E*A,h=_*A,d=(i-u)/2,c=(n-h)/2}e.save();const C=s%180===0?1:u/h;e.translate(i/2,n/2),e.rotate(s*Math.PI/180),e.scale(1/C,C),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),l,f,w,T,d,c,u,h),e.restore()}_rotateSourceRegion(e,r,i,n,s){return s===90?[e,r,i,n]=[r,this.codedHeight-e-i,n,i]:s===180?[e,r]=[this.codedWidth-e-i,this.codedHeight-r-n]:s===270&&([e,r,i,n]=[this.codedWidth-r-n,e,n,i]),{sx:e,sy:r,sWidth:i,sHeight:n}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=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}[Symbol.dispose](){this.close()}}class Se{constructor(e){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 re=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Ur=(t,e,r)=>{t.left=Math.min(t.left,e),t.top=Math.min(t.top,r),t.width=Math.min(t.width,e-t.left),t.height=Math.min(t.height,r-t.top),p(t.width>=0),p(t.height>=0)},Wr=(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.")},st=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.")}},Lr=(t,e,r)=>{const i=Hr(t),n=[];let s=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),d=Math.ceil(r/a.heightDivisor),c=o*a.sampleBytes,u=c*d;n.push({offset:s,stride:c}),s+=u}return n},Hr=t=>{const e=(r,i,n,s,a)=>{const o=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return a&&o.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),o};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:ve(t),p(!1)}},Ae=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ne{get microsecondTimestamp(){return Math.trunc(Z*this.timestamp)}get microsecondDuration(){return Math.trunc(Z*this.duration)}constructor(e){if(this._closed=!1,me(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ae.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const r=e.data.byteLength/(fe(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*fe(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}we?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ae.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=fe(r),a=ye(r);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*s}copyTo(e,r){if(!Ee(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ae.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:n,frameCount:s,frameOffset:a}=r,o=n??this.format;if(!o)throw new Error("Destination format not determined");const d=this.numberOfFrames,c=this.numberOfChannels,u=a??0;if(u>=d)throw new RangeError("frameOffset out of range");const h=s!==void 0?s:d-u;if(h>d-u)throw new RangeError("frameCount out of range");const l=fe(o),f=ye(o);if(f&&i>=c)throw new RangeError("planeIndex out of range");if(!f&&i!==0)throw new RangeError("planeIndex out of range");const T=(f?h:h*c)*l;if(e.byteLength<T)throw new RangeError("Destination buffer is too small");const C=Re(e),E=jr(o);if(me(this._data))if(f)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:h,format:"f32-planar"});else{const _=new ArrayBuffer(h*4),A=new Float32Array(_);this._data.copyTo(A,{planeIndex:i,frameOffset:u,frameCount:h,format:"f32-planar"});const F=new DataView(_);for(let P=0;P<h;P++){const U=P*l,R=F.getFloat32(P*4,!0);E(C,U,R)}}else{const _=c,A=new Float32Array(h);for(let F=0;F<_;F++){this._data.copyTo(A,{planeIndex:F,frameOffset:u,frameCount:h,format:"f32-planar"});for(let P=0;P<h;P++){const R=(P*_+F)*l;E(C,R,A[P])}}}else{const _=this._data,A=Re(_),F=this.format,P=$r(F),U=fe(F),R=ye(F);for(let W=0;W<h;W++)if(f){const X=W*l;let B;R?B=(i*d+(W+u))*U:B=((W+u)*c+i)*U;const S=P(A,B);E(C,X,S)}else for(let X=0;X<c;X++){const S=(W*c+X)*l;let te;R?te=(X*d+(W+u))*U:te=((W+u)*c+X)*U;const he=P(A,te);E(C,S,he)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(me(this._data)){const e=new ne(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new ne({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(we?.unregister(this),me(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(me(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ye(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let d=0,c=a;for(;c>0;){const u=Math.min(o,c),h=new Float32Array(n*u);for(let l=0;l<n;l++)e.copyFromChannel(h.subarray(l*u,(l+1)*u),l,d);yield new ne({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:r+d/s,data:h}),d+=u,c-=u}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(i/n);let d=0,c=a;const u=[];for(;c>0;){const h=Math.min(o,c),l=new Float32Array(n*h);for(let w=0;w<n;w++)e.copyFromChannel(l.subarray(w*h,(w+1)*h),w,d);const f=new ne({format:"f32-planar",sampleRate:s,numberOfFrames:h,numberOfChannels:n,timestamp:r+d/s,data:l});u.push(f),d+=h,c-=h}return u}}const fe=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ye=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},$r=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},jr=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,M((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,M(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,M(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},me=t=>typeof AudioData<"u"&&t instanceof AudioData;const Dr=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};const ke=8,ot=16;const at=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Qr=t=>{const e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};class ct{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 r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%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 r=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 i=this.writer.getPos(),n=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const r=this.offsets.get(e);p(r!==void 0);const i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(const i of e.children)i&&(r+=this.measureBox(i));return r}}}const v=new Uint8Array(8),D=new DataView(v.buffer),k=t=>[(t%256+256)%256],y=t=>(D.setUint16(0,t,!1),[v[0],v[1]]),vt=t=>(D.setInt16(0,t,!1),[v[0],v[1]]),xt=t=>(D.setUint32(0,t,!1),[v[1],v[2],v[3]]),m=t=>(D.setUint32(0,t,!1),[v[0],v[1],v[2],v[3]]),Y=t=>(D.setInt32(0,t,!1),[v[0],v[1],v[2],v[3]]),ae=t=>(D.setUint32(0,Math.floor(t/2**32),!1),D.setUint32(4,t,!1),[v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]]),_t=t=>(D.setInt16(0,2**8*t,!1),[v[0],v[1]]),Q=t=>(D.setInt32(0,2**16*t,!1),[v[0],v[1],v[2],v[3]]),Be=t=>(D.setInt32(0,2**30*t,!1),[v[0],v[1],v[2],v[3]]),Pe=(t,e)=>{const r=[];let i=t;do{let n=i&127;i>>=7,r.length>0&&(n|=128),r.push(n)}while(i>0||e);return r.reverse()},O=(t,e=!1)=>{const r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},Ge=t=>{let e=null;for(const r of t)(!e||r.timestamp>e.timestamp)&&(e=r);return e},St=t=>{const e=t*(Math.PI/180),r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},At=St(0),kt=t=>[Q(t[0]),Q(t[1]),Be(t[2]),Q(t[3]),Q(t[4]),Be(t[5]),Q(t[6]),Q(t[7]),Be(t[8])],b=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),x=(t,e,r,i,n)=>b(t,[k(e),xt(r),i??[]],n),Gr=t=>t.isQuickTime?b("ftyp",[O("qt "),m(512),O("qt ")]):t.fragmented?b("ftyp",[O("iso5"),m(512),O("iso5"),O("iso6"),O("mp41")]):b("ftyp",[O("isom"),m(512),O("isom"),t.holdsAvc?O("avc1"):[],O("mp41")]),be=t=>({type:"mdat",largeSize:t}),qr=t=>({type:"free",size:t}),pe=t=>b("moov",void 0,[Xr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Kr(e,t.creationTime)),t.isFragmented?Ii(t.trackDatas):null,ji(t)]),Xr=(t,e)=>{const r=I(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=Ge(a.samples);return o.timestamp+o.duration})),We),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!ue(t)||!ue(r),s=n?ae:m;return x("mvhd",+n,0,[s(t),s(t),m(We),s(r),Q(1),_t(1),Array(10).fill(0),kt(At),Array(24).fill(0),m(i)])},Kr=(t,e)=>{const r=tn(t);return b("trak",void 0,[Yr(t,e),Zr(t,e),r.name!==void 0?b("udta",void 0,[b("name",[...j.encode(r.name)])]):null])},Yr=(t,e)=>{const r=Ge(t.samples),i=I(r?r.timestamp+r.duration:0,We),n=!ue(e)||!ue(i),s=n?ae:m;let a;if(t.type==="video"){const d=t.track.metadata.rotation;a=St(d??0)}else a=At;let o=2;return t.track.metadata.disposition?.default!==!1&&(o|=1),x("tkhd",+n,o,[s(e),s(e),m(t.track.id),m(0),s(i),Array(8).fill(0),y(0),y(t.track.id),_t(t.type==="audio"?1:0),y(0),kt(a),Q(t.type==="video"?t.info.width:0),Q(t.type==="video"?t.info.height:0)])},Zr=(t,e)=>b("mdia",void 0,[Jr(t,e),qe(!0,ei[t.type],ti[t.type]),ri(t)]),Jr=(t,e)=>{const r=Ge(t.samples),i=I(r?r.timestamp+r.duration:0,t.timescale),n=!ue(e)||!ue(i),s=n?ae:m;return x("mdhd",+n,0,[s(e),s(e),m(t.timescale),s(i),y(Ft(t.track.metadata.languageCode??Zt)),y(0)])},ei={video:"vide",audio:"soun",subtitle:"text"},ti={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},qe=(t,e,r,i="\0\0\0\0")=>x("hdlr",0,0,[t?O("mhlr"):m(0),O(e),O(i),m(0),m(0),O(r,!0)]),ri=t=>b("minf",void 0,[oi[t.type](),ai(),ui(t)]),ii=()=>x("vmhd",0,1,[y(0),y(0),y(0),y(0)]),ni=()=>x("smhd",0,0,[y(0),y(0)]),si=()=>x("nmhd",0,0),oi={video:ii,audio:ni,subtitle:si},ai=()=>b("dinf",void 0,[ci()]),ci=()=>x("dref",0,0,[m(1)],[di()]),di=()=>x("url ",0,1),ui=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return b("stbl",void 0,[li(t),xi(t),e?Bi(t):null,e?Pi(t):null,Si(t),Ai(t),ki(t),_i(t)])},li=t=>{let e;if(t.type==="video")e=hi(qi(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const r=It(t.track.source._codec,t.muxer.isQuickTime);p(r),e=wi(r,t)}else t.type==="subtitle"&&(e=Ei(Yi[t.track.source._codec],t));return p(e),x("stsd",0,0,[m(1)],[e])},hi=(t,e)=>b(t,[Array(6).fill(0),y(1),y(0),y(0),Array(12).fill(0),y(e.info.width),y(e.info.height),m(4718592),m(4718592),m(0),y(1),Array(32).fill(0),y(24),vt(65535)],[Xi[e.track.source._codec](e),Xt(e.info.decoderConfig.colorSpace)?fi(e):null]),fi=t=>b("colr",[O("nclx"),y($e[t.info.decoderConfig.colorSpace.primaries]),y(je[t.info.decoderConfig.colorSpace.transfer]),y(De[t.info.decoderConfig.colorSpace.matrix]),k((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),mi=t=>t.info.decoderConfig&&b("avcC",[...q(t.info.decoderConfig.description)]),pi=t=>t.info.decoderConfig&&b("hvcC",[...q(t.info.decoderConfig.description)]),dt=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),n=Number(r[2]),s=Number(r[3]),a=r[4]?Number(r[4]):1,o=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),d=(s<<4)+(a<<1)+o,c=r[5]?Number(r[5]):e.colorSpace?.primaries?$e[e.colorSpace.primaries]:2,u=r[6]?Number(r[6]):e.colorSpace?.transfer?je[e.colorSpace.transfer]:2,h=r[7]?Number(r[7]):e.colorSpace?.matrix?De[e.colorSpace.matrix]:2;return x("vpcC",1,0,[k(i),k(n),k(d),k(c),k(u),k(h),y(0)])},gi=t=>b("av1C",ar(t.info.decoderConfig.codec)),wi=(t,e)=>{let r=0,i,n=16;if(N.includes(e.track.source._codec)){const s=e.track.source._codec,{sampleSize:a}=le(s);n=8*a,n>16&&(r=1)}return r===0?i=[Array(6).fill(0),y(1),y(r),y(0),m(0),y(e.info.numberOfChannels),y(n),y(0),y(0),y(e.info.sampleRate<2**16?e.info.sampleRate:0),y(0)]:i=[Array(6).fill(0),y(1),y(r),y(0),m(0),y(e.info.numberOfChannels),y(Math.min(n,16)),y(0),y(0),y(e.info.sampleRate<2**16?e.info.sampleRate:0),y(0),m(1),m(n/8),m(e.info.numberOfChannels*n/8),m(2)],b(t,i,[Ki(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ie=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 r=[...k(e),...k(21),...xt(0),...m(0),...m(0)];if(t.info.decoderConfig.description){const i=q(t.info.decoderConfig.description);r=[...r,...k(5),...Pe(i.byteLength),...i]}return r=[...y(1),...k(0),...k(4),...Pe(r.length),...r,...k(6),...k(1),...k(2)],r=[...k(3),...Pe(r.length),...r],x("esds",0,0,r)},K=t=>b("wave",void 0,[yi(t),bi(t),b("\0\0\0\0")]),yi=t=>b("frma",[O(It(t.track.source._codec,t.muxer.isQuickTime))]),bi=t=>{const{littleEndian:e}=le(t.track.source._codec);return b("enda",[y(+e)])},Ti=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,n=0,s=0,a=new Uint8Array(0);const o=t.info.decoderConfig?.description;if(o){p(o.byteLength>=18);const d=q(o),c=Rr(d);e=c.outputChannelCount,r=c.preSkip,i=c.inputSampleRate,n=c.outputGain,s=c.channelMappingFamily,c.channelMappingTable&&(a=c.channelMappingTable)}return b("dOps",[k(0),k(e),y(r),m(i),vt(n),k(s),...a])},Ci=t=>{const e=t.info.decoderConfig?.description;p(e);const r=q(e);return x("dfLa",0,0,[...r.subarray(4)])},L=t=>{const{littleEndian:e,sampleSize:r}=le(t.track.source._codec),i=+e;return x("pcmC",0,0,[k(i),k(8*r)])},Ei=(t,e)=>b(t,[Array(6).fill(0),y(1)],[Zi[e.track.source._codec](e)]),vi=t=>b("vttC",[...j.encode(t.info.config.description)]),xi=t=>x("stts",0,0,[m(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[m(e.sampleCount),m(e.sampleDelta)])]),_i=t=>{if(t.samples.every(r=>r.type==="key"))return null;const e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return x("stss",0,0,[m(e.length),e.map(([r])=>m(r+1))])},Si=t=>x("stsc",0,0,[m(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[m(e.firstChunk),m(e.samplesPerChunk),m(1)])]),Ai=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=le(t.track.source._codec);return x("stsz",0,0,[m(e*t.info.numberOfChannels),m(t.samples.reduce((r,i)=>r+I(i.duration,t.timescale),0))])}return x("stsz",0,0,[m(0),m(t.samples.length),t.samples.map(e=>m(e.size))])},ki=t=>t.finalizedChunks.length>0&&V(t.finalizedChunks).offset>=2**32?x("co64",0,0,[m(t.finalizedChunks.length),t.finalizedChunks.map(e=>ae(e.offset))]):x("stco",0,0,[m(t.finalizedChunks.length),t.finalizedChunks.map(e=>m(e.offset))]),Bi=t=>x("ctts",1,0,[m(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[m(e.sampleCount),Y(e.sampleCompositionTimeOffset)])]),Pi=t=>{let e=1/0,r=-1/0,i=1/0,n=-1/0;p(t.compositionTimeOffsetTable.length>0),p(t.samples.length>0);for(let a=0;a<t.compositionTimeOffsetTable.length;a++){const o=t.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),r=Math.max(r,o.sampleCompositionTimeOffset)}for(let a=0;a<t.samples.length;a++){const o=t.samples[a];i=Math.min(i,I(o.timestamp,t.timescale)),n=Math.max(n,I(o.timestamp+o.duration,t.timescale))}const s=Math.max(-e,0);return n>=2**31?null:x("cslg",0,0,[Y(s),Y(e),Y(r),Y(i),Y(n)])},Ii=t=>b("mvex",void 0,t.map(Fi)),Fi=t=>x("trex",0,0,[m(t.track.id),m(1),m(0),m(0),m(0)]),ut=(t,e)=>b("moof",void 0,[Oi(t),...e.map(Mi)]),Oi=t=>x("mfhd",0,0,[m(t)]),Bt=t=>{let e=0,r=0;const i=0,n=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|i<<8|n},Mi=t=>b("traf",void 0,[Ri(t),zi(t),Vi(t)]),Ri=t=>{p(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Bt(r)};return x("tfhd",0,e,[m(t.track.id),m(i.duration),m(i.size),m(i.flags)])},zi=t=>(p(t.currentChunk),x("tfdt",1,0,[ae(I(t.currentChunk.startTimestamp,t.timescale))])),Vi=t=>{p(t.currentChunk);const e=t.currentChunk.samples.map(T=>T.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(T=>T.size),i=t.currentChunk.samples.map(Bt),n=t.currentChunk.samples.map(T=>I(T.timestamp-T.decodeTimestamp,t.timescale)),s=new Set(e),a=new Set(r),o=new Set(i),d=new Set(n),c=o.size===2&&i[0]!==i[1],u=s.size>1,h=a.size>1,l=!c&&o.size>1,f=d.size>1||[...d].some(T=>T!==0);let w=0;return w|=1,w|=4*+c,w|=256*+u,w|=512*+h,w|=1024*+l,w|=2048*+f,x("trun",1,w,[m(t.currentChunk.samples.length),m(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?m(i[0]):[],t.currentChunk.samples.map((T,C)=>[u?m(e[C]):[],h?m(r[C]):[],l?m(i[C]):[],f?Y(n[C]):[]])])},Ni=t=>b("mfra",void 0,[...t.map(Ui),Wi()]),Ui=(t,e)=>x("tfra",1,0,[m(t.track.id),m(63),m(t.finalizedChunks.length),t.finalizedChunks.map(i=>[ae(I(i.samples[0].timestamp,t.timescale)),ae(i.moofOffset),m(e+1),m(1),m(1)])]),Wi=()=>x("mfro",0,0,[m(0)]),Li=()=>b("vtte"),Hi=(t,e,r,i,n)=>b("vttc",void 0,[n!==null?b("vsid",[Y(n)]):null,r!==null?b("iden",[...j.encode(r)]):null,e!==null?b("ctim",[...j.encode(Qr(e))]):null,i!==null?b("sttg",[...j.encode(i)]):null,b("payl",[...j.encode(t)])]),$i=t=>b("vtta",[...j.encode(t)]),ji=t=>{const e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){const n=Qi(i);n&&e.push(n)}else if(r==="mdta"){const n=Gi(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&Di(e,t.output._metadataTags);return e.length===0?null:b("udta",void 0,e)},Di=(t,e)=>{for(const{key:r,value:i}of gt(e))switch(r){case"title":t.push(H("©nam",i));break;case"description":t.push(H("©des",i));break;case"artist":t.push(H("©ART",i));break;case"album":t.push(H("©alb",i));break;case"albumArtist":t.push(H("albr",i));break;case"genre":t.push(H("©gen",i));break;case"date":t.push(H("©day",i.toISOString().slice(0,10)));break;case"comment":t.push(H("©cmt",i));break;case"lyrics":t.push(H("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ve(r)}if(e.raw)for(const r in e.raw){const i=e.raw[r];i==null||r.length!==4||t.some(n=>n.type===r)||(typeof i=="string"?t.push(H(r,i)):i instanceof Uint8Array&&t.push(b(r,Array.from(i))))}},H=(t,e)=>{const r=j.encode(e);return b(t,[y(r.length),y(Ft("und")),Array.from(r)])},lt={"image/jpeg":13,"image/png":14,"image/bmp":27},Pt=(t,e)=>{const r=[];for(const{key:i,value:n}of gt(t))switch(i){case"title":r.push({key:e?"title":"©nam",value:z(n)});break;case"description":r.push({key:e?"description":"©des",value:z(n)});break;case"artist":r.push({key:e?"artist":"©ART",value:z(n)});break;case"album":r.push({key:e?"album":"©alb",value:z(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:z(n)});break;case"comment":r.push({key:e?"comment":"©cmt",value:z(n)});break;case"genre":r.push({key:e?"genre":"©gen",value:z(n)});break;case"lyrics":r.push({key:e?"lyrics":"©lyr",value:z(n)});break;case"date":r.push({key:e?"date":"©day",value:z(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&r.push({key:"covr",value:b("data",[m(lt[s.mimeType]??0),m(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();r.push({key:"track",value:z(s)})}else r.push({key:"trkn",value:b("data",[m(0),m(0),y(0),y(n),y(t.tracksTotal??0),y(0)])});break;case"discNumber":e||r.push({key:"disc",value:b("data",[m(0),m(0),y(0),y(n),y(t.discsTotal??0),y(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ve(i)}if(t.raw)for(const i in t.raw){const n=t.raw[i];n==null||!e&&i.length!==4||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:z(n)}):n instanceof Uint8Array?r.push({key:i,value:b("data",[m(0),m(0),Array.from(n)])}):n instanceof wt&&r.push({key:i,value:b("data",[m(lt[n.mimeType]??0),m(0),Array.from(n.data)])}))}return r},Qi=t=>{const e=Pt(t,!1);return e.length===0?null:x("meta",0,0,void 0,[qe(!1,"mdir","","appl"),b("ilst",void 0,e.map(r=>b(r.key,void 0,[r.value])))])},Gi=t=>{const e=Pt(t,!0);return e.length===0?null:b("meta",void 0,[qe(!1,"mdta",""),x("keys",0,0,[m(e.length)],e.map(r=>b("mdta",[...j.encode(r.key)]))),b("ilst",void 0,e.map((r,i)=>{const n=String.fromCharCode(...m(i+1));return b(n,void 0,[r.value])}))])},z=t=>b("data",[m(1),m(0),...j.encode(t)]),qi=(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"}},Xi={avc:mi,hevc:pi,vp8:dt,vp9:dt,av1:gi},It=(t,e)=>{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"}if(e)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"}},Ki=(t,e)=>{switch(t){case"aac":return Ie;case"mp3":return Ie;case"opus":return Ti;case"vorbis":return Ie;case"flac":return Ci}if(e)switch(t){case"pcm-s24":return K;case"pcm-s24be":return K;case"pcm-s32":return K;case"pcm-s32be":return K;case"pcm-f32":return K;case"pcm-f32be":return K;case"pcm-f64":return K;case"pcm-f64be":return K}else switch(t){case"pcm-s16":return L;case"pcm-s16be":return L;case"pcm-s24":return L;case"pcm-s24be":return L;case"pcm-s32":return L;case"pcm-s32be":return L;case"pcm-f32":return L;case"pcm-f32be":return L;case"pcm-f64":return L;case"pcm-f64be":return L}return null},Yi={webvtt:"wvtt"},Zi={webvtt:vi},Ft=t=>{p(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};class Ji{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}const i=r+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+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 r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}}const Fe=2**16,Oe=2**32;class Ot extends Ji{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Fe,{maxByteLength:Oe})}catch{this.buffer=new ArrayBuffer(Fe),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Fe);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let r=this.buffer.byteLength;for(;r<e;)r*=2;if(r!==this.buffer.byteLength){if(r>Oe)throw new Error(`ArrayBuffer exceeded maximum size of ${Oe} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{const i=new ArrayBuffer(r),n=new Uint8Array(i);n.set(this.bytes,0),this.buffer=i,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,r){return this.bytes.slice(e,r)}}class Mt{constructor(){this._output=null,this.onwrite=null}}class Rt extends Mt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Ot(this)}}const We=1e3,en=2082844800,tn=t=>{const e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},I=(t,e,r=!0)=>{const i=t*e;return r?Math.round(i):i};class rn extends Er{constructor(e,r){super(e),this.auxTarget=new Rt,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ct(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Kt(),this.creationTime=Math.floor(Date.now()/1e3)+en,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=r,this.writer=e._writer,this.boxWriter=new ct(this.writer),this.isQuickTime=r instanceof Ut;const i=this.writer instanceof Ot?"in-memory":!1;this.fastStart=r._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),r=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Gr({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=be(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Dr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;yr(i),p(i),p(i.decoderConfig);const s={...i.decoderConfig};p(s.codedWidth!==void 0),p(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){const c=xr(r.data);if(!c)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=_r(c),a=!0}else if(e.source._codec==="hevc"&&!s.description){const c=Ar(r.data);if(!c)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=Mr(c),a=!0}const o=tr(1/(e.metadata.frameRate??57600),1e6).denominator,d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(d),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;Tr(r),p(r),p(r.decoderConfig);const n={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&N.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(e,r){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;Cr(r),p(r),p(r.config);const n={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,r,i);let a=r.data;if(s.info.requiresAnnexBTransformation){const c=vr(a);if(!c)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.");a=c}const o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),d=this.createSampleForTrack(s,a,o,r.duration,r.type);await this.registerSample(s,d)}finally{n()}}async addEncodedAudioPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),o=this.createSampleForTrack(s,r.data,a,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,a),await this.registerSample(s,o)}finally{n()}}async maybePadWithSilence(e,r){const i=V(e.samples),n=i?i.timestamp+i.duration:0,s=r-n,a=I(s,e.timescale);if(a>0){const{sampleSize:o,silentValue:d}=le(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(o*c).fill(d),h=this.createSampleForTrack(e,new Uint8Array(u.buffer),n,s,"key");await this.registerSample(e,h)}}async addSubtitleCue(e,r,i){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)p(c.timestamp<=r),p(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,u)=>c-u),s=n[0],a=n[1]??s;if(r<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=Li();this.auxBoxWriter.writeBox(c);const u=this.auxWriter.getSlice(0,this.auxWriter.getPos()),h=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,h),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const u=e.cueQueue[c];if(u.timestamp>=a)break;at.lastIndex=0;const h=at.test(u.text),l=u.timestamp+u.duration;let f=e.cueToSourceId.get(u);if(f===void 0&&a<l&&(f=e.nextSourceId++,e.cueToSourceId.set(u,f)),u.notes){const T=$i(u.notes);this.auxBoxWriter.writeBox(T)}const w=Hi(u.text,h?s:null,u.identifier??null,u.settings??null,f??null);this.auxBoxWriter.writeBox(w),l===a&&e.cueQueue.splice(c--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=a}}createSampleForTrack(e,r,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:I(n,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const a=e.timestampProcessingQueue[s],o=I(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const s=V(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(s.decodeTimestamp=0);const a=I(s.timestamp-s.decodeTimestamp,e.timescale),o=I(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const d=I(s.decodeTimestamp,e.timescale,!1),c=Math.round(d-e.lastTimescaleUnits);if(p(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let u=V(e.timeToSampleTable);if(p(u),u.sampleCount===1){u.sampleDelta=c;const l=e.timeToSampleTable[e.timeToSampleTable.length-2];l&&l.sampleDelta===c&&(l.sampleCount++,e.timeToSampleTable.pop(),u=l)}else u.sampleDelta!==c&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:c}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const h=V(e.compositionTimeOffsetTable);p(h),h.sampleCompositionTimeOffset===a?h.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=I(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(r.type==="key");const n=I(r.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),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 i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);const n=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(a=>{if(e===a)return r.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),p(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(p(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,n)=>i+I(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||V(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;const n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(e=!0){p(this.isFragmented);const r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const f=pe(this);if(this.boxWriter.writeBox(f),this.format._options.onMoov){const{data:w,start:T}=this.writer.stopTrackingWrites();this.format._options.onMoov(w,T)}}const i=this.trackDatas.filter(f=>f.currentChunk),n=ut(r,i),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+ke,d=1/0;for(const f of i){f.currentChunk.offset=o,f.currentChunk.moofOffset=s;for(const w of f.currentChunk.samples)o+=w.size;d=Math.min(d,f.currentChunk.startTimestamp)}const c=o-a,u=c>=2**32;if(u)for(const f of i)f.currentChunk.offset+=ot-ke;this.format._options.onMoof&&this.writer.startTrackingWrites();const h=ut(r,i);if(this.boxWriter.writeBox(h),this.format._options.onMoof){const{data:f,start:w}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,w,d)}p(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const l=be(u);l.size=c,this.boxWriter.writeBox(l),this.writer.seek(a+(u?ot:ke));for(const f of i)for(const w of f.currentChunk.samples)this.writer.write(w.data),w.data=null;if(this.format._options.onMdat){const{data:f,start:w}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,w)}for(const f of i)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){const i=pe(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=be(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(const r of this.trackDatas){const i=r.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const r=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(n=>n.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(const r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){this.mdat=be(!1);let r;for(let n=0;n<2;n++){const s=pe(this),a=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+r;for(const d of this.finalizedChunks){d.offset=o;for(const{data:c}of d.samples)p(c),o+=c.byteLength,r+=c.byteLength}if(o<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=pe(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,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.format._options.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){const r=this.writer.getPos(),i=Ni(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{p(this.mdat);const r=this.boxWriter.offsets.get(this.mdat);p(r!==void 0);const i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}const n=pe(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(qr(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}class zt{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ee.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>oe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ce.includes(e))}_codecUnsupportedHint(e){return""}}class Vt extends zt{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&&(!Number.isFinite(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:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new rn(e,this)}}class Nt extends Vt{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ee,...yt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ce]}_codecUnsupportedHint(e){return new Ut().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Ut extends Vt{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ee,...oe]}_codecUnsupportedHint(e){return new Nt().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const nn=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!ee.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${ee.join(", ")}.`);if(!(t.bitrate instanceof ce)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate 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.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, 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.");Wt(t.codec,t)},Wt=(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'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))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&&Ct(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.")},Le=t=>{const e=t.bitrate instanceof ce?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??or(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...lr(t.codec)}},sn=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!oe.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${oe.join(", ")}.`);if(t.bitrate===void 0&&(!N.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof ce)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, 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.");Lt(t.codec,t)},Lt=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Ct(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},He=t=>{const e=t.bitrate instanceof ce?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??cr(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...hr(t.codec)}};class ce{constructor(e){this._factor=e}_toVideoBitrate(e,r,i){const n=r*i,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,d=Math.pow(n/a,.95),h=o*d*s[e]*this._factor;return Math.ceil(h/1e3)*1e3}_toAudioBitrate(e){if(N.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a)),Math.round(n/1e3)*1e3}}const Ht=new ce(2),on=async(t,e={})=>{const{width:r=1280,height:i=720,bitrate:n=1e6,...s}=e;if(!ee.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(n instanceof ce)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Wt(t,s);let a=null;return Ne.length>0&&(a??=Le({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s}),Ne.some(c=>c.supports(t,a)))?!0:typeof VideoEncoder>"u"||(r%2===1||i%2===1)&&(t==="avc"||t==="hevc")||(a??=Le({codec:t,width:r,height:i,bitrate:n,framerate:void 0,...s,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(a)).supported)?!1:Te()?new Promise(async c=>{try{const u=new VideoEncoder({output:()=>{},error:()=>c(!1)});u.configure(a);const h=new Uint8Array(r*i*4),l=new VideoFrame(h,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});u.encode(l),l.close(),await u.flush(),c(!0)}catch{c(!1)}}):!0},an=async(t,e={})=>{const{numberOfChannels:r=2,sampleRate:i=48e3,bitrate:n=128e3,...s}=e;if(!oe.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(n instanceof ce)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");Lt(t,s);let a=null;return Ue.length>0&&(a??=He({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s}),Ue.some(d=>d.supports(t,a)))||N.includes(t)?!0:typeof AudioEncoder>"u"?!1:(a??=He({codec:t,numberOfChannels:r,sampleRate:i,bitrate:n,...s}),(await AudioEncoder.isConfigSupported(a)).supported===!0)},cn=async(t,e)=>{for(const r of t)if(await on(r,e))return r;return null},dn=async(t,e)=>{for(const r of t)if(await an(r,e))return r;return null};class Xe{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_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?this._closingPromise:this._flushAndClose(e)}}class $t extends Xe{constructor(e){if(super(),this._connectedTrack=null,!ee.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ee.join(", ")}.`);this._codec=e}}class un{constructor(e,r){this.source=e,this.encodingConfig=r,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new pt,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(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 'strict' in the encoding options.`);{let d=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),d=!0);const c=this.resizeCanvas.getContext("2d",{alpha:Te()});p(c),d||(Te()?(c.fillStyle="black",c.fillRect(0,0,this.codedWidth,this.codedHeight)):c.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(c,{fit:o}),r&&e.close(),e=new ie(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/n),a={...i,keyFrame:i?.keyFrame||n===0||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(c=>this.error??=c).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await d}else{p(this.encoder);const o=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(o,a),o.close();else if(!!o.format&&!o.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close();else{const c=o.displayWidth,u=o.displayHeight;if(!this.splitter)try{this.splitter=new ln(c,u)}catch(h){console.error("Due to an error, only color data will be encoded.",h),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(o,a),o.close()}if(this.splitter){const h=this.splitter.extractColor(o),l=this.splitter.extractAlpha(o);this.alphaFrameQueue.push(l),this.encoder.encode(h,a),h.close(),o.close()}}r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(d=>this.encoder.addEventListener("dequeue",d,{once:!0}))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const i=Le({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const n=Ne.find(s=>s.supports(this.encodingConfig.codec,i));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(s,a)=>{if(!(s instanceof J))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,a).catch(o=>{this.error??=o,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.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.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const o=[],d=[];let c=0,u=0;const h=(l,f,w)=>{const T={};if(f){const E=new Uint8Array(f.byteLength);f.copyTo(E),T.alpha=E}const C=J.fromEncodedChunk(l,T);this.encodingConfig.onEncodedPacket?.(C,w),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,C,w).catch(E=>{this.error??=E,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(l,f)=>{if(!this.alphaEncoder){h(l,null,f);return}const w=this.alphaFrameQueue.shift();p(w!==void 0),w?(this.alphaEncoder.encode(w,{keyFrame:l.type==="key"}),u++,w.close(),o.push({chunk:l,meta:f})):u===0?h(l,null,f):(d.push(c+u),o.push({chunk:l,meta:f}))},error:l=>{l.stack=r.stack,this.error??=l}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(l,f)=>{u--;const w=o.shift();for(p(w!==void 0),h(w.chunk,l,w.meta),c++;d.length>0&&d[0]===c;){d.shift();const T=o.shift();p(T!==void 0),h(T.chunk,null,T.meta)}},error:l=>{l.stack=r.stack,this.error??=l}}),this.alphaEncoder.configure(i))}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class ln{constructor(e,r){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,r):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=r);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2
2
|
in vec2 a_position;
|
|
3
3
|
in vec2 a_texCoord;
|
|
4
4
|
out vec2 v_texCoord;
|