mediabunny 1.3.0 → 1.3.2
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.
- package/README.md +2 -0
- package/dist/bundles/mediabunny.cjs +22 -3
- package/dist/bundles/mediabunny.min.cjs +4 -4
- package/dist/bundles/mediabunny.min.mjs +4 -4
- package/dist/bundles/mediabunny.mjs +22 -3
- package/dist/modules/misc.js +1 -1
- package/dist/modules/source.d.ts.map +1 -1
- package/dist/modules/source.js +23 -2
- package/package.json +2 -2
- package/src/misc.ts +3 -3
- package/src/source.ts +27 -2
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
6
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
7
|
*/
|
|
8
|
-
function m(i){if(!i)throw new Error("Assertion failed.")}var Ae=i=>{let e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},V=i=>i&&i[i.length-1],De=i=>i>=0&&i<2**32,K=class i{constructor(e){this.bytes=e;this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(this.pos&7),a=(t&1<<r)>>r;return this.pos++,a}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new i(this.bytes);return e.pos=this.pos,e}},P=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},je=i=>{let e=P(i);return(e&1)===0?-(e>>1):e+1>>1},hn=(i,e,t,r)=>{for(let a=e;a<t;a++){let n=Math.floor(a/8),s=i[n],o=7-(a&7);s&=~(1<<o),s|=(r&1<<t-a-1)>>t-a-1<<o,i[n]=s}},L=i=>i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),Y=i=>i instanceof DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),ue=new TextEncoder,ui=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),we={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},jt=ui(we),Te={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},Gt=ui(Te),ye={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Xt=ui(ye),Yt=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,Ge=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),ne=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(a=>{e=a}),r=this.currentPromise;return this.currentPromise=t,await r,e}},li=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),mi=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),W=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+a>>1,o=t(i[s]);o===e?(n=s,a=s-1):o<e?r=s+1:a=s-1}return n},F=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+(a-r+1)/2|0;t(i[s])<=e?(n=s,r=s+1):a=s-1}return n},z=()=>{let i,e;return{promise:new Promise((r,a)=>{i=r,e=a}),resolve:i,reject:e}},gn=(i,e)=>{let t=i.indexOf(e);t!==-1&&i.splice(t,1)},fi=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},Zt=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},bn=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},kn=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},Re=i=>{throw new Error(`Unexpected value: ${i}`)},pi=(i,e,t)=>{let r=i.getUint8(e),a=i.getUint8(e+1),n=i.getUint8(e+2);return t?r|a<<8|n<<16:r<<16|a<<8|n},wn=(i,e,t)=>pi(i,e,t)<<8>>8,hi=(i,e,t,r)=>{t=t>>>0,t=t&16777215,r?(i.setUint8(e,t&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t>>>16&255)):(i.setUint8(e,t>>>16&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t&255))},Tn=(i,e,t,r)=>{t=$(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),hi(i,e,t,r)},yn=(i,e,t,r)=>{r?(i.setUint32(e+0,t,!0),i.setInt32(e+4,Math.floor(t/2**32),!0)):(i.setInt32(e+0,Math.floor(t/2**32),!0),i.setUint32(e+4,t,!0))},wt=(i,e)=>({async next(){let t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),$=(i,e,t)=>Math.max(e,Math.min(t,i)),Z="und",Xe=(i,e)=>{let t=10**e;return Math.round(i*t)/t},Tt=(i,e)=>Math.round(i/e)*e,Sn=i=>{let e=0;for(;i;)e++,i>>=1;return e},Oa=/^[a-z]{3}$/,Ye=i=>Oa.test(i),me=1e6*(1+Number.EPSILON),Jt=(i,e)=>{let t={...i};for(let r in e)typeof i[r]=="object"&&i[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=Jt(i[r],e[r]):t[r]=e[r];return t},gi=async(i,e,t)=>{let r=0;for(;;)try{return await fetch(i,e)}catch(a){console.error("Retrying failed fetch. Error:",a),r++;let n=t(r);if(n===null)throw a;if(!Number.isFinite(n)||n<0)throw new TypeError("Retry delay must be a non-negative finite number.");n>0&&await new Promise(s=>setTimeout(s,1e3*n))}},Cn=(i,e)=>{let t=i<0?-1:1;i=Math.abs(i);let r=0,a=1,n=1,s=0,o=i;for(;;){let c=Math.floor(o),u=c*n+r,d=c*s+a;if(d>e)return{numerator:t*n,denominator:s};if(r=n,a=s,n=u,s=d,o=1/(o-c),!isFinite(o))break}return{numerator:t*n,denominator:s}},_e=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}};var er=class{static supports(e,t){return!1}},tr=class{static supports(e,t){return!1}},rr=class{static supports(e,t){return!1}},ir=class{static supports(e,t){return!1}},yt=[],St=[],Ze=[],Je=[],Ma=i=>{if(i.prototype instanceof er)yt.push(i);else if(i.prototype instanceof tr)St.push(i);else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},Ba=i=>{if(i.prototype instanceof rr)Ze.push(i);else if(i.prototype instanceof ir)Je.push(i);else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var q=["avc","hevc","vp9","av1","vp8"],U=["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"],Ce=["aac","opus","mp3","vorbis","flac"],j=[...Ce,...U],ae=["webvtt"],xn=[{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}],vn=[{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}],Se=[{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}],Pn=[{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}],En=".01.01.01.01.00",In=".0.110.01.01.01.0",nr=(i,e,t,r)=>{if(i==="avc"){let n=Math.ceil(e/16)*Math.ceil(t/16),s=xn.find(l=>n<=l.maxMacroblocks&&r<=l.maxBitrate)??V(xn),o=s?s.level:0,c="64".padStart(2,"0"),u="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${u}${d}`}else if(i==="hevc"){let a="",s="6",o=e*t,c=vn.find(d=>o<=d.maxPictureSize&&r<=d.maxBitrate)??V(vn);return`hev1.${a}1.${s}.${c.tier}${c.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",n=e*t,s=Se.find(c=>n<=c.maxPictureSize&&r<=c.maxBitrate)??V(Se);return`vp09.${a}.${s.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let n=e*t,s=Pn.find(u=>n<=u.maxPictureSize&&r<=u.maxBitrate)??V(Pn);return`av01.0.${s.level.toString().padStart(2,"0")}${s.tier}.08`}}throw new TypeError(`Unhandled codec '${i}'.`)},_n=i=>{let e=i.split("."),t=Number(e[1]),r=Number(e[2]),a=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,a,4,1,n]},cr=i=>{let e=i.split("."),a=(1<<7)+1,n=Number(e[1]),s=e[2],o=Number(s.slice(0,-1)),c=(n<<5)+o,u=s.slice(-1)==="H"?1:0,l=Number(e[3])===8?0:1,p=0,h=e[4]?Number(e[4]):0,f=e[5]?Number(e[5][0]):1,b=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,k=(u<<7)+(l<<6)+(p<<5)+(h<<4)+(f<<3)+(b<<2)+g;return[a,c,k,0]},dr=i=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:s,av1CodecInfo:o}=i;if(e==="avc"){if(a){let c=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc1.${li(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${li(t.subarray(1,4))}`}else if(e==="hevc"){let c,u,d,l,p,h;if(n)c=n.generalProfileSpace,u=n.generalProfileIdc,d=mi(n.generalProfileCompatibilityFlags),l=n.generalTierFlag,p=n.generalLevelIdc,h=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let b=Y(t),g=b.getUint8(1);c=g>>6&3,u=g&31,d=mi(b.getUint32(2)),l=g>>5&1,p=b.getUint8(12),h=[];for(let k=0;k<6;k++)h.push(b.getUint8(6+k))}let f="hev1.";for(f+=["","A","B","C"][c]+u,f+=".",f+=d.toString(16).toUpperCase(),f+=".",f+=l===0?"L":"H",f+=p;h.length>0&&h[h.length-1]===0;)h.pop();return h.length>0&&(f+=".",f+=h.map(b=>b.toString(16).toUpperCase()).join(".")),f}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let k=i.width*i.height,y=V(Se).level;for(let C of Se)if(k<=C.maxPictureSize){y=C.level;break}return`vp09.00.${y.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),u=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),l=s.chromaSubsampling.toString().padStart(2,"0"),p=s.colourPrimaries.toString().padStart(2,"0"),h=s.transferCharacteristics.toString().padStart(2,"0"),f=s.matrixCoefficients.toString().padStart(2,"0"),b=s.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${u}.${d}.${l}`;return g+=`.${p}.${h}.${f}.${b}`,g.endsWith(En)&&(g=g.slice(0,-En.length)),g}else if(e==="av1"){if(!o){let C=i.width*i.height,S=V(Se).level;for(let w of Se)if(C<=w.maxPictureSize){S=w.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}let c=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",l=o.bitDepth.toString().padStart(2,"0"),p=o.monochrome?"1":"0",h=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),f=r?.primaries?we[r.primaries]:1,b=r?.transfer?Te[r.transfer]:1,g=r?.matrix?ye[r.matrix]:1,k=r?.fullRange?1:0,y=`av01.${c}.${u}${d}.${l}`;return y+=`.${p}.${h.toString().padStart(3,"0")}`,y+=`.${f.toString().padStart(2,"0")}`,y+=`.${b.toString().padStart(2,"0")}`,y+=`.${g.toString().padStart(2,"0")}`,y+=`.${k}`,y.endsWith(In)&&(y=y.slice(0,-In.length)),y}}throw new TypeError(`Unhandled codec '${e}'.`)},ar=(i,e,t)=>{if(i==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(U.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},ur=i=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${bi(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&U.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},bi=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new K(i),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),a=null;if(r===15)a=e.readBits(24);else{let o=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r<o.length&&(a=o[r])}let n=e.readBits(4),s=null;return n>=1&&n<=7&&(s={1:1,2:2,3:3,4:4,5:5,6:6,7:8}[n]),{objectType:t,frequencyIndex:r,sampleRate:a,channelConfiguration:n,numberOfChannels:s}},et=48e3,An=/^pcm-([usf])(\d+)+(be)?$/,G=i=>{if(m(U.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=An.exec(i);m(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,a=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:a,silentValue:n}},ki=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":i.startsWith("mp4a.40")||i==="mp4a.67"?"aac":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp3":i==="opus"?"opus":i==="vorbis"?"vorbis":i==="flac"?"flac":i==="ulaw"?"ulaw":i==="alaw"?"alaw":An.test(i)?i:i==="webvtt"?"webvtt":null,sr=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},or=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},H=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){let a=t*r,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},s=1920*1080,o=3e6,c=Math.pow(a/s,.95),l=o*c*n[e]*this._factor;return Math.ceil(l/1e3)*1e3}_toAudioBitrate(e){if(U.includes(e)||e==="flac")return;let r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!r)throw new Error(`Unhandled codec: ${e}`);let a=r*this._factor;return e==="aac"?a=[96e3,128e3,16e4,192e3].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s):e==="opus"||e==="vorbis"?a=Math.max(6e3,a):e==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s)),Math.round(a/1e3)*1e3}},Da=new H(.3),Va=new H(.6),Ua=new H(1),lr=new H(2),za=new H(4),Na=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Wa=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,La=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ha=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Ka=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,mr=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Na.some(e=>i.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(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.description!==void 0&&!Ge(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(we);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let r=Object.keys(Te);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);let a=Object.keys(ye);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.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(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!Wa.test(i.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(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!La.test(i.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(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!Ha.test(i.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(i.decoderConfig.codec.startsWith("av01")&&!Ka.test(i.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/.')},Qa=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Fe=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Qa.some(e=>i.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(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Ge(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.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(!i.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(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.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(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.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(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.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(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.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((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!U.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${U.join(", ")}).`)},fr=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},$a=i=>{if(q.includes(i))return pr(i);if(j.includes(i))return hr(i);if(ae.includes(i))return gr(i);throw new TypeError(`Unknown codec '${i}'.`)},pr=async(i,{width:e=1280,height:t=720,bitrate:r=1e6}={})=>{if(!q.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("height must be a positive integer.");if(!(r instanceof H)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");let a=r instanceof H?r._toVideoBitrate(i,e,t):r;if(Ze.length>0){let s={codec:nr(i,e,t,a),width:e,height:t,bitrate:a,...sr(i)};if(Ze.some(o=>o.supports(i,s)))return!0}return typeof VideoEncoder>"u"?!1:(await VideoEncoder.isConfigSupported({codec:nr(i,e,t,a),width:e,height:t,bitrate:a,...sr(i)})).supported===!0},hr=async(i,{numberOfChannels:e=2,sampleRate:t=48e3,bitrate:r=128e3}={})=>{if(!j.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(r instanceof H)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");let a=r instanceof H?r._toAudioBitrate(i):r;if(Je.length>0){let s={codec:ar(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...or(i)};if(Je.some(o=>o.supports(i,s)))return!0}return U.includes(i)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported({codec:ar(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...or(i)})).supported===!0},gr=async i=>!!ae.includes(i),qa=async()=>{let[i,e,t]=await Promise.all([Rn(),Ct(),Fn()]);return[...i,...e,...t]},Rn=async(i=q,e)=>{let t=await Promise.all(i.map(r=>pr(r,e)));return i.filter((r,a)=>t[a])},Ct=async(i=j,e)=>{let t=await Promise.all(i.map(r=>hr(r,e)));return i.filter((r,a)=>t[a])},Fn=async(i=ae)=>{let e=await Promise.all(i.map(gr));return i.filter((t,r)=>e[r])},wi=async(i,e)=>{for(let t of i)if(await pr(t,e))return t;return null},ja=async(i,e)=>{for(let t of i)if(await hr(t,e))return t;return null},Ga=async i=>{for(let e of i)if(await gr(e))return e;return null};var xt=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Xa=/^WEBVTT(.|\n)*?\n{2}/,tt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,br=class{constructor(e){this.preambleText=null;this.preambleEmitted=!1;this.options=e}parse(e){e=e.replaceAll(`\r
|
|
8
|
+
function m(i){if(!i)throw new Error("Assertion failed.")}var Ae=i=>{let e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},V=i=>i&&i[i.length-1],De=i=>i>=0&&i<2**32,K=class i{constructor(e){this.bytes=e;this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(this.pos&7),a=(t&1<<r)>>r;return this.pos++,a}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new i(this.bytes);return e.pos=this.pos,e}},P=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},je=i=>{let e=P(i);return(e&1)===0?-(e>>1):e+1>>1},hn=(i,e,t,r)=>{for(let a=e;a<t;a++){let n=Math.floor(a/8),s=i[n],o=7-(a&7);s&=~(1<<o),s|=(r&1<<t-a-1)>>t-a-1<<o,i[n]=s}},L=i=>i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),Y=i=>i instanceof DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),ue=new TextEncoder,li=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),we={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Gt=li(we),Te={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},Xt=li(Te),ye={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Yt=li(ye),Zt=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,Ge=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),ne=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(a=>{e=a}),r=this.currentPromise;return this.currentPromise=t,await r,e}},mi=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),fi=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),W=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+a>>1,o=t(i[s]);o===e?(n=s,a=s-1):o<e?r=s+1:a=s-1}return n},F=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+(a-r+1)/2|0;t(i[s])<=e?(n=s,r=s+1):a=s-1}return n},z=()=>{let i,e;return{promise:new Promise((r,a)=>{i=r,e=a}),resolve:i,reject:e}},gn=(i,e)=>{let t=i.indexOf(e);t!==-1&&i.splice(t,1)},pi=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},Jt=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},bn=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},kn=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},Re=i=>{throw new Error(`Unexpected value: ${i}`)},hi=(i,e,t)=>{let r=i.getUint8(e),a=i.getUint8(e+1),n=i.getUint8(e+2);return t?r|a<<8|n<<16:r<<16|a<<8|n},wn=(i,e,t)=>hi(i,e,t)<<8>>8,gi=(i,e,t,r)=>{t=t>>>0,t=t&16777215,r?(i.setUint8(e,t&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t>>>16&255)):(i.setUint8(e,t>>>16&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t&255))},Tn=(i,e,t,r)=>{t=$(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),gi(i,e,t,r)},yn=(i,e,t,r)=>{r?(i.setUint32(e+0,t,!0),i.setInt32(e+4,Math.floor(t/2**32),!0)):(i.setInt32(e+0,Math.floor(t/2**32),!0),i.setUint32(e+4,t,!0))},wt=(i,e)=>({async next(){let t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),$=(i,e,t)=>Math.max(e,Math.min(t,i)),Z="und",Xe=(i,e)=>{let t=10**e;return Math.round(i*t)/t},Tt=(i,e)=>Math.round(i/e)*e,Sn=i=>{let e=0;for(;i;)e++,i>>=1;return e},Oa=/^[a-z]{3}$/,Ye=i=>Oa.test(i),me=1e6*(1+Number.EPSILON),yt=(i,e)=>{let t={...i};for(let r in e)typeof i[r]=="object"&&i[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=yt(i[r],e[r]):t[r]=e[r];return t},er=async(i,e,t)=>{let r=0;for(;;)try{return await fetch(i,e)}catch(a){r++;let n=t(r);if(n===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(n)||n<0)throw new TypeError("Retry delay must be a non-negative finite number.");n>0&&await new Promise(s=>setTimeout(s,1e3*n))}},Cn=(i,e)=>{let t=i<0?-1:1;i=Math.abs(i);let r=0,a=1,n=1,s=0,o=i;for(;;){let c=Math.floor(o),u=c*n+r,d=c*s+a;if(d>e)return{numerator:t*n,denominator:s};if(r=n,a=s,n=u,s=d,o=1/(o-c),!isFinite(o))break}return{numerator:t*n,denominator:s}},_e=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}};var tr=class{static supports(e,t){return!1}},rr=class{static supports(e,t){return!1}},ir=class{static supports(e,t){return!1}},nr=class{static supports(e,t){return!1}},St=[],Ct=[],Ze=[],Je=[],Ma=i=>{if(i.prototype instanceof tr)St.push(i);else if(i.prototype instanceof rr)Ct.push(i);else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},Ba=i=>{if(i.prototype instanceof ir)Ze.push(i);else if(i.prototype instanceof nr)Je.push(i);else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var q=["avc","hevc","vp9","av1","vp8"],U=["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"],Ce=["aac","opus","mp3","vorbis","flac"],j=[...Ce,...U],ae=["webvtt"],xn=[{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}],vn=[{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}],Se=[{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}],Pn=[{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}],En=".01.01.01.01.00",In=".0.110.01.01.01.0",ar=(i,e,t,r)=>{if(i==="avc"){let n=Math.ceil(e/16)*Math.ceil(t/16),s=xn.find(l=>n<=l.maxMacroblocks&&r<=l.maxBitrate)??V(xn),o=s?s.level:0,c="64".padStart(2,"0"),u="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${u}${d}`}else if(i==="hevc"){let a="",s="6",o=e*t,c=vn.find(d=>o<=d.maxPictureSize&&r<=d.maxBitrate)??V(vn);return`hev1.${a}1.${s}.${c.tier}${c.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",n=e*t,s=Se.find(c=>n<=c.maxPictureSize&&r<=c.maxBitrate)??V(Se);return`vp09.${a}.${s.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let n=e*t,s=Pn.find(u=>n<=u.maxPictureSize&&r<=u.maxBitrate)??V(Pn);return`av01.0.${s.level.toString().padStart(2,"0")}${s.tier}.08`}}throw new TypeError(`Unhandled codec '${i}'.`)},_n=i=>{let e=i.split("."),t=Number(e[1]),r=Number(e[2]),a=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,a,4,1,n]},dr=i=>{let e=i.split("."),a=(1<<7)+1,n=Number(e[1]),s=e[2],o=Number(s.slice(0,-1)),c=(n<<5)+o,u=s.slice(-1)==="H"?1:0,l=Number(e[3])===8?0:1,p=0,h=e[4]?Number(e[4]):0,f=e[5]?Number(e[5][0]):1,b=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,k=(u<<7)+(l<<6)+(p<<5)+(h<<4)+(f<<3)+(b<<2)+g;return[a,c,k,0]},ur=i=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:s,av1CodecInfo:o}=i;if(e==="avc"){if(a){let c=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc1.${mi(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${mi(t.subarray(1,4))}`}else if(e==="hevc"){let c,u,d,l,p,h;if(n)c=n.generalProfileSpace,u=n.generalProfileIdc,d=fi(n.generalProfileCompatibilityFlags),l=n.generalTierFlag,p=n.generalLevelIdc,h=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let b=Y(t),g=b.getUint8(1);c=g>>6&3,u=g&31,d=fi(b.getUint32(2)),l=g>>5&1,p=b.getUint8(12),h=[];for(let k=0;k<6;k++)h.push(b.getUint8(6+k))}let f="hev1.";for(f+=["","A","B","C"][c]+u,f+=".",f+=d.toString(16).toUpperCase(),f+=".",f+=l===0?"L":"H",f+=p;h.length>0&&h[h.length-1]===0;)h.pop();return h.length>0&&(f+=".",f+=h.map(b=>b.toString(16).toUpperCase()).join(".")),f}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let k=i.width*i.height,y=V(Se).level;for(let C of Se)if(k<=C.maxPictureSize){y=C.level;break}return`vp09.00.${y.toString().padStart(2,"0")}.08`}let c=s.profile.toString().padStart(2,"0"),u=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),l=s.chromaSubsampling.toString().padStart(2,"0"),p=s.colourPrimaries.toString().padStart(2,"0"),h=s.transferCharacteristics.toString().padStart(2,"0"),f=s.matrixCoefficients.toString().padStart(2,"0"),b=s.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${u}.${d}.${l}`;return g+=`.${p}.${h}.${f}.${b}`,g.endsWith(En)&&(g=g.slice(0,-En.length)),g}else if(e==="av1"){if(!o){let C=i.width*i.height,S=V(Se).level;for(let w of Se)if(C<=w.maxPictureSize){S=w.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}let c=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",l=o.bitDepth.toString().padStart(2,"0"),p=o.monochrome?"1":"0",h=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),f=r?.primaries?we[r.primaries]:1,b=r?.transfer?Te[r.transfer]:1,g=r?.matrix?ye[r.matrix]:1,k=r?.fullRange?1:0,y=`av01.${c}.${u}${d}.${l}`;return y+=`.${p}.${h.toString().padStart(3,"0")}`,y+=`.${f.toString().padStart(2,"0")}`,y+=`.${b.toString().padStart(2,"0")}`,y+=`.${g.toString().padStart(2,"0")}`,y+=`.${k}`,y.endsWith(In)&&(y=y.slice(0,-In.length)),y}}throw new TypeError(`Unhandled codec '${e}'.`)},sr=(i,e,t)=>{if(i==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(U.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},lr=i=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${bi(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&U.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},bi=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new K(i),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),a=null;if(r===15)a=e.readBits(24);else{let o=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r<o.length&&(a=o[r])}let n=e.readBits(4),s=null;return n>=1&&n<=7&&(s={1:1,2:2,3:3,4:4,5:5,6:6,7:8}[n]),{objectType:t,frequencyIndex:r,sampleRate:a,channelConfiguration:n,numberOfChannels:s}},et=48e3,An=/^pcm-([usf])(\d+)+(be)?$/,G=i=>{if(m(U.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=An.exec(i);m(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,a=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:a,silentValue:n}},ki=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":i.startsWith("mp4a.40")||i==="mp4a.67"?"aac":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp3":i==="opus"?"opus":i==="vorbis"?"vorbis":i==="flac"?"flac":i==="ulaw"?"ulaw":i==="alaw"?"alaw":An.test(i)?i:i==="webvtt"?"webvtt":null,or=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},cr=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},H=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){let a=t*r,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},s=1920*1080,o=3e6,c=Math.pow(a/s,.95),l=o*c*n[e]*this._factor;return Math.ceil(l/1e3)*1e3}_toAudioBitrate(e){if(U.includes(e)||e==="flac")return;let r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!r)throw new Error(`Unhandled codec: ${e}`);let a=r*this._factor;return e==="aac"?a=[96e3,128e3,16e4,192e3].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s):e==="opus"||e==="vorbis"?a=Math.max(6e3,a):e==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s)),Math.round(a/1e3)*1e3}},Da=new H(.3),Va=new H(.6),Ua=new H(1),mr=new H(2),za=new H(4),Na=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Wa=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,La=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ha=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Ka=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,fr=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Na.some(e=>i.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(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.description!==void 0&&!Ge(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(we);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let r=Object.keys(Te);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);let a=Object.keys(ye);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.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(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!Wa.test(i.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(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!La.test(i.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(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!Ha.test(i.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(i.decoderConfig.codec.startsWith("av01")&&!Ka.test(i.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/.')},Qa=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Fe=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Qa.some(e=>i.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(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Ge(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.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(!i.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(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.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(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.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(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.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(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.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((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!U.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${U.join(", ")}).`)},pr=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},$a=i=>{if(q.includes(i))return hr(i);if(j.includes(i))return gr(i);if(ae.includes(i))return br(i);throw new TypeError(`Unknown codec '${i}'.`)},hr=async(i,{width:e=1280,height:t=720,bitrate:r=1e6}={})=>{if(!q.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("height must be a positive integer.");if(!(r instanceof H)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");let a=r instanceof H?r._toVideoBitrate(i,e,t):r;if(Ze.length>0){let s={codec:ar(i,e,t,a),width:e,height:t,bitrate:a,...or(i)};if(Ze.some(o=>o.supports(i,s)))return!0}return typeof VideoEncoder>"u"?!1:(await VideoEncoder.isConfigSupported({codec:ar(i,e,t,a),width:e,height:t,bitrate:a,...or(i)})).supported===!0},gr=async(i,{numberOfChannels:e=2,sampleRate:t=48e3,bitrate:r=128e3}={})=>{if(!j.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(r instanceof H)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");let a=r instanceof H?r._toAudioBitrate(i):r;if(Je.length>0){let s={codec:sr(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...cr(i)};if(Je.some(o=>o.supports(i,s)))return!0}return U.includes(i)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported({codec:sr(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...cr(i)})).supported===!0},br=async i=>!!ae.includes(i),qa=async()=>{let[i,e,t]=await Promise.all([Rn(),xt(),Fn()]);return[...i,...e,...t]},Rn=async(i=q,e)=>{let t=await Promise.all(i.map(r=>hr(r,e)));return i.filter((r,a)=>t[a])},xt=async(i=j,e)=>{let t=await Promise.all(i.map(r=>gr(r,e)));return i.filter((r,a)=>t[a])},Fn=async(i=ae)=>{let e=await Promise.all(i.map(br));return i.filter((t,r)=>e[r])},wi=async(i,e)=>{for(let t of i)if(await hr(t,e))return t;return null},ja=async(i,e)=>{for(let t of i)if(await gr(t,e))return t;return null},Ga=async i=>{for(let e of i)if(await br(e))return e;return null};var vt=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Xa=/^WEBVTT(.|\n)*?\n{2}/,tt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,kr=class{constructor(e){this.preambleText=null;this.preambleEmitted=!1;this.options=e}parse(e){e=e.replaceAll(`\r
|
|
9
9
|
`,`
|
|
10
10
|
`).replaceAll("\r",`
|
|
11
|
-
`),
|
|
11
|
+
`),vt.lastIndex=0;let t;if(!this.preambleText){if(!Xa.test(e))throw new Error("WebVTT preamble incorrect.");t=vt.exec(e);let r=e.slice(0,t?.index??e.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,t&&(e=e.slice(t.index),vt.lastIndex=0)}for(;t=vt.exec(e);){let r=e.slice(0,t.index),a=t[1],n=t.index+t[0].length,s=e.indexOf(`
|
|
12
12
|
`,n)+1,o=e.slice(n,s).trim(),c=e.indexOf(`
|
|
13
13
|
|
|
14
|
-
`,n);c===-1&&(c=e.length);let u=kr(t[2]),l=kr(t[3])-u,p=e.slice(s,c).trim();e=e.slice(c).trimStart(),xt.lastIndex=0;let h={timestamp:u/1e3,duration:l/1e3,text:p,identifier:a,settings:o,notes:r},f={};this.preambleEmitted||(f.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,f)}}},Ya=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,kr=i=>{let e=Ya.exec(i);if(!e)throw new Error("Expected match.");return 60*60*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},wr=i=>{let e=Math.floor(i/36e5),t=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),a=i%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var vt=i=>{let e=[],t=0;for(;t<i.length;){let r=-1,a=0;for(let n=t;n<i.length-3;n++){if(i[n]===0&&i[n+1]===0&&i[n+2]===1){r=n,a=3;break}if(n<i.length-4&&i[n]===0&&i[n+1]===0&&i[n+2]===0&&i[n+3]===1){r=n,a=4;break}}if(r===-1)break;if(t>0&&r>t){let n=i.subarray(t,r);n.length>0&&e.push(n)}t=r+a}if(t<i.length){let r=i.subarray(t);r.length>0&&e.push(r)}return e},On=(i,e)=>{let t=[],r=0,a=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;r+e<=i.length;){let n;e===1?n=a.getUint8(r):e===2?n=a.getUint16(r,!1):e===3?n=(a.getUint16(r,!1)<<8)+a.getUint8(r+2):e===4?n=a.getUint32(r,!1):(Re(e),m(!1)),r+=e;let s=i.subarray(r,r+n);t.push(s),r+=n}return t},Ti=i=>{let e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)},Un=i=>{let t=vt(i);if(t.length===0)return null;let r=0;for(let o of t)r+=4+o.byteLength;let a=new Uint8Array(r),n=new DataView(a.buffer),s=0;for(let o of t){let c=o.byteLength;n.setUint32(s,c,!1),s+=4,a.set(o,s),s+=o.byteLength}return a},Tr=i=>i[0]&31,yr=i=>{try{let e=vt(i),t=e.filter(p=>Tr(p)===7),r=e.filter(p=>Tr(p)===8),a=e.filter(p=>Tr(p)===13);if(t.length===0||r.length===0)return null;let n=t[0],s=new K(Ti(n));if(s.skipBits(1),s.skipBits(2),s.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let c=s.readAlignedByte(),u=s.readAlignedByte(),d=s.readAlignedByte(),l={configurationVersion:1,avcProfileIndication:c,profileCompatibility:u,avcLevelIndication:d,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(c===100||c===110||c===122||c===144){P(s);let p=P(s);p===3&&s.skipBits(1);let h=P(s),f=P(s);l.chromaFormat=p,l.bitDepthLumaMinus8=h,l.bitDepthChromaMinus8=f,l.sequenceParameterSetExt=a}return l}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},zn=i=>{let e=[];e.push(i.configurationVersion),e.push(i.avcProfileIndication),e.push(i.profileCompatibility),e.push(i.avcLevelIndication),e.push(252|i.lengthSizeMinusOne&3),e.push(224|i.sequenceParameterSets.length&31);for(let t of i.sequenceParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}e.push(i.pictureParameterSets.length);for(let t of i.pictureParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}if(i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144){m(i.chromaFormat!==null),m(i.bitDepthLumaMinus8!==null),m(i.bitDepthChromaMinus8!==null),m(i.sequenceParameterSetExt!==null),e.push(252|i.chromaFormat&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.sequenceParameterSetExt.length);for(let t of i.sequenceParameterSetExt){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}}return new Uint8Array(e)},Mn=32,Bn=33,Dn=34,Za=39,Ja=40,Ve=i=>i[0]>>1&63,Sr=i=>{try{let e=vt(i),t=e.filter(A=>Ve(A)===Mn),r=e.filter(A=>Ve(A)===Bn),a=e.filter(A=>Ve(A)===Dn),n=e.filter(A=>Ve(A)===Za||Ve(A)===Ja);if(r.length===0||a.length===0)return null;let s=r[0],o=new K(Ti(s));o.skipBits(16),o.readBits(4);let c=o.readBits(3),u=o.readBits(1),{general_profile_space:d,general_tier_flag:l,general_profile_idc:p,general_profile_compatibility_flags:h,general_constraint_indicator_flags:f,general_level_idc:b}=es(o,c);P(o);let g=P(o);g===3&&o.skipBits(1),P(o),P(o),o.readBits(1)&&(P(o),P(o),P(o),P(o));let k=P(o),y=P(o);P(o);let S=o.readBits(1)?0:c;for(let A=S;A<=c;A++)P(o),P(o),P(o);P(o),P(o),P(o),P(o),P(o),P(o),o.readBits(1)&&o.readBits(1)&&ts(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),P(o),P(o),o.skipBits(1));let w=P(o);if(rs(o,w),o.readBits(1)){let A=P(o);for(let _=0;_<A;_++)P(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let T=0;o.readBits(1)&&(T=ns(o,c));let x=0;if(a.length>0){let A=a[0],_=new K(Ti(A));_.skipBits(16),P(_),P(_),_.skipBits(1),_.skipBits(1),_.skipBits(3),_.skipBits(1),_.skipBits(1),P(_),P(_),je(_),_.skipBits(1),_.skipBits(1),_.readBits(1)&&P(_),je(_),je(_),_.skipBits(1),_.skipBits(1),_.skipBits(1),_.skipBits(1);let te=_.readBits(1),ke=_.readBits(1);!te&&!ke?x=0:te&&!ke?x=2:!te&&ke?x=3:x=0}let E=[...t.length?[{arrayCompleteness:1,nalUnitType:Mn,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Bn,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Dn,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Ve(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:l,generalProfileIdc:p,generalProfileCompatibilityFlags:h,generalConstraintIndicatorFlags:f,generalLevelIdc:b,minSpatialSegmentationIdc:T,parallelismType:x,chromaFormatIdc:g,bitDepthLumaMinus8:k,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:E}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},es=(i,e)=>{let t=i.readBits(2),r=i.readBits(1),a=i.readBits(5),n=0;for(let d=0;d<32;d++)n=n<<1|i.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let d=0;d<e;d++)c.push(i.readBits(1)),u.push(i.readBits(1));if(e>0)for(let d=e;d<8;d++)i.skipBits(2);for(let d=0;d<e;d++)c[d]&&i.skipBits(88),u[d]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:n,general_constraint_indicator_flags:s,general_level_idc:o}},ts=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))P(i);else{let a=Math.min(64,1<<4+(e<<1));e>1&&je(i);for(let n=0;n<a;n++)je(i)}},rs=(i,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=is(i,r,e,t)},is=(i,e,t,r)=>{let a=0,n=0,s=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){let c=P(i);s=e-(c+1)}else s=e-1;i.readBits(1),P(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);a=r[s]}else{let o=P(i),c=P(i);for(let u=0;u<o;u++)P(i),i.readBits(1);for(let u=0;u<c;u++)P(i),i.readBits(1);a=o+c}return a},ns=(i,e)=>{if(i.readBits(1)&&i.readBits(8)===255&&(i.readBits(16),i.readBits(16)),i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),i.readBits(1),i.readBits(1)&&(i.readBits(8),i.readBits(8),i.readBits(8))),i.readBits(1)&&(P(i),P(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(P(i),P(i),P(i),P(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&P(i),i.readBits(1)&&as(i,!0,e)),i.readBits(1)){i.readBits(1),i.readBits(1),i.readBits(1);let t=P(i);return P(i),P(i),P(i),P(i),t}return 0},as=(i,e,t)=>{let r=!1,a=!1,n=!1;e&&(r=i.readBits(1)===1,a=i.readBits(1)===1,(r||a)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=t;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let u=!1;c?P(i):u=i.readBits(1)===1;let d=1;u||(d=P(i)+1),r&&Vn(i,d,n),a&&Vn(i,d,n)}},Vn=(i,e,t)=>{for(let r=0;r<e;r++)P(i),P(i),t&&(P(i),P(i)),i.readBits(1)},Nn=i=>{let e=[];e.push(i.configurationVersion),e.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),e.push(i.generalProfileCompatibilityFlags>>>24&255),e.push(i.generalProfileCompatibilityFlags>>>16&255),e.push(i.generalProfileCompatibilityFlags>>>8&255),e.push(i.generalProfileCompatibilityFlags&255),e.push(...i.generalConstraintIndicatorFlags),e.push(i.generalLevelIdc&255),e.push(240|i.minSpatialSegmentationIdc>>8&15),e.push(i.minSpatialSegmentationIdc&255),e.push(252|i.parallelismType&3),e.push(252|i.chromaFormatIdc&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.avgFrameRate>>8&255),e.push(i.avgFrameRate&255),e.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),e.push(i.arrays.length&255);for(let t of i.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let r of t.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let a=0;a<r.length;a++)e.push(r[a])}}return new Uint8Array(e)},Cr=i=>{let e=new K(i);if(e.readBits(2)!==2)return null;let r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;n>=2&&(u=e.readBits(1)?12:10);let d=e.readBits(3),l=0,p=0;if(d!==7)if(p=e.readBits(1),n===1||n===3){let x=e.readBits(1),E=e.readBits(1);l=!x&&!E?3:x&&!E?2:1,e.skipBits(1)}else l=1;else l=3,p=1;let h=e.readBits(16),f=e.readBits(16),b=h+1,g=f+1,k=b*g,y=V(Se).level;for(let T of Se)if(k<=T.maxPictureSize){y=T.level;break}return{profile:n,level:y,bitDepth:u,chromaSubsampling:l,videoFullRangeFlag:p,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}};function*Wn(i){let e=new K(i),t=()=>{let r=0;for(let a=0;a<8;a++){let n=e.readAlignedByte();if(r|=(n&127)<<a*7,!(n&128))break;if(a===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=e.readBits(4),a=e.readBits(1),n=e.readBits(1);e.skipBits(1),a&&e.skipBits(8);let s;if(n){let o=t();if(o===null)return;s=o}else s=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}}var xr=i=>{for(let{type:e,data:t}of Wn(i)){if(e!==1)continue;let r=new K(t),a=r.readBits(3),n=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let k=r.readBits(1);k&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let y=r.readBits(5);for(let C=0;C<=y;C++){r.skipBits(12);let S=r.readBits(5);if(C===0&&(o=S),S>7){let T=r.readBits(1);C===0&&(c=T)}if(k&&r.readBits(1)){let x=u+1;r.skipBits(x),r.skipBits(x),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let d=r.readBits(1),l=8;a===2&&d?l=r.readBits(1)?12:10:a<=2&&(l=d?10:8);let p=0;a!==1&&(p=r.readBits(1));let h=1,f=1,b=0;return p||(a===0?(h=1,f=1):a===1?(h=0,f=0):l===12&&(h=r.readBits(1),h&&(f=r.readBits(1))),h&&f&&(b=r.readBits(2))),{profile:a,level:o,tier:c,bitDepth:l,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:f,chromaSamplePosition:b}}return null},Oe=i=>{let e=Y(i),t=e.getUint8(9),r=e.getUint16(10,!0),a=e.getUint32(12,!0),n=e.getInt16(16,!0),s=e.getUint8(18),o=null;return s&&(o=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:a,outputGain:n,channelMappingFamily:s,channelMappingTable:o}},ss=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Ln=i=>{let e=i[0]>>3;return{durationInSamples:ss[e]}},vr=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=i.length,r=new Uint8Array(t);for(let l=0;l<t;l++)r[l]=i[t-1-l];let a=new K(r),n=0;for(;a.getBitsLeft()>97;)if(a.readBits(1)===1){n=a.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;a.getBitsLeft()>=97;){let l=a.pos,p=a.readBits(8),h=a.readBits(16),f=a.readBits(16);if(p>63||h!==0||f!==0){a.pos=l;break}if(a.skipBits(1),s++,s>64)break;a.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let u=c;a.pos=0,a.skipBits(n);let d=Array(u).fill(0);for(let l=u-1;l>=0;l--)a.skipBits(40),d[l]=a.readBits(1);return{modeBlockflags:d}},Hn=async(i,e)=>{switch(m(i.codec),i.codec){case"avc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(L(t.description)[4]&3)+1;r=On(e.data,o)}else r=vt(e.data);return r.some(n=>Tr(n)===5)?"key":"delta"}case"hevc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(L(t.description)[21]&3)+1;r=On(e.data,o)}else r=vt(e.data);return r.some(n=>{let s=Ve(n);return 16<=s&&s<=23})?"key":"delta"}case"vp8":return(e.data[0]&1)===0?"key":"delta";case"vp9":{let t=new K(e.data);if(t.readBits(2)!==2)return null;let r=t.readBits(1);return(t.readBits(1)<<1)+r===3&&t.skipBits(1),t.readBits(1)?null:t.readBits(1)===0?"key":"delta"}case"av1":{let t=!1;for(let{type:r,data:a}of Wn(e.data))if(r===1){let n=new K(a);n.skipBits(4),t=!!n.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let n=new K(a);return n.readBits(1)?null:n.readBits(2)===0?"key":"delta"}return null}default:Re(i.codec),m(!1)}};var Pt=class{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 t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%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{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let r=this.writer.getPos(),a=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,a),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);m(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let r of e.children)r&&(t+=this.measureBox(r));return t}}},M=new Uint8Array(8),pe=new DataView(M.buffer),N=i=>[(i%256+256)%256],R=i=>(pe.setUint16(0,i,!1),[M[0],M[1]]),Qn=i=>(pe.setInt16(0,i,!1),[M[0],M[1]]),$n=i=>(pe.setUint32(0,i,!1),[M[1],M[2],M[3]]),v=i=>(pe.setUint32(0,i,!1),[M[0],M[1],M[2],M[3]]),Be=i=>(pe.setInt32(0,i,!1),[M[0],M[1],M[2],M[3]]),Ue=i=>(pe.setUint32(0,Math.floor(i/2**32),!1),pe.setUint32(4,i,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),qn=i=>(pe.setInt16(0,2**8*i,!1),[M[0],M[1]]),xe=i=>(pe.setInt32(0,2**16*i,!1),[M[0],M[1],M[2],M[3]]),yi=i=>(pe.setInt32(0,2**30*i,!1),[M[0],M[1],M[2],M[3]]),Si=(i,e)=>{let t=[],r=i;do{let a=r&127;r>>=7,t.length>0&&(a|=128),t.push(a),e!==void 0&&e--}while(r>0||e);return t.reverse()},J=(i,e=!1)=>{let t=Array(i.length).fill(null).map((r,a)=>i.charCodeAt(a));return e&&t.push(0),t},xi=i=>{let e=null;for(let t of i)(!e||t.timestamp>e.timestamp)&&(e=t);return e},jn=i=>{let e=i*(Math.PI/180),t=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[t,r,0,-r,t,0,0,0,1]},Gn=jn(0),Xn=i=>[xe(i[0]),xe(i[1]),yi(i[2]),xe(i[3]),xe(i[4]),yi(i[5]),xe(i[6]),xe(i[7]),yi(i[8])],O=(i,e,t)=>({type:i,contents:e&&new Uint8Array(e.flat(10)),children:t}),B=(i,e,t,r,a)=>O(i,[N(e),$n(t),r??[]],a),Yn=i=>i.isQuickTime?O("ftyp",[J("qt "),v(512),J("qt ")]):i.fragmented?O("ftyp",[J("iso5"),v(512),J("iso5"),J("iso6"),J("mp41")]):O("ftyp",[J("isom"),v(512),J("isom"),i.holdsAvc?J("avc1"):[],J("mp41")]),Er=i=>({type:"mdat",largeSize:i}),Et=(i,e,t=!1)=>O("moov",void 0,[os(e,i),...i.map(r=>cs(r,e)),t?Ks(i):null]),os=(i,e)=>{let t=Q(Math.max(0,...e.filter(s=>s.samples.length>0).map(s=>{let o=xi(s.samples);return o.timestamp+o.duration})),Pr),r=Math.max(0,...e.map(s=>s.track.id))+1,a=!De(i)||!De(t),n=a?Ue:v;return B("mvhd",+a,0,[n(i),n(i),v(Pr),n(t),xe(1),qn(1),Array(10).fill(0),Xn(Gn),Array(24).fill(0),v(r)])},cs=(i,e)=>O("trak",void 0,[ds(i,e),us(i,e)]),ds=(i,e)=>{let t=xi(i.samples),r=Q(t?t.timestamp+t.duration:0,Pr),a=!De(e)||!De(r),n=a?Ue:v,s;if(i.type==="video"){let o=i.track.metadata.rotation;s=jn(o??0)}else s=Gn;return B("tkhd",+a,3,[n(e),n(e),v(i.track.id),v(0),n(r),Array(8).fill(0),R(0),R(i.track.id),qn(i.type==="audio"?1:0),R(0),Xn(s),xe(i.type==="video"?i.info.width:0),xe(i.type==="video"?i.info.height:0)])},us=(i,e)=>O("mdia",void 0,[ls(i,e),ps(i),hs(i)]),ls=(i,e)=>{let t=xi(i.samples),r=Q(t?t.timestamp+t.duration:0,i.timescale),a=!De(e)||!De(r),n=a?Ue:v,s=0;for(let o of i.track.metadata.languageCode??Z)s<<=5,s+=o.charCodeAt(0)-96;return B("mdhd",+a,0,[n(e),n(e),v(i.timescale),n(r),R(s),R(0)])},ms={video:"vide",audio:"soun",subtitle:"text"},fs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ps=i=>B("hdlr",0,0,[J("mhlr"),J(ms[i.type]),v(0),v(0),v(0),J(fs[i.type],!0)]),hs=i=>O("minf",void 0,[ws[i.type](),Ts(),Cs(i)]),gs=()=>B("vmhd",0,1,[R(0),R(0),R(0),R(0)]),bs=()=>B("smhd",0,0,[R(0),R(0)]),ks=()=>B("nmhd",0,0),ws={video:gs,audio:bs,subtitle:ks},Ts=()=>O("dinf",void 0,[ys()]),ys=()=>B("dref",0,0,[v(1)],[Ss()]),Ss=()=>B("url ",0,1),Cs=i=>{let e=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return O("stbl",void 0,[xs(i),Vs(i),e?Ls(i):null,e?Hs(i):null,zs(i),Ns(i),Ws(i),Us(i)])},xs=i=>{let e;if(i.type==="video")e=vs(Js[i.track.source._codec],i);else if(i.type==="audio"){let t=ia(i.track.source._codec,i.muxer.isQuickTime);m(t),e=As(t,i)}else i.type==="subtitle"&&(e=Bs(ro[i.track.source._codec],i));return m(e),B("stsd",0,0,[v(1)],[e])},vs=(i,e)=>O(i,[Array(6).fill(0),R(1),R(0),R(0),Array(12).fill(0),R(e.info.width),R(e.info.height),v(4718592),v(4718592),v(0),R(1),Array(32).fill(0),R(24),Qn(65535)],[eo[e.track.source._codec](e),Yt(e.info.decoderConfig.colorSpace)?Ps(e):null]),Ps=i=>O("colr",[J("nclx"),R(we[i.info.decoderConfig.colorSpace.primaries]),R(Te[i.info.decoderConfig.colorSpace.transfer]),R(ye[i.info.decoderConfig.colorSpace.matrix]),N((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Es=i=>i.info.decoderConfig&&O("avcC",[...L(i.info.decoderConfig.description)]),Is=i=>i.info.decoderConfig&&O("hvcC",[...L(i.info.decoderConfig.description)]),Kn=i=>{if(!i.info.decoderConfig)return null;let e=i.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),a=Number(t[2]),n=Number(t[3]),s=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(s<<1)+o,u=t[5]?Number(t[5]):e.colorSpace?.primaries?we[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?Te[e.colorSpace.transfer]:2,l=t[7]?Number(t[7]):e.colorSpace?.matrix?ye[e.colorSpace.matrix]:2;return B("vpcC",1,0,[N(r),N(a),N(c),N(u),N(d),N(l),R(0)])},_s=i=>O("av1C",cr(i.info.decoderConfig.codec)),As=(i,e)=>{let t=0,r,a=16;if(U.includes(e.track.source._codec)){let n=e.track.source._codec,{sampleSize:s}=G(n);a=8*s,a>16&&(t=1)}return t===0?r=[Array(6).fill(0),R(1),R(t),R(0),v(0),R(e.info.numberOfChannels),R(a),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0)]:r=[Array(6).fill(0),R(1),R(t),R(0),v(0),R(e.info.numberOfChannels),R(Math.min(a,16)),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0),v(1),v(a/8),v(e.info.numberOfChannels*a/8),v(2)],O(i,r,[to(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ci=i=>{let e;switch(i.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: ${i.track.source._codec}`)}let t=[...N(e),...N(21),...$n(0),...v(0),...v(0)];if(i.info.decoderConfig.description){let r=L(i.info.decoderConfig.description);t=[...t,...N(5),...Si(r.byteLength),...r]}return t=[...R(1),...N(0),...N(4),...Si(t.length),...t,...N(6),...N(1),...N(2)],t=[...N(3),...Si(t.length),...t],B("esds",0,0,t)},Me=i=>O("wave",void 0,[Rs(i),Fs(i),O("\0\0\0\0")]),Rs=i=>O("frma",[J(ia(i.track.source._codec,i.muxer.isQuickTime))]),Fs=i=>{let{littleEndian:e}=G(i.track.source._codec);return O("enda",[R(+e)])},Os=i=>{let e=i.info.numberOfChannels,t=3840,r=i.info.sampleRate,a=0,n=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){m(o.byteLength>=18);let c=L(o),u=Oe(c);e=u.outputChannelCount,t=u.preSkip,r=u.inputSampleRate,a=u.outputGain,n=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return O("dOps",[N(0),N(e),R(t),v(r),Qn(a),N(n),...s])},Ms=i=>{let e=i.info.decoderConfig?.description;m(e);let t=L(e);return B("dfLa",0,0,[...t.subarray(4)])},fe=i=>{let{littleEndian:e,sampleSize:t}=G(i.track.source._codec),r=+e;return B("pcmC",0,0,[N(r),N(8*t)])},Bs=(i,e)=>O(i,[Array(6).fill(0),R(1)],[io[e.track.source._codec](e)]),Ds=i=>O("vttC",[...ue.encode(i.info.config.description)]);var Vs=i=>B("stts",0,0,[v(i.timeToSampleTable.length),i.timeToSampleTable.map(e=>[v(e.sampleCount),v(e.sampleDelta)])]),Us=i=>{if(i.samples.every(t=>t.type==="key"))return null;let e=[...i.samples.entries()].filter(([,t])=>t.type==="key");return B("stss",0,0,[v(e.length),e.map(([t])=>v(t+1))])},zs=i=>B("stsc",0,0,[v(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(e=>[v(e.firstChunk),v(e.samplesPerChunk),v(1)])]),Ns=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:e}=G(i.track.source._codec);return B("stsz",0,0,[v(e*i.info.numberOfChannels),v(i.samples.reduce((t,r)=>t+Q(r.duration,i.timescale),0))])}return B("stsz",0,0,[v(0),v(i.samples.length),i.samples.map(e=>v(e.size))])},Ws=i=>i.finalizedChunks.length>0&&V(i.finalizedChunks).offset>=2**32?B("co64",0,0,[v(i.finalizedChunks.length),i.finalizedChunks.map(e=>Ue(e.offset))]):B("stco",0,0,[v(i.finalizedChunks.length),i.finalizedChunks.map(e=>v(e.offset))]),Ls=i=>B("ctts",1,0,[v(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(e=>[v(e.sampleCount),Be(e.sampleCompositionTimeOffset)])]),Hs=i=>{let e=1/0,t=-1/0,r=1/0,a=-1/0;m(i.compositionTimeOffsetTable.length>0),m(i.samples.length>0);for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,Q(o.timestamp,i.timescale)),a=Math.max(a,Q(o.timestamp+o.duration,i.timescale))}let n=Math.max(-e,0);return a>=2**31?null:B("cslg",0,0,[Be(n),Be(e),Be(t),Be(r),Be(a)])},Ks=i=>O("mvex",void 0,i.map(Qs)),Qs=i=>B("trex",0,0,[v(i.track.id),v(1),v(0),v(0),v(0)]),vi=(i,e)=>O("moof",void 0,[$s(i),...e.map(qs)]),$s=i=>B("mfhd",0,0,[v(i)]),Zn=i=>{let e=0,t=0,r=0,a=0,n=i.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|r<<8|a},qs=i=>O("traf",void 0,[js(i),Gs(i),Xs(i)]),js=i=>{m(i.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Zn(t)};return B("tfhd",0,e,[v(i.track.id),v(r.duration),v(r.size),v(r.flags)])},Gs=i=>(m(i.currentChunk),B("tfdt",1,0,[Ue(Q(i.currentChunk.startTimestamp,i.timescale))])),Xs=i=>{m(i.currentChunk);let e=i.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),t=i.currentChunk.samples.map(b=>b.size),r=i.currentChunk.samples.map(Zn),a=i.currentChunk.samples.map(b=>Q(b.timestamp-b.decodeTimestamp,i.timescale)),n=new Set(e),s=new Set(t),o=new Set(r),c=new Set(a),u=o.size===2&&r[0]!==r[1],d=n.size>1,l=s.size>1,p=!u&&o.size>1,h=c.size>1||[...c].some(b=>b!==0),f=0;return f|=1,f|=4*+u,f|=256*+d,f|=512*+l,f|=1024*+p,f|=2048*+h,B("trun",1,f,[v(i.currentChunk.samples.length),v(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?v(r[0]):[],i.currentChunk.samples.map((b,g)=>[d?v(e[g]):[],l?v(t[g]):[],p?v(r[g]):[],h?Be(a[g]):[]])])},Jn=i=>O("mfra",void 0,[...i.map(Ys),Zs()]),Ys=(i,e)=>B("tfra",1,0,[v(i.track.id),v(63),v(i.finalizedChunks.length),i.finalizedChunks.map(r=>[Ue(Q(r.samples[0].timestamp,i.timescale)),Ue(r.moofOffset),v(e+1),v(1),v(1)])]),Zs=()=>B("mfro",0,0,[v(0)]),ea=()=>O("vtte"),ta=(i,e,t,r,a)=>O("vttc",void 0,[a!==null?O("vsid",[Be(a)]):null,t!==null?O("iden",[...ue.encode(t)]):null,e!==null?O("ctim",[...ue.encode(wr(e))]):null,r!==null?O("sttg",[...ue.encode(r)]):null,O("payl",[...ue.encode(i)])]),ra=i=>O("vtta",[...ue.encode(i)]),Js={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},eo={avc:Es,hevc:Is,vp8:Kn,vp9:Kn,av1:_s},ia=(i,e)=>{switch(i){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(i){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(i){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"}},to=(i,e)=>{switch(i){case"aac":return Ci;case"mp3":return Ci;case"opus":return Os;case"vorbis":return Ci;case"flac":return Ms}if(e)switch(i){case"pcm-s24":return Me;case"pcm-s24be":return Me;case"pcm-s32":return Me;case"pcm-s32be":return Me;case"pcm-f32":return Me;case"pcm-f32be":return Me;case"pcm-f64":return Me;case"pcm-f64be":return Me}else switch(i){case"pcm-s16":return fe;case"pcm-s16be":return fe;case"pcm-s24":return fe;case"pcm-s24be":return fe;case"pcm-s32":return fe;case"pcm-s32be":return fe;case"pcm-f32":return fe;case"pcm-f32be":return fe;case"pcm-f64":return fe;case"pcm-f64be":return fe}return null},ro={webvtt:"wvtt"},io={webvtt:Ds};var se=class{constructor(e){this.mutex=new ne;this.firstMediaStreamTimestamp=null;this.trackTimestampInfo=new WeakMap;this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let a=this.trackTimestampInfo.get(e);if(!a){if(!r)throw new Error("First frame must be a key frame.");a={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,a)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(a.maxTimestampBeforeLastKeyFrame=a.maxTimestamp),t<a.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous run (a run begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${a.maxTimestampBeforeLastKeyFrame}s.`);return a.maxTimestamp=Math.max(a.maxTimestamp,t),t}};var Ir=class{constructor(){this.ensureMonotonicity=!1;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let r=t+e.byteLength-this.trackedStart,a=this.trackedWrites.byteLength;for(;a<r;)a*=2;if(a!==this.trackedWrites.byteLength){let n=new Uint8Array(a);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+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.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},Pi=2**16,Ei=2**32,rt=class extends Ir{constructor(t){super();this.pos=0;this.maxPos=0;if(this.target=t,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Pi,{maxByteLength:Ei})}catch{this.buffer=new ArrayBuffer(Pi),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Pi);this.bytes=new Uint8Array(this.buffer)}ensureSize(t){let r=this.buffer.byteLength;for(;r<t;)r*=2;if(r!==this.buffer.byteLength){if(r>Ei)throw new Error(`ArrayBuffer exceeded maximum size of ${Ei} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let a=new ArrayBuffer(r),n=new Uint8Array(a);n.set(this.bytes,0),this.buffer=a,this.bytes=n}}}write(t){this.maybeTrackWrites(t),this.ensureSize(this.pos+t.byteLength),this.bytes.set(t,this.pos),this.pos+=t.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(t){this.pos=t}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(t,r){return this.bytes.slice(t,r)}},no=2**24,ao=2,_r=class extends Ir{constructor(t){super();this.pos=0;this.sections=[];this.lastWriteEnd=0;this.lastFlushEnd=0;this.writer=null;this.chunks=[];this.target=t,this.chunked=t._options.chunked??!1,this.chunkSize=t._options.chunkSize??no}start(){this.writer=this.target._writable.getWriter()}write(t){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(t),this.sections.push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let a=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(a))}if(m(this.writer),this.sections.length===0)return;let t=[],r=[...this.sections].sort((a,n)=>a.start-n.start);t.push({start:r[0].start,size:r[0].data.byteLength});for(let a=1;a<r.length;a++){let n=t[t.length-1],s=r[a];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):t.push({start:s.start,size:s.data.byteLength})}for(let a of t){a.data=new Uint8Array(a.size);for(let n of this.sections)a.start<=n.start&&n.start<a.start+a.size&&a.data.set(n.data,n.start-a.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(a.data,a.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&a.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data,position:a.start}),this.lastFlushEnd=a.start+a.data.byteLength}}this.sections.length=0}writeDataIntoChunks(t,r){let a=this.chunks.findIndex(u=>u.start<=r&&r<u.start+this.chunkSize);a===-1&&(a=this.createChunk(r));let n=this.chunks[a],s=r-n.start,o=t.subarray(0,Math.min(this.chunkSize-s,t.byteLength));n.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this.insertSectionIntoChunk(n,c),n.written[0].start===0&&n.written[0].end===this.chunkSize&&(n.shouldFlush=!0),this.chunks.length>ao){for(let u=0;u<this.chunks.length-1;u++)this.chunks[u].shouldFlush=!0;this.tryToFlushChunks()}o.byteLength<t.byteLength&&this.writeDataIntoChunks(t.subarray(o.byteLength),r+o.byteLength)}insertSectionIntoChunk(t,r){let a=0,n=t.written.length-1,s=-1;for(;a<=n;){let o=Math.floor(a+(n-a+1)/2);t.written[o].start<=r.start?(a=o+1,s=o):n=o-1}for(t.written.splice(s+1,0,r),(s===-1||t.written[s].end<r.start)&&s++;s<t.written.length-1&&t.written[s].end>=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)}createChunk(t){let a={start:Math.floor(t/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(a),this.chunks.sort((n,s)=>n.start-s.start),this.chunks.indexOf(a)}tryToFlushChunks(t=!1){m(this.writer);for(let r=0;r<this.chunks.length;r++){let a=this.chunks[r];if(!(!a.shouldFlush&&!t)){for(let n of a.written){let s=a.start+n.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data.subarray(n.start,n.end),position:s}),this.lastFlushEnd=a.start+n.end}this.chunks.splice(r--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),m(this.writer),this.writer.close()}async close(){return this.writer?.close()}};var ze=class{constructor(){this._output=null}},It=class extends ze{constructor(){super(...arguments);this.buffer=null}_createWriter(){return new rt(this)}},Ii=class extends ze{constructor(e,t={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t}_createWriter(){return new _r(this)}};var Ar=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var Pr=1e3,so=2082844800,Q=(i,e,t=!0)=>{let r=i*e;return t?Math.round(r):r},Rr=class extends se{constructor(t,r){super(t);this.auxTarget=new It;this.auxWriter=this.auxTarget._createWriter();this.auxBoxWriter=new Pt(this.auxWriter);this.mdat=null;this.trackDatas=[];this.allTracksKnown=z();this.creationTime=Math.floor(Date.now()/1e3)+so;this.finalizedChunks=[];this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.format=r,this.writer=t._writer,this.boxWriter=new Pt(this.writer),this.isQuickTime=r instanceof it;let a=this.writer instanceof rt?"in-memory":!1;this.fastStart=r._options.fastStart??a,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let t=await this.mutex.acquire(),r=this.output._tracks.some(a=>a.type==="video"&&a.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Yn({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:a,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(a,n)}this.fastStart==="in-memory"?this.mdat=Er(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Er(!0),this.boxWriter.writeBox(this.mdat)),await this.writer.flush(),t()}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let t=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ar({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r,a){let n=this.trackDatas.find(d=>d.track===t);if(n)return n;mr(a),m(a),m(a.decoderConfig);let s={...a.decoderConfig};m(s.codedWidth!==void 0),m(s.codedHeight!==void 0);let o=!1;if(t.source._codec==="avc"&&!s.description){let d=yr(r.data);if(!d)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=zn(d),o=!0}else if(t.source._codec==="hevc"&&!s.description){let d=Sr(r.data);if(!d)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=Nn(d),o=!0}let c=Cn(1/(t.metadata.frameRate??57600),1e6).denominator,u={muxer:this,track:t,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:o},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((d,l)=>d.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Fe(r),m(r),m(r.decoderConfig);let n={muxer:this,track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&U.includes(t.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,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;fr(r),m(r),m(r.config);let n={muxer:this,track:t,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,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,r,a),o=r.data;if(s.info.requiresAnnexBTransformation){let d=Un(o);if(!d)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=d}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.createSampleForTrack(s,o,c,r.duration,r.type);await this.registerSample(s,u)}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,r.data,o,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,o),await this.registerSample(s,c)}finally{n()}}async maybePadWithSilence(t,r){let a=V(t.samples),n=a?a.timestamp+a.duration:0,s=r-n,o=Q(s,t.timescale);if(o>0){let{sampleSize:c,silentValue:u}=G(t.info.decoderConfig.codec),d=o*t.info.numberOfChannels,l=new Uint8Array(c*d).fill(u),p=this.createSampleForTrack(t,new Uint8Array(l.buffer),n,s,"key");await this.registerSample(t,p)}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),t.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(t,r){for(;t.cueQueue.length>0;){let a=new Set([]);for(let d of t.cueQueue)m(d.timestamp<=r),m(t.lastCueEndTimestamp<=d.timestamp+d.duration),a.add(Math.max(d.timestamp,t.lastCueEndTimestamp)),a.add(d.timestamp+d.duration);let n=[...a].sort((d,l)=>d-l),s=n[0],o=n[1]??s;if(r<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);let d=ea();this.auxBoxWriter.writeBox(d);let l=this.auxWriter.getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(t,l,t.lastCueEndTimestamp,s-t.lastCueEndTimestamp,"key");await this.registerSample(t,p),t.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let d=0;d<t.cueQueue.length;d++){let l=t.cueQueue[d];if(l.timestamp>=o)break;tt.lastIndex=0;let p=tt.test(l.text),h=l.timestamp+l.duration,f=t.cueToSourceId.get(l);if(f===void 0&&o<h&&(f=t.nextSourceId++,t.cueToSourceId.set(l,f)),l.notes){let g=ra(l.notes);this.auxBoxWriter.writeBox(g)}let b=ta(l.text,p?s:null,l.identifier??null,l.settings??null,f??null);this.auxBoxWriter.writeBox(b),h===o&&t.cueQueue.splice(d--,1)}let c=this.auxWriter.getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(t,c,s,o-s,"key");await this.registerSample(t,u),t.lastCueEndTimestamp=o}}createSampleForTrack(t,r,a,n,s){return{timestamp:a,decodeTimestamp:a,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:Q(n,t.timescale)}}processTimestamps(t,r){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){let n=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){let o=t.timestampProcessingQueue[s],c=Q(o.duration,t.timescale);n+=c}if(t.timeToSampleTable.length===0)t.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let s=V(t.timeToSampleTable);s.sampleCount+=n}t.timestampProcessingQueue.length=0;return}let a=t.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<t.timestampProcessingQueue.length;n++){let s=t.timestampProcessingQueue[n];s.decodeTimestamp=a[n],!this.isFragmented&&t.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=Q(s.timestamp-s.decodeTimestamp,t.timescale),c=Q(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){m(t.lastSample);let u=Q(s.decodeTimestamp,t.timescale,!1),d=Math.round(u-t.lastTimescaleUnits);if(m(d>=0),t.lastTimescaleUnits+=d,t.lastSample.timescaleUnitsToNextSample=d,!this.isFragmented){let l=V(t.timeToSampleTable);if(m(l),l.sampleCount===1){l.sampleDelta=d;let h=t.timeToSampleTable[t.timeToSampleTable.length-2];h&&h.sampleDelta===d&&(h.sampleCount++,t.timeToSampleTable.pop(),l=h)}else l.sampleDelta!==d&&(l.sampleCount--,t.timeToSampleTable.push(l={sampleCount:1,sampleDelta:d}));l.sampleDelta===c?l.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let p=V(t.compositionTimeOffsetTable);m(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=Q(s.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));t.lastSample=s}if(t.timestampProcessingQueue.length=0,m(t.lastSample),m(t.lastTimescaleUnits!==null),r!==void 0&&t.lastSample.timescaleUnitsToNextSample===0){m(r.type==="key");let n=Q(r.timestamp,t.timescale,!1),s=Math.round(n-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=s}}async registerSample(t,r){r.type==="key"&&this.processTimestamps(t,r),t.timestampProcessingQueue.push(r),this.isFragmented?(t.sampleQueue.push(r),await this.interleaveSamples()):await this.addSampleToTrack(t,r)}async addSampleToTrack(t,r){this.isFragmented||t.samples.push(r);let a=!1;if(!t.currentChunk)a=!0;else{t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,r.timestamp);let n=r.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(t===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(a=!0,await this.finalizeFragment())}else a=n>=.5}a&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),m(t.currentChunk),t.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(t){if(m(!this.isFragmented),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let r=t.currentChunk.samples.length;if(t.type==="audio"&&t.info.requiresPcmTransformation&&(r=t.currentChunk.samples.reduce((a,n)=>a+Q(n.duration,t.timescale),0)),(t.compactlyCodedChunkTable.length===0||V(t.compactlyCodedChunkTable).samplesPerChunk!==r)&&t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=this.writer.getPos();for(let a of t.currentChunk.samples)m(a.data),this.writer.write(a.data),a.data=null;await this.writer.flush()}async interleaveSamples(t=!1){if(m(this.isFragmented),!(!t&&!this.allTracksAreKnown()))e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<a&&(r=s,a=s.sampleQueue[0].timestamp)}if(!r)break;let n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(t=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let f=Et(this.trackDatas,this.creationTime,!0);if(this.boxWriter.writeBox(f),this.format._options.onMoov){let{data:b,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(b,g)}}let a=this.trackDatas.filter(f=>f.currentChunk),n=vi(r,a),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),c=16,u=o+c,d=1/0;for(let f of a){f.currentChunk.offset=u,f.currentChunk.moofOffset=s;for(let b of f.currentChunk.samples)u+=b.size;d=Math.min(d,f.currentChunk.startTimestamp)}let l=u-o;this.format._options.onMoof&&this.writer.startTrackingWrites();let p=vi(r,a);if(this.boxWriter.writeBox(p),this.format._options.onMoof){let{data:f,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,b,d)}m(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=Er(l>=2**32);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(o+c);for(let f of a)for(let b of f.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.format._options.onMdat){let{data:f,start:b}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,b)}for(let f of a)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;t&&await this.writer.flush()}async onTrackClose(t){let r=await this.mutex.acquire();if(t.type==="subtitle"&&t.source._codec==="webvtt"){let a=this.trackDatas.find(n=>n.track===t);a&&await this.processWebVTTCues(a,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let t=await this.mutex.acquire();this.allTracksKnown.resolve();for(let 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(let r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(let r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){m(this.mdat);let r;for(let n=0;n<2;n++){let s=Et(this.trackDatas,this.creationTime),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+o+r;for(let u of this.finalizedChunks){u.offset=c;for(let{data:d}of u.samples)m(d),c+=d.byteLength,r+=d.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let a=Et(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(a),this.format._options.onMoov){let{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(let n of this.finalizedChunks)for(let s of n.samples)m(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){let r=this.writer.getPos(),a=Jn(this.trackDatas);this.boxWriter.writeBox(a);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{m(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);m(r!==void 0);let a=this.writer.getPos()-r;if(this.mdat.size=a,this.mdat.largeSize=a>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=Et(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}t()}};var nt=class{constructor(e){this.value=e}},at=class{constructor(e){this.value=e}},_t=class{constructor(e){this.value=e}};var oo=[440786851,408125543],co=[17138,17139,290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],_i=[...oo,...co],na=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,aa=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,uo=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},Fr=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=na(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=aa(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=uo(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),r=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);let a=this.writer.getPos();if(this.dataOffsets.set(e,a),this.writeEBML(e.data),e.size!==-1){let n=this.writer.getPos()-a,s=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,r),this.writer.seek(s)}}else if(typeof e.data=="number"){let t=e.size??na(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof nt)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof at)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof _t){let t=e.size??aa(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}}}},sa=8,Or=2,Ne=4+sa,We=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos++,e.getUint8(t)}readS16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getInt16(t,!1)}readVarIntSize(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1),r=e.getUint8(t),a=1,n=128;for(;(r&n)===0&&a<8;)a++,n>>=1;return a}readVarInt(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1),r=e.getUint8(t),a=1,n=128;for(;(r&n)===0&&a<sa;)a++,n>>=1;let{view:s,offset:o}=this.reader.getViewAndOffset(this.pos,this.pos+a),c=r&n-1;for(let u=1;u<a;u++)c*=256,c+=s.getUint8(o+u);return this.pos+=a,c}readUnsignedInt(e){if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=0;for(let n=0;n<e;n++)a*=256,a+=t.getUint8(r+n);return this.pos+=e,a}readSignedInt(e){let t=this.readUnsignedInt(e);return t&1<<e*8-1&&(t-=2**(e*8)),t}readFloat(e){if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=e===4?t.getFloat32(r,!1):t.getFloat64(r,!1);return this.pos+=e,a}readString(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,String.fromCharCode(...new Uint8Array(t.buffer,r,e))}readElementId(){let e=this.readVarIntSize();return this.readUnsignedInt(e)}readElementSize(){let e=this.readU8();return e===255?e=null:(this.pos--,e=this.readVarInt(),e===72057594037927940&&(e=null)),e}readElementHeader(){let e=this.readElementId(),t=this.readElementSize();return{id:e,size:t}}async searchForNextElementId(e,t){let a=new Set(e);for(;this.pos<t-Ne;){this.reader.rangeIsLoaded(this.pos,this.pos+Ne)||await this.reader.loadRange(this.pos,Math.min(this.pos+1048576,t));let n=this.pos,s=this.readElementHeader();if(a.has(s.id))return n;Le(s.size),this.pos+=s.size}return null}},re={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Le(i){if(i===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Mr=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var lo=-(2**15),mo=2**15-1,oa="https://github.com/Vanilagy/mediabunny",ca=6,da=5,fo={video:1,audio:2,subtitle:17},Br=class extends se{constructor(t,r){super(t);this.trackDatas=[];this.allTracksKnown=z();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.duration=0;this.writer=t._writer,this.format=r,this.ebmlWriter=new Fr(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){let t=await this.mutex.acquire();this.writeEBMLHeader(),this.format._options.appendOnly||this.createSeekHead(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let t={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof st?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format._options.onEbmlHeader){let{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,a)}}createSeekHead(){let t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),n={id:290298740,data:[{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:0}]}]};this.seekHead=n}createSegmentInfo(){let t={id:17545,data:new at(0)};this.segmentDuration=t;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:oa},{id:22337,data:oa},this.format._options.appendOnly?null:t]};this.segmentInfo=r}createTracks(){let t={id:374648427,data:[]};this.tracksElement=t;for(let r of this.trackDatas){let a=re[r.track.source._codec];m(a);let n=0;if(r.type==="audio"&&r.track.source._codec==="opus"){n=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=L(s),c=Oe(o);n=Math.round(1e9*(c.preSkip/et))}}t.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:fo[r.type]},{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??Z},{id:134,data:a},{id:22186,data:0},{id:22203,data:n},r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(t){let{frameRate:r,rotation:a}=t.track.metadata,n=[t.info.decoderConfig.description?{id:25506,data:L(t.info.decoderConfig.description)}:null,r?{id:2352003,data:1e9/r}:null],s=a?Ae(-a):0,o=t.info.decoderConfig.colorSpace,c={id:224,data:[{id:176,data:t.info.width},{id:186,data:t.info.height},Yt(o)?{id:21936,data:[{id:21937,data:ye[o.matrix]},{id:21946,data:Te[o.transfer]},{id:21947,data:we[o.primaries]},{id:21945,data:o.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new nt((s+180)%360-180)}]}:null]};return n.push(c),n}audioSpecificTrackInfo(t){let r=U.includes(t.track.source._codec)?G(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:25506,data:L(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new nt(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:25506,data:ue.encode(t.info.config.description)}]}createSegment(){let t={id:408125543,size:this.format._options.appendOnly?-1:ca,data:[this.format._options.appendOnly?null:this.seekHead,this.segmentInfo,this.tracksElement]};if(this.segment=t,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format._options.onSegmentHeader){let{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,a)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return m(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let t=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Mr({isWebM:this.format instanceof st,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;mr(r),m(r),m(r.decoderConfig),m(r.decoderConfig.codedWidth!==void 0),m(r.decoderConfig.codedHeight!==void 0);let n={track:t,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return t.source._codec==="vp9"?n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(_n(n.info.decoderConfig.codec))}:t.source._codec==="av1"&&(n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(cr(n.info.decoderConfig.codec))}),this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Fe(r),m(r),m(r.decoderConfig);let n={track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;fr(r),m(r),m(r.config);let n={track:t,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=r.duration;t.metadata.frameRate!==void 0&&(c=Tt(c,1/t.metadata.frameRate),u=Tt(u,1/t.metadata.frameRate));let d=this.createInternalChunk(r.data,c,u,r.type);t.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=this.createInternalChunk(r.data,c,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{n()}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),c=r.text,u=Math.round(o*1e3);tt.lastIndex=0,c=c.replace(tt,h=>{let b=kr(h.slice(1,-1))-u;return`<${wr(b)}>`});let d=ue.encode(c),l=`${r.settings??""}
|
|
14
|
+
`,n);c===-1&&(c=e.length);let u=wr(t[2]),l=wr(t[3])-u,p=e.slice(s,c).trim();e=e.slice(c).trimStart(),vt.lastIndex=0;let h={timestamp:u/1e3,duration:l/1e3,text:p,identifier:a,settings:o,notes:r},f={};this.preambleEmitted||(f.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,f)}}},Ya=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,wr=i=>{let e=Ya.exec(i);if(!e)throw new Error("Expected match.");return 60*60*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},Tr=i=>{let e=Math.floor(i/36e5),t=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),a=i%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var Pt=i=>{let e=[],t=0;for(;t<i.length;){let r=-1,a=0;for(let n=t;n<i.length-3;n++){if(i[n]===0&&i[n+1]===0&&i[n+2]===1){r=n,a=3;break}if(n<i.length-4&&i[n]===0&&i[n+1]===0&&i[n+2]===0&&i[n+3]===1){r=n,a=4;break}}if(r===-1)break;if(t>0&&r>t){let n=i.subarray(t,r);n.length>0&&e.push(n)}t=r+a}if(t<i.length){let r=i.subarray(t);r.length>0&&e.push(r)}return e},On=(i,e)=>{let t=[],r=0,a=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;r+e<=i.length;){let n;e===1?n=a.getUint8(r):e===2?n=a.getUint16(r,!1):e===3?n=(a.getUint16(r,!1)<<8)+a.getUint8(r+2):e===4?n=a.getUint32(r,!1):(Re(e),m(!1)),r+=e;let s=i.subarray(r,r+n);t.push(s),r+=n}return t},Ti=i=>{let e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)},Un=i=>{let t=Pt(i);if(t.length===0)return null;let r=0;for(let o of t)r+=4+o.byteLength;let a=new Uint8Array(r),n=new DataView(a.buffer),s=0;for(let o of t){let c=o.byteLength;n.setUint32(s,c,!1),s+=4,a.set(o,s),s+=o.byteLength}return a},yr=i=>i[0]&31,Sr=i=>{try{let e=Pt(i),t=e.filter(p=>yr(p)===7),r=e.filter(p=>yr(p)===8),a=e.filter(p=>yr(p)===13);if(t.length===0||r.length===0)return null;let n=t[0],s=new K(Ti(n));if(s.skipBits(1),s.skipBits(2),s.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let c=s.readAlignedByte(),u=s.readAlignedByte(),d=s.readAlignedByte(),l={configurationVersion:1,avcProfileIndication:c,profileCompatibility:u,avcLevelIndication:d,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(c===100||c===110||c===122||c===144){P(s);let p=P(s);p===3&&s.skipBits(1);let h=P(s),f=P(s);l.chromaFormat=p,l.bitDepthLumaMinus8=h,l.bitDepthChromaMinus8=f,l.sequenceParameterSetExt=a}return l}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},zn=i=>{let e=[];e.push(i.configurationVersion),e.push(i.avcProfileIndication),e.push(i.profileCompatibility),e.push(i.avcLevelIndication),e.push(252|i.lengthSizeMinusOne&3),e.push(224|i.sequenceParameterSets.length&31);for(let t of i.sequenceParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}e.push(i.pictureParameterSets.length);for(let t of i.pictureParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}if(i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144){m(i.chromaFormat!==null),m(i.bitDepthLumaMinus8!==null),m(i.bitDepthChromaMinus8!==null),m(i.sequenceParameterSetExt!==null),e.push(252|i.chromaFormat&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.sequenceParameterSetExt.length);for(let t of i.sequenceParameterSetExt){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}}return new Uint8Array(e)},Mn=32,Bn=33,Dn=34,Za=39,Ja=40,Ve=i=>i[0]>>1&63,Cr=i=>{try{let e=Pt(i),t=e.filter(A=>Ve(A)===Mn),r=e.filter(A=>Ve(A)===Bn),a=e.filter(A=>Ve(A)===Dn),n=e.filter(A=>Ve(A)===Za||Ve(A)===Ja);if(r.length===0||a.length===0)return null;let s=r[0],o=new K(Ti(s));o.skipBits(16),o.readBits(4);let c=o.readBits(3),u=o.readBits(1),{general_profile_space:d,general_tier_flag:l,general_profile_idc:p,general_profile_compatibility_flags:h,general_constraint_indicator_flags:f,general_level_idc:b}=es(o,c);P(o);let g=P(o);g===3&&o.skipBits(1),P(o),P(o),o.readBits(1)&&(P(o),P(o),P(o),P(o));let k=P(o),y=P(o);P(o);let S=o.readBits(1)?0:c;for(let A=S;A<=c;A++)P(o),P(o),P(o);P(o),P(o),P(o),P(o),P(o),P(o),o.readBits(1)&&o.readBits(1)&&ts(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),P(o),P(o),o.skipBits(1));let w=P(o);if(rs(o,w),o.readBits(1)){let A=P(o);for(let _=0;_<A;_++)P(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let T=0;o.readBits(1)&&(T=ns(o,c));let x=0;if(a.length>0){let A=a[0],_=new K(Ti(A));_.skipBits(16),P(_),P(_),_.skipBits(1),_.skipBits(1),_.skipBits(3),_.skipBits(1),_.skipBits(1),P(_),P(_),je(_),_.skipBits(1),_.skipBits(1),_.readBits(1)&&P(_),je(_),je(_),_.skipBits(1),_.skipBits(1),_.skipBits(1),_.skipBits(1);let te=_.readBits(1),ke=_.readBits(1);!te&&!ke?x=0:te&&!ke?x=2:!te&&ke?x=3:x=0}let E=[...t.length?[{arrayCompleteness:1,nalUnitType:Mn,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Bn,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Dn,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Ve(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:l,generalProfileIdc:p,generalProfileCompatibilityFlags:h,generalConstraintIndicatorFlags:f,generalLevelIdc:b,minSpatialSegmentationIdc:T,parallelismType:x,chromaFormatIdc:g,bitDepthLumaMinus8:k,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:E}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},es=(i,e)=>{let t=i.readBits(2),r=i.readBits(1),a=i.readBits(5),n=0;for(let d=0;d<32;d++)n=n<<1|i.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let d=0;d<e;d++)c.push(i.readBits(1)),u.push(i.readBits(1));if(e>0)for(let d=e;d<8;d++)i.skipBits(2);for(let d=0;d<e;d++)c[d]&&i.skipBits(88),u[d]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:n,general_constraint_indicator_flags:s,general_level_idc:o}},ts=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))P(i);else{let a=Math.min(64,1<<4+(e<<1));e>1&&je(i);for(let n=0;n<a;n++)je(i)}},rs=(i,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=is(i,r,e,t)},is=(i,e,t,r)=>{let a=0,n=0,s=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){let c=P(i);s=e-(c+1)}else s=e-1;i.readBits(1),P(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);a=r[s]}else{let o=P(i),c=P(i);for(let u=0;u<o;u++)P(i),i.readBits(1);for(let u=0;u<c;u++)P(i),i.readBits(1);a=o+c}return a},ns=(i,e)=>{if(i.readBits(1)&&i.readBits(8)===255&&(i.readBits(16),i.readBits(16)),i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),i.readBits(1),i.readBits(1)&&(i.readBits(8),i.readBits(8),i.readBits(8))),i.readBits(1)&&(P(i),P(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(P(i),P(i),P(i),P(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&P(i),i.readBits(1)&&as(i,!0,e)),i.readBits(1)){i.readBits(1),i.readBits(1),i.readBits(1);let t=P(i);return P(i),P(i),P(i),P(i),t}return 0},as=(i,e,t)=>{let r=!1,a=!1,n=!1;e&&(r=i.readBits(1)===1,a=i.readBits(1)===1,(r||a)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=t;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let u=!1;c?P(i):u=i.readBits(1)===1;let d=1;u||(d=P(i)+1),r&&Vn(i,d,n),a&&Vn(i,d,n)}},Vn=(i,e,t)=>{for(let r=0;r<e;r++)P(i),P(i),t&&(P(i),P(i)),i.readBits(1)},Nn=i=>{let e=[];e.push(i.configurationVersion),e.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),e.push(i.generalProfileCompatibilityFlags>>>24&255),e.push(i.generalProfileCompatibilityFlags>>>16&255),e.push(i.generalProfileCompatibilityFlags>>>8&255),e.push(i.generalProfileCompatibilityFlags&255),e.push(...i.generalConstraintIndicatorFlags),e.push(i.generalLevelIdc&255),e.push(240|i.minSpatialSegmentationIdc>>8&15),e.push(i.minSpatialSegmentationIdc&255),e.push(252|i.parallelismType&3),e.push(252|i.chromaFormatIdc&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.avgFrameRate>>8&255),e.push(i.avgFrameRate&255),e.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),e.push(i.arrays.length&255);for(let t of i.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let r of t.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let a=0;a<r.length;a++)e.push(r[a])}}return new Uint8Array(e)},xr=i=>{let e=new K(i);if(e.readBits(2)!==2)return null;let r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;n>=2&&(u=e.readBits(1)?12:10);let d=e.readBits(3),l=0,p=0;if(d!==7)if(p=e.readBits(1),n===1||n===3){let x=e.readBits(1),E=e.readBits(1);l=!x&&!E?3:x&&!E?2:1,e.skipBits(1)}else l=1;else l=3,p=1;let h=e.readBits(16),f=e.readBits(16),b=h+1,g=f+1,k=b*g,y=V(Se).level;for(let T of Se)if(k<=T.maxPictureSize){y=T.level;break}return{profile:n,level:y,bitDepth:u,chromaSubsampling:l,videoFullRangeFlag:p,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}};function*Wn(i){let e=new K(i),t=()=>{let r=0;for(let a=0;a<8;a++){let n=e.readAlignedByte();if(r|=(n&127)<<a*7,!(n&128))break;if(a===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=e.readBits(4),a=e.readBits(1),n=e.readBits(1);e.skipBits(1),a&&e.skipBits(8);let s;if(n){let o=t();if(o===null)return;s=o}else s=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}}var vr=i=>{for(let{type:e,data:t}of Wn(i)){if(e!==1)continue;let r=new K(t),a=r.readBits(3),n=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let k=r.readBits(1);k&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let y=r.readBits(5);for(let C=0;C<=y;C++){r.skipBits(12);let S=r.readBits(5);if(C===0&&(o=S),S>7){let T=r.readBits(1);C===0&&(c=T)}if(k&&r.readBits(1)){let x=u+1;r.skipBits(x),r.skipBits(x),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}let d=r.readBits(1),l=8;a===2&&d?l=r.readBits(1)?12:10:a<=2&&(l=d?10:8);let p=0;a!==1&&(p=r.readBits(1));let h=1,f=1,b=0;return p||(a===0?(h=1,f=1):a===1?(h=0,f=0):l===12&&(h=r.readBits(1),h&&(f=r.readBits(1))),h&&f&&(b=r.readBits(2))),{profile:a,level:o,tier:c,bitDepth:l,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:f,chromaSamplePosition:b}}return null},Oe=i=>{let e=Y(i),t=e.getUint8(9),r=e.getUint16(10,!0),a=e.getUint32(12,!0),n=e.getInt16(16,!0),s=e.getUint8(18),o=null;return s&&(o=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:a,outputGain:n,channelMappingFamily:s,channelMappingTable:o}},ss=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Ln=i=>{let e=i[0]>>3;return{durationInSamples:ss[e]}},Pr=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=i.length,r=new Uint8Array(t);for(let l=0;l<t;l++)r[l]=i[t-1-l];let a=new K(r),n=0;for(;a.getBitsLeft()>97;)if(a.readBits(1)===1){n=a.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;a.getBitsLeft()>=97;){let l=a.pos,p=a.readBits(8),h=a.readBits(16),f=a.readBits(16);if(p>63||h!==0||f!==0){a.pos=l;break}if(a.skipBits(1),s++,s>64)break;a.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let u=c;a.pos=0,a.skipBits(n);let d=Array(u).fill(0);for(let l=u-1;l>=0;l--)a.skipBits(40),d[l]=a.readBits(1);return{modeBlockflags:d}},Hn=async(i,e)=>{switch(m(i.codec),i.codec){case"avc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(L(t.description)[4]&3)+1;r=On(e.data,o)}else r=Pt(e.data);return r.some(n=>yr(n)===5)?"key":"delta"}case"hevc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(L(t.description)[21]&3)+1;r=On(e.data,o)}else r=Pt(e.data);return r.some(n=>{let s=Ve(n);return 16<=s&&s<=23})?"key":"delta"}case"vp8":return(e.data[0]&1)===0?"key":"delta";case"vp9":{let t=new K(e.data);if(t.readBits(2)!==2)return null;let r=t.readBits(1);return(t.readBits(1)<<1)+r===3&&t.skipBits(1),t.readBits(1)?null:t.readBits(1)===0?"key":"delta"}case"av1":{let t=!1;for(let{type:r,data:a}of Wn(e.data))if(r===1){let n=new K(a);n.skipBits(4),t=!!n.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let n=new K(a);return n.readBits(1)?null:n.readBits(2)===0?"key":"delta"}return null}default:Re(i.codec),m(!1)}};var Et=class{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 t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%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{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let r=this.writer.getPos(),a=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,a),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);m(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let r of e.children)r&&(t+=this.measureBox(r));return t}}},M=new Uint8Array(8),pe=new DataView(M.buffer),N=i=>[(i%256+256)%256],R=i=>(pe.setUint16(0,i,!1),[M[0],M[1]]),Qn=i=>(pe.setInt16(0,i,!1),[M[0],M[1]]),$n=i=>(pe.setUint32(0,i,!1),[M[1],M[2],M[3]]),v=i=>(pe.setUint32(0,i,!1),[M[0],M[1],M[2],M[3]]),Be=i=>(pe.setInt32(0,i,!1),[M[0],M[1],M[2],M[3]]),Ue=i=>(pe.setUint32(0,Math.floor(i/2**32),!1),pe.setUint32(4,i,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),qn=i=>(pe.setInt16(0,2**8*i,!1),[M[0],M[1]]),xe=i=>(pe.setInt32(0,2**16*i,!1),[M[0],M[1],M[2],M[3]]),yi=i=>(pe.setInt32(0,2**30*i,!1),[M[0],M[1],M[2],M[3]]),Si=(i,e)=>{let t=[],r=i;do{let a=r&127;r>>=7,t.length>0&&(a|=128),t.push(a),e!==void 0&&e--}while(r>0||e);return t.reverse()},J=(i,e=!1)=>{let t=Array(i.length).fill(null).map((r,a)=>i.charCodeAt(a));return e&&t.push(0),t},xi=i=>{let e=null;for(let t of i)(!e||t.timestamp>e.timestamp)&&(e=t);return e},jn=i=>{let e=i*(Math.PI/180),t=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[t,r,0,-r,t,0,0,0,1]},Gn=jn(0),Xn=i=>[xe(i[0]),xe(i[1]),yi(i[2]),xe(i[3]),xe(i[4]),yi(i[5]),xe(i[6]),xe(i[7]),yi(i[8])],O=(i,e,t)=>({type:i,contents:e&&new Uint8Array(e.flat(10)),children:t}),B=(i,e,t,r,a)=>O(i,[N(e),$n(t),r??[]],a),Yn=i=>i.isQuickTime?O("ftyp",[J("qt "),v(512),J("qt ")]):i.fragmented?O("ftyp",[J("iso5"),v(512),J("iso5"),J("iso6"),J("mp41")]):O("ftyp",[J("isom"),v(512),J("isom"),i.holdsAvc?J("avc1"):[],J("mp41")]),Ir=i=>({type:"mdat",largeSize:i}),It=(i,e,t=!1)=>O("moov",void 0,[os(e,i),...i.map(r=>cs(r,e)),t?Ks(i):null]),os=(i,e)=>{let t=Q(Math.max(0,...e.filter(s=>s.samples.length>0).map(s=>{let o=xi(s.samples);return o.timestamp+o.duration})),Er),r=Math.max(0,...e.map(s=>s.track.id))+1,a=!De(i)||!De(t),n=a?Ue:v;return B("mvhd",+a,0,[n(i),n(i),v(Er),n(t),xe(1),qn(1),Array(10).fill(0),Xn(Gn),Array(24).fill(0),v(r)])},cs=(i,e)=>O("trak",void 0,[ds(i,e),us(i,e)]),ds=(i,e)=>{let t=xi(i.samples),r=Q(t?t.timestamp+t.duration:0,Er),a=!De(e)||!De(r),n=a?Ue:v,s;if(i.type==="video"){let o=i.track.metadata.rotation;s=jn(o??0)}else s=Gn;return B("tkhd",+a,3,[n(e),n(e),v(i.track.id),v(0),n(r),Array(8).fill(0),R(0),R(i.track.id),qn(i.type==="audio"?1:0),R(0),Xn(s),xe(i.type==="video"?i.info.width:0),xe(i.type==="video"?i.info.height:0)])},us=(i,e)=>O("mdia",void 0,[ls(i,e),ps(i),hs(i)]),ls=(i,e)=>{let t=xi(i.samples),r=Q(t?t.timestamp+t.duration:0,i.timescale),a=!De(e)||!De(r),n=a?Ue:v,s=0;for(let o of i.track.metadata.languageCode??Z)s<<=5,s+=o.charCodeAt(0)-96;return B("mdhd",+a,0,[n(e),n(e),v(i.timescale),n(r),R(s),R(0)])},ms={video:"vide",audio:"soun",subtitle:"text"},fs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ps=i=>B("hdlr",0,0,[J("mhlr"),J(ms[i.type]),v(0),v(0),v(0),J(fs[i.type],!0)]),hs=i=>O("minf",void 0,[ws[i.type](),Ts(),Cs(i)]),gs=()=>B("vmhd",0,1,[R(0),R(0),R(0),R(0)]),bs=()=>B("smhd",0,0,[R(0),R(0)]),ks=()=>B("nmhd",0,0),ws={video:gs,audio:bs,subtitle:ks},Ts=()=>O("dinf",void 0,[ys()]),ys=()=>B("dref",0,0,[v(1)],[Ss()]),Ss=()=>B("url ",0,1),Cs=i=>{let e=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return O("stbl",void 0,[xs(i),Vs(i),e?Ls(i):null,e?Hs(i):null,zs(i),Ns(i),Ws(i),Us(i)])},xs=i=>{let e;if(i.type==="video")e=vs(Js[i.track.source._codec],i);else if(i.type==="audio"){let t=ia(i.track.source._codec,i.muxer.isQuickTime);m(t),e=As(t,i)}else i.type==="subtitle"&&(e=Bs(ro[i.track.source._codec],i));return m(e),B("stsd",0,0,[v(1)],[e])},vs=(i,e)=>O(i,[Array(6).fill(0),R(1),R(0),R(0),Array(12).fill(0),R(e.info.width),R(e.info.height),v(4718592),v(4718592),v(0),R(1),Array(32).fill(0),R(24),Qn(65535)],[eo[e.track.source._codec](e),Zt(e.info.decoderConfig.colorSpace)?Ps(e):null]),Ps=i=>O("colr",[J("nclx"),R(we[i.info.decoderConfig.colorSpace.primaries]),R(Te[i.info.decoderConfig.colorSpace.transfer]),R(ye[i.info.decoderConfig.colorSpace.matrix]),N((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Es=i=>i.info.decoderConfig&&O("avcC",[...L(i.info.decoderConfig.description)]),Is=i=>i.info.decoderConfig&&O("hvcC",[...L(i.info.decoderConfig.description)]),Kn=i=>{if(!i.info.decoderConfig)return null;let e=i.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),a=Number(t[2]),n=Number(t[3]),s=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(s<<1)+o,u=t[5]?Number(t[5]):e.colorSpace?.primaries?we[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?Te[e.colorSpace.transfer]:2,l=t[7]?Number(t[7]):e.colorSpace?.matrix?ye[e.colorSpace.matrix]:2;return B("vpcC",1,0,[N(r),N(a),N(c),N(u),N(d),N(l),R(0)])},_s=i=>O("av1C",dr(i.info.decoderConfig.codec)),As=(i,e)=>{let t=0,r,a=16;if(U.includes(e.track.source._codec)){let n=e.track.source._codec,{sampleSize:s}=G(n);a=8*s,a>16&&(t=1)}return t===0?r=[Array(6).fill(0),R(1),R(t),R(0),v(0),R(e.info.numberOfChannels),R(a),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0)]:r=[Array(6).fill(0),R(1),R(t),R(0),v(0),R(e.info.numberOfChannels),R(Math.min(a,16)),R(0),R(0),R(e.info.sampleRate<2**16?e.info.sampleRate:0),R(0),v(1),v(a/8),v(e.info.numberOfChannels*a/8),v(2)],O(i,r,[to(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ci=i=>{let e;switch(i.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: ${i.track.source._codec}`)}let t=[...N(e),...N(21),...$n(0),...v(0),...v(0)];if(i.info.decoderConfig.description){let r=L(i.info.decoderConfig.description);t=[...t,...N(5),...Si(r.byteLength),...r]}return t=[...R(1),...N(0),...N(4),...Si(t.length),...t,...N(6),...N(1),...N(2)],t=[...N(3),...Si(t.length),...t],B("esds",0,0,t)},Me=i=>O("wave",void 0,[Rs(i),Fs(i),O("\0\0\0\0")]),Rs=i=>O("frma",[J(ia(i.track.source._codec,i.muxer.isQuickTime))]),Fs=i=>{let{littleEndian:e}=G(i.track.source._codec);return O("enda",[R(+e)])},Os=i=>{let e=i.info.numberOfChannels,t=3840,r=i.info.sampleRate,a=0,n=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){m(o.byteLength>=18);let c=L(o),u=Oe(c);e=u.outputChannelCount,t=u.preSkip,r=u.inputSampleRate,a=u.outputGain,n=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return O("dOps",[N(0),N(e),R(t),v(r),Qn(a),N(n),...s])},Ms=i=>{let e=i.info.decoderConfig?.description;m(e);let t=L(e);return B("dfLa",0,0,[...t.subarray(4)])},fe=i=>{let{littleEndian:e,sampleSize:t}=G(i.track.source._codec),r=+e;return B("pcmC",0,0,[N(r),N(8*t)])},Bs=(i,e)=>O(i,[Array(6).fill(0),R(1)],[io[e.track.source._codec](e)]),Ds=i=>O("vttC",[...ue.encode(i.info.config.description)]);var Vs=i=>B("stts",0,0,[v(i.timeToSampleTable.length),i.timeToSampleTable.map(e=>[v(e.sampleCount),v(e.sampleDelta)])]),Us=i=>{if(i.samples.every(t=>t.type==="key"))return null;let e=[...i.samples.entries()].filter(([,t])=>t.type==="key");return B("stss",0,0,[v(e.length),e.map(([t])=>v(t+1))])},zs=i=>B("stsc",0,0,[v(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(e=>[v(e.firstChunk),v(e.samplesPerChunk),v(1)])]),Ns=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:e}=G(i.track.source._codec);return B("stsz",0,0,[v(e*i.info.numberOfChannels),v(i.samples.reduce((t,r)=>t+Q(r.duration,i.timescale),0))])}return B("stsz",0,0,[v(0),v(i.samples.length),i.samples.map(e=>v(e.size))])},Ws=i=>i.finalizedChunks.length>0&&V(i.finalizedChunks).offset>=2**32?B("co64",0,0,[v(i.finalizedChunks.length),i.finalizedChunks.map(e=>Ue(e.offset))]):B("stco",0,0,[v(i.finalizedChunks.length),i.finalizedChunks.map(e=>v(e.offset))]),Ls=i=>B("ctts",1,0,[v(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(e=>[v(e.sampleCount),Be(e.sampleCompositionTimeOffset)])]),Hs=i=>{let e=1/0,t=-1/0,r=1/0,a=-1/0;m(i.compositionTimeOffsetTable.length>0),m(i.samples.length>0);for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,Q(o.timestamp,i.timescale)),a=Math.max(a,Q(o.timestamp+o.duration,i.timescale))}let n=Math.max(-e,0);return a>=2**31?null:B("cslg",0,0,[Be(n),Be(e),Be(t),Be(r),Be(a)])},Ks=i=>O("mvex",void 0,i.map(Qs)),Qs=i=>B("trex",0,0,[v(i.track.id),v(1),v(0),v(0),v(0)]),vi=(i,e)=>O("moof",void 0,[$s(i),...e.map(qs)]),$s=i=>B("mfhd",0,0,[v(i)]),Zn=i=>{let e=0,t=0,r=0,a=0,n=i.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|r<<8|a},qs=i=>O("traf",void 0,[js(i),Gs(i),Xs(i)]),js=i=>{m(i.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Zn(t)};return B("tfhd",0,e,[v(i.track.id),v(r.duration),v(r.size),v(r.flags)])},Gs=i=>(m(i.currentChunk),B("tfdt",1,0,[Ue(Q(i.currentChunk.startTimestamp,i.timescale))])),Xs=i=>{m(i.currentChunk);let e=i.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),t=i.currentChunk.samples.map(b=>b.size),r=i.currentChunk.samples.map(Zn),a=i.currentChunk.samples.map(b=>Q(b.timestamp-b.decodeTimestamp,i.timescale)),n=new Set(e),s=new Set(t),o=new Set(r),c=new Set(a),u=o.size===2&&r[0]!==r[1],d=n.size>1,l=s.size>1,p=!u&&o.size>1,h=c.size>1||[...c].some(b=>b!==0),f=0;return f|=1,f|=4*+u,f|=256*+d,f|=512*+l,f|=1024*+p,f|=2048*+h,B("trun",1,f,[v(i.currentChunk.samples.length),v(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?v(r[0]):[],i.currentChunk.samples.map((b,g)=>[d?v(e[g]):[],l?v(t[g]):[],p?v(r[g]):[],h?Be(a[g]):[]])])},Jn=i=>O("mfra",void 0,[...i.map(Ys),Zs()]),Ys=(i,e)=>B("tfra",1,0,[v(i.track.id),v(63),v(i.finalizedChunks.length),i.finalizedChunks.map(r=>[Ue(Q(r.samples[0].timestamp,i.timescale)),Ue(r.moofOffset),v(e+1),v(1),v(1)])]),Zs=()=>B("mfro",0,0,[v(0)]),ea=()=>O("vtte"),ta=(i,e,t,r,a)=>O("vttc",void 0,[a!==null?O("vsid",[Be(a)]):null,t!==null?O("iden",[...ue.encode(t)]):null,e!==null?O("ctim",[...ue.encode(Tr(e))]):null,r!==null?O("sttg",[...ue.encode(r)]):null,O("payl",[...ue.encode(i)])]),ra=i=>O("vtta",[...ue.encode(i)]),Js={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},eo={avc:Es,hevc:Is,vp8:Kn,vp9:Kn,av1:_s},ia=(i,e)=>{switch(i){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(i){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(i){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"}},to=(i,e)=>{switch(i){case"aac":return Ci;case"mp3":return Ci;case"opus":return Os;case"vorbis":return Ci;case"flac":return Ms}if(e)switch(i){case"pcm-s24":return Me;case"pcm-s24be":return Me;case"pcm-s32":return Me;case"pcm-s32be":return Me;case"pcm-f32":return Me;case"pcm-f32be":return Me;case"pcm-f64":return Me;case"pcm-f64be":return Me}else switch(i){case"pcm-s16":return fe;case"pcm-s16be":return fe;case"pcm-s24":return fe;case"pcm-s24be":return fe;case"pcm-s32":return fe;case"pcm-s32be":return fe;case"pcm-f32":return fe;case"pcm-f32be":return fe;case"pcm-f64":return fe;case"pcm-f64be":return fe}return null},ro={webvtt:"wvtt"},io={webvtt:Ds};var se=class{constructor(e){this.mutex=new ne;this.firstMediaStreamTimestamp=null;this.trackTimestampInfo=new WeakMap;this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let a=this.trackTimestampInfo.get(e);if(!a){if(!r)throw new Error("First frame must be a key frame.");a={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,a)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(a.maxTimestampBeforeLastKeyFrame=a.maxTimestamp),t<a.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous run (a run begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${a.maxTimestampBeforeLastKeyFrame}s.`);return a.maxTimestamp=Math.max(a.maxTimestamp,t),t}};var _r=class{constructor(){this.ensureMonotonicity=!1;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let r=t+e.byteLength-this.trackedStart,a=this.trackedWrites.byteLength;for(;a<r;)a*=2;if(a!==this.trackedWrites.byteLength){let n=new Uint8Array(a);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+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.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},Pi=2**16,Ei=2**32,rt=class extends _r{constructor(t){super();this.pos=0;this.maxPos=0;if(this.target=t,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Pi,{maxByteLength:Ei})}catch{this.buffer=new ArrayBuffer(Pi),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Pi);this.bytes=new Uint8Array(this.buffer)}ensureSize(t){let r=this.buffer.byteLength;for(;r<t;)r*=2;if(r!==this.buffer.byteLength){if(r>Ei)throw new Error(`ArrayBuffer exceeded maximum size of ${Ei} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let a=new ArrayBuffer(r),n=new Uint8Array(a);n.set(this.bytes,0),this.buffer=a,this.bytes=n}}}write(t){this.maybeTrackWrites(t),this.ensureSize(this.pos+t.byteLength),this.bytes.set(t,this.pos),this.pos+=t.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(t){this.pos=t}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(t,r){return this.bytes.slice(t,r)}},no=2**24,ao=2,Ar=class extends _r{constructor(t){super();this.pos=0;this.sections=[];this.lastWriteEnd=0;this.lastFlushEnd=0;this.writer=null;this.chunks=[];this.target=t,this.chunked=t._options.chunked??!1,this.chunkSize=t._options.chunkSize??no}start(){this.writer=this.target._writable.getWriter()}write(t){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(t),this.sections.push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let a=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(a))}if(m(this.writer),this.sections.length===0)return;let t=[],r=[...this.sections].sort((a,n)=>a.start-n.start);t.push({start:r[0].start,size:r[0].data.byteLength});for(let a=1;a<r.length;a++){let n=t[t.length-1],s=r[a];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):t.push({start:s.start,size:s.data.byteLength})}for(let a of t){a.data=new Uint8Array(a.size);for(let n of this.sections)a.start<=n.start&&n.start<a.start+a.size&&a.data.set(n.data,n.start-a.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(a.data,a.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&a.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data,position:a.start}),this.lastFlushEnd=a.start+a.data.byteLength}}this.sections.length=0}writeDataIntoChunks(t,r){let a=this.chunks.findIndex(u=>u.start<=r&&r<u.start+this.chunkSize);a===-1&&(a=this.createChunk(r));let n=this.chunks[a],s=r-n.start,o=t.subarray(0,Math.min(this.chunkSize-s,t.byteLength));n.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this.insertSectionIntoChunk(n,c),n.written[0].start===0&&n.written[0].end===this.chunkSize&&(n.shouldFlush=!0),this.chunks.length>ao){for(let u=0;u<this.chunks.length-1;u++)this.chunks[u].shouldFlush=!0;this.tryToFlushChunks()}o.byteLength<t.byteLength&&this.writeDataIntoChunks(t.subarray(o.byteLength),r+o.byteLength)}insertSectionIntoChunk(t,r){let a=0,n=t.written.length-1,s=-1;for(;a<=n;){let o=Math.floor(a+(n-a+1)/2);t.written[o].start<=r.start?(a=o+1,s=o):n=o-1}for(t.written.splice(s+1,0,r),(s===-1||t.written[s].end<r.start)&&s++;s<t.written.length-1&&t.written[s].end>=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)}createChunk(t){let a={start:Math.floor(t/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(a),this.chunks.sort((n,s)=>n.start-s.start),this.chunks.indexOf(a)}tryToFlushChunks(t=!1){m(this.writer);for(let r=0;r<this.chunks.length;r++){let a=this.chunks[r];if(!(!a.shouldFlush&&!t)){for(let n of a.written){let s=a.start+n.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data.subarray(n.start,n.end),position:s}),this.lastFlushEnd=a.start+n.end}this.chunks.splice(r--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),m(this.writer),this.writer.close()}async close(){return this.writer?.close()}};var ze=class{constructor(){this._output=null}},_t=class extends ze{constructor(){super(...arguments);this.buffer=null}_createWriter(){return new rt(this)}},Ii=class extends ze{constructor(e,t={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t}_createWriter(){return new Ar(this)}};var Rr=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var Er=1e3,so=2082844800,Q=(i,e,t=!0)=>{let r=i*e;return t?Math.round(r):r},Fr=class extends se{constructor(t,r){super(t);this.auxTarget=new _t;this.auxWriter=this.auxTarget._createWriter();this.auxBoxWriter=new Et(this.auxWriter);this.mdat=null;this.trackDatas=[];this.allTracksKnown=z();this.creationTime=Math.floor(Date.now()/1e3)+so;this.finalizedChunks=[];this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.format=r,this.writer=t._writer,this.boxWriter=new Et(this.writer),this.isQuickTime=r instanceof it;let a=this.writer instanceof rt?"in-memory":!1;this.fastStart=r._options.fastStart??a,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=r._options.minimumFragmentDuration??1}async start(){let t=await this.mutex.acquire(),r=this.output._tracks.some(a=>a.type==="video"&&a.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Yn({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:a,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(a,n)}this.fastStart==="in-memory"?this.mdat=Ir(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ir(!0),this.boxWriter.writeBox(this.mdat)),await this.writer.flush(),t()}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let t=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Rr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r,a){let n=this.trackDatas.find(d=>d.track===t);if(n)return n;fr(a),m(a),m(a.decoderConfig);let s={...a.decoderConfig};m(s.codedWidth!==void 0),m(s.codedHeight!==void 0);let o=!1;if(t.source._codec==="avc"&&!s.description){let d=Sr(r.data);if(!d)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=zn(d),o=!0}else if(t.source._codec==="hevc"&&!s.description){let d=Cr(r.data);if(!d)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=Nn(d),o=!0}let c=Cn(1/(t.metadata.frameRate??57600),1e6).denominator,u={muxer:this,track:t,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:o},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((d,l)=>d.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Fe(r),m(r),m(r.decoderConfig);let n={muxer:this,track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&U.includes(t.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,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;pr(r),m(r),m(r.config);let n={muxer:this,track:t,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,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,r,a),o=r.data;if(s.info.requiresAnnexBTransformation){let d=Un(o);if(!d)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=d}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.createSampleForTrack(s,o,c,r.duration,r.type);await this.registerSample(s,u)}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,r.data,o,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,o),await this.registerSample(s,c)}finally{n()}}async maybePadWithSilence(t,r){let a=V(t.samples),n=a?a.timestamp+a.duration:0,s=r-n,o=Q(s,t.timescale);if(o>0){let{sampleSize:c,silentValue:u}=G(t.info.decoderConfig.codec),d=o*t.info.numberOfChannels,l=new Uint8Array(c*d).fill(u),p=this.createSampleForTrack(t,new Uint8Array(l.buffer),n,s,"key");await this.registerSample(t,p)}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),t.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(t,r){for(;t.cueQueue.length>0;){let a=new Set([]);for(let d of t.cueQueue)m(d.timestamp<=r),m(t.lastCueEndTimestamp<=d.timestamp+d.duration),a.add(Math.max(d.timestamp,t.lastCueEndTimestamp)),a.add(d.timestamp+d.duration);let n=[...a].sort((d,l)=>d-l),s=n[0],o=n[1]??s;if(r<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);let d=ea();this.auxBoxWriter.writeBox(d);let l=this.auxWriter.getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(t,l,t.lastCueEndTimestamp,s-t.lastCueEndTimestamp,"key");await this.registerSample(t,p),t.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let d=0;d<t.cueQueue.length;d++){let l=t.cueQueue[d];if(l.timestamp>=o)break;tt.lastIndex=0;let p=tt.test(l.text),h=l.timestamp+l.duration,f=t.cueToSourceId.get(l);if(f===void 0&&o<h&&(f=t.nextSourceId++,t.cueToSourceId.set(l,f)),l.notes){let g=ra(l.notes);this.auxBoxWriter.writeBox(g)}let b=ta(l.text,p?s:null,l.identifier??null,l.settings??null,f??null);this.auxBoxWriter.writeBox(b),h===o&&t.cueQueue.splice(d--,1)}let c=this.auxWriter.getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(t,c,s,o-s,"key");await this.registerSample(t,u),t.lastCueEndTimestamp=o}}createSampleForTrack(t,r,a,n,s){return{timestamp:a,decodeTimestamp:a,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:Q(n,t.timescale)}}processTimestamps(t,r){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){let n=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){let o=t.timestampProcessingQueue[s],c=Q(o.duration,t.timescale);n+=c}if(t.timeToSampleTable.length===0)t.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let s=V(t.timeToSampleTable);s.sampleCount+=n}t.timestampProcessingQueue.length=0;return}let a=t.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<t.timestampProcessingQueue.length;n++){let s=t.timestampProcessingQueue[n];s.decodeTimestamp=a[n],!this.isFragmented&&t.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=Q(s.timestamp-s.decodeTimestamp,t.timescale),c=Q(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){m(t.lastSample);let u=Q(s.decodeTimestamp,t.timescale,!1),d=Math.round(u-t.lastTimescaleUnits);if(m(d>=0),t.lastTimescaleUnits+=d,t.lastSample.timescaleUnitsToNextSample=d,!this.isFragmented){let l=V(t.timeToSampleTable);if(m(l),l.sampleCount===1){l.sampleDelta=d;let h=t.timeToSampleTable[t.timeToSampleTable.length-2];h&&h.sampleDelta===d&&(h.sampleCount++,t.timeToSampleTable.pop(),l=h)}else l.sampleDelta!==d&&(l.sampleCount--,t.timeToSampleTable.push(l={sampleCount:1,sampleDelta:d}));l.sampleDelta===c?l.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let p=V(t.compositionTimeOffsetTable);m(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=Q(s.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));t.lastSample=s}if(t.timestampProcessingQueue.length=0,m(t.lastSample),m(t.lastTimescaleUnits!==null),r!==void 0&&t.lastSample.timescaleUnitsToNextSample===0){m(r.type==="key");let n=Q(r.timestamp,t.timescale,!1),s=Math.round(n-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=s}}async registerSample(t,r){r.type==="key"&&this.processTimestamps(t,r),t.timestampProcessingQueue.push(r),this.isFragmented?(t.sampleQueue.push(r),await this.interleaveSamples()):await this.addSampleToTrack(t,r)}async addSampleToTrack(t,r){this.isFragmented||t.samples.push(r);let a=!1;if(!t.currentChunk)a=!0;else{t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,r.timestamp);let n=r.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(t===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(a=!0,await this.finalizeFragment())}else a=n>=.5}a&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),m(t.currentChunk),t.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(t){if(m(!this.isFragmented),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let r=t.currentChunk.samples.length;if(t.type==="audio"&&t.info.requiresPcmTransformation&&(r=t.currentChunk.samples.reduce((a,n)=>a+Q(n.duration,t.timescale),0)),(t.compactlyCodedChunkTable.length===0||V(t.compactlyCodedChunkTable).samplesPerChunk!==r)&&t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=this.writer.getPos();for(let a of t.currentChunk.samples)m(a.data),this.writer.write(a.data),a.data=null;await this.writer.flush()}async interleaveSamples(t=!1){if(m(this.isFragmented),!(!t&&!this.allTracksAreKnown()))e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<a&&(r=s,a=s.sampleQueue[0].timestamp)}if(!r)break;let n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(t=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let f=It(this.trackDatas,this.creationTime,!0);if(this.boxWriter.writeBox(f),this.format._options.onMoov){let{data:b,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(b,g)}}let a=this.trackDatas.filter(f=>f.currentChunk),n=vi(r,a),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),c=16,u=o+c,d=1/0;for(let f of a){f.currentChunk.offset=u,f.currentChunk.moofOffset=s;for(let b of f.currentChunk.samples)u+=b.size;d=Math.min(d,f.currentChunk.startTimestamp)}let l=u-o;this.format._options.onMoof&&this.writer.startTrackingWrites();let p=vi(r,a);if(this.boxWriter.writeBox(p),this.format._options.onMoof){let{data:f,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,b,d)}m(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=Ir(l>=2**32);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(o+c);for(let f of a)for(let b of f.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.format._options.onMdat){let{data:f,start:b}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,b)}for(let f of a)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;t&&await this.writer.flush()}async onTrackClose(t){let r=await this.mutex.acquire();if(t.type==="subtitle"&&t.source._codec==="webvtt"){let a=this.trackDatas.find(n=>n.track===t);a&&await this.processWebVTTCues(a,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let t=await this.mutex.acquire();this.allTracksKnown.resolve();for(let 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(let r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(let r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){m(this.mdat);let r;for(let n=0;n<2;n++){let s=It(this.trackDatas,this.creationTime),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+o+r;for(let u of this.finalizedChunks){u.offset=c;for(let{data:d}of u.samples)m(d),c+=d.byteLength,r+=d.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let a=It(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(a),this.format._options.onMoov){let{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(let n of this.finalizedChunks)for(let s of n.samples)m(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){let r=this.writer.getPos(),a=Jn(this.trackDatas);this.boxWriter.writeBox(a);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{m(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);m(r!==void 0);let a=this.writer.getPos()-r;if(this.mdat.size=a,this.mdat.largeSize=a>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=It(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}t()}};var nt=class{constructor(e){this.value=e}},at=class{constructor(e){this.value=e}},At=class{constructor(e){this.value=e}};var oo=[440786851,408125543],co=[17138,17139,290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],_i=[...oo,...co],na=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,aa=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,uo=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},Or=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=na(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=aa(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=uo(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),r=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);let a=this.writer.getPos();if(this.dataOffsets.set(e,a),this.writeEBML(e.data),e.size!==-1){let n=this.writer.getPos()-a,s=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,r),this.writer.seek(s)}}else if(typeof e.data=="number"){let t=e.size??na(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof nt)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof at)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof At){let t=e.size??aa(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}}}},sa=8,Mr=2,Ne=4+sa,We=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos++,e.getUint8(t)}readS16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getInt16(t,!1)}readVarIntSize(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1),r=e.getUint8(t),a=1,n=128;for(;(r&n)===0&&a<8;)a++,n>>=1;return a}readVarInt(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1),r=e.getUint8(t),a=1,n=128;for(;(r&n)===0&&a<sa;)a++,n>>=1;let{view:s,offset:o}=this.reader.getViewAndOffset(this.pos,this.pos+a),c=r&n-1;for(let u=1;u<a;u++)c*=256,c+=s.getUint8(o+u);return this.pos+=a,c}readUnsignedInt(e){if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=0;for(let n=0;n<e;n++)a*=256,a+=t.getUint8(r+n);return this.pos+=e,a}readSignedInt(e){let t=this.readUnsignedInt(e);return t&1<<e*8-1&&(t-=2**(e*8)),t}readFloat(e){if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=e===4?t.getFloat32(r,!1):t.getFloat64(r,!1);return this.pos+=e,a}readString(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,String.fromCharCode(...new Uint8Array(t.buffer,r,e))}readElementId(){let e=this.readVarIntSize();return this.readUnsignedInt(e)}readElementSize(){let e=this.readU8();return e===255?e=null:(this.pos--,e=this.readVarInt(),e===72057594037927940&&(e=null)),e}readElementHeader(){let e=this.readElementId(),t=this.readElementSize();return{id:e,size:t}}async searchForNextElementId(e,t){let a=new Set(e);for(;this.pos<t-Ne;){this.reader.rangeIsLoaded(this.pos,this.pos+Ne)||await this.reader.loadRange(this.pos,Math.min(this.pos+1048576,t));let n=this.pos,s=this.readElementHeader();if(a.has(s.id))return n;Le(s.size),this.pos+=s.size}return null}},re={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Le(i){if(i===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Br=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var lo=-(2**15),mo=2**15-1,oa="https://github.com/Vanilagy/mediabunny",ca=6,da=5,fo={video:1,audio:2,subtitle:17},Dr=class extends se{constructor(t,r){super(t);this.trackDatas=[];this.allTracksKnown=z();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.duration=0;this.writer=t._writer,this.format=r,this.ebmlWriter=new Or(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){let t=await this.mutex.acquire();this.writeEBMLHeader(),this.format._options.appendOnly||this.createSeekHead(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let t={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof st?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format._options.onEbmlHeader){let{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,a)}}createSeekHead(){let t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),n={id:290298740,data:[{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:0}]}]};this.seekHead=n}createSegmentInfo(){let t={id:17545,data:new at(0)};this.segmentDuration=t;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:oa},{id:22337,data:oa},this.format._options.appendOnly?null:t]};this.segmentInfo=r}createTracks(){let t={id:374648427,data:[]};this.tracksElement=t;for(let r of this.trackDatas){let a=re[r.track.source._codec];m(a);let n=0;if(r.type==="audio"&&r.track.source._codec==="opus"){n=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=L(s),c=Oe(o);n=Math.round(1e9*(c.preSkip/et))}}t.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:fo[r.type]},{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??Z},{id:134,data:a},{id:22186,data:0},{id:22203,data:n},r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(t){let{frameRate:r,rotation:a}=t.track.metadata,n=[t.info.decoderConfig.description?{id:25506,data:L(t.info.decoderConfig.description)}:null,r?{id:2352003,data:1e9/r}:null],s=a?Ae(-a):0,o=t.info.decoderConfig.colorSpace,c={id:224,data:[{id:176,data:t.info.width},{id:186,data:t.info.height},Zt(o)?{id:21936,data:[{id:21937,data:ye[o.matrix]},{id:21946,data:Te[o.transfer]},{id:21947,data:we[o.primaries]},{id:21945,data:o.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new nt((s+180)%360-180)}]}:null]};return n.push(c),n}audioSpecificTrackInfo(t){let r=U.includes(t.track.source._codec)?G(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:25506,data:L(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new nt(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:25506,data:ue.encode(t.info.config.description)}]}createSegment(){let t={id:408125543,size:this.format._options.appendOnly?-1:ca,data:[this.format._options.appendOnly?null:this.seekHead,this.segmentInfo,this.tracksElement]};if(this.segment=t,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format._options.onSegmentHeader){let{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,a)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return m(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let t=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Br({isWebM:this.format instanceof st,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;fr(r),m(r),m(r.decoderConfig),m(r.decoderConfig.codedWidth!==void 0),m(r.decoderConfig.codedHeight!==void 0);let n={track:t,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return t.source._codec==="vp9"?n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(_n(n.info.decoderConfig.codec))}:t.source._codec==="av1"&&(n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(dr(n.info.decoderConfig.codec))}),this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Fe(r),m(r),m(r.decoderConfig);let n={track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;pr(r),m(r),m(r.config);let n={track:t,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=r.duration;t.metadata.frameRate!==void 0&&(c=Tt(c,1/t.metadata.frameRate),u=Tt(u,1/t.metadata.frameRate));let d=this.createInternalChunk(r.data,c,u,r.type);t.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=this.createInternalChunk(r.data,c,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{n()}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),c=r.text,u=Math.round(o*1e3);tt.lastIndex=0,c=c.replace(tt,h=>{let b=wr(h.slice(1,-1))-u;return`<${Tr(b)}>`});let d=ue.encode(c),l=`${r.settings??""}
|
|
15
15
|
${r.identifier??""}
|
|
16
|
-
${r.notes??""}`,p=this.createInternalChunk(d,o,r.duration,"key",l.trim()?ue.encode(l):null);s.chunkQueue.push(p),await this.interleaveChunks()}finally{n()}}async interleaveChunks(t=!1){if(!(!t&&!this.allTracksAreKnown())){e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.chunkQueue.length===0&&!s.track.source._closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<a&&(r=s,a=s.chunkQueue[0].timestamp)}if(!r)break;let n=r.chunkQueue.shift();this.writeBlock(r,n)}t||await this.writer.flush()}}fixVP9ColorSpace(t,r){if(r.type!=="key"||!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;let a=new K(r.data);a.skipBits(2);let n=a.readBits(1),o=(a.readBits(1)<<1)+n;if(o===3&&a.skipBits(1),a.readBits(1)||a.readBits(1)!==0||(a.skipBits(2),a.readBits(24)!==4817730))return;o>=2&&a.skipBits(1);let l={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];hn(r.data,a.pos,a.pos+3,l)}createInternalChunk(t,r,a,n,s=null){return{data:t,type:n,timestamp:r,duration:a,additions:s}}writeBlock(t,r){this.segment||(this.createTracks(),this.createSegment());let a=Math.round(1e3*r.timestamp),n=this.trackDatas.every(l=>{if(t===l)return r.type==="key";let p=l.chunkQueue[0];return p?p.type==="key":l.track.source._closed}),s=!1;if(!this.currentCluster)s=!0;else{m(this.currentClusterStartMsTimestamp!==null),m(this.currentClusterMaxMsTimestamp!==null);let l=a-this.currentClusterStartMsTimestamp;s=n&&a>this.currentClusterMaxMsTimestamp&&l>=1e3*(this.format._options.minimumClusterDuration??1)||l>mo}s&&this.createNewCluster(a);let o=a-this.currentClusterStartMsTimestamp;if(o<lo)return;let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|t.track.id),u.setInt16(1,o,!1);let d=Math.round(1e3*r.duration);if(d===0&&!r.additions){u.setUint8(3,+(r.type==="key")<<7);let l={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(l)}else{let l={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new _t(t.lastWrittenMsTimestamp-a)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:165,data:r.additions},{id:238,data:1}]}]}:null,d>0?{id:155,data:d}:null]};this.ebmlWriter.writeEBML(l)}this.duration=Math.max(this.duration,a+d),t.lastWrittenMsTimestamp=a,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:a}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,a)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:da,data:[{id:231,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(m(this.currentCluster),!this.format._options.appendOnly){let n=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(n,da),this.writer.seek(s)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(n,s,this.currentClusterStartMsTimestamp/1e3)}let t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[n,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(n);let a=[...r.entries()].sort((n,s)=>n[0]-s[0]);for(let[n,s]of a)m(this.cues),this.cues.data.push({id:187,data:[{id:179,data:n},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:t}]}))]})}async onTrackClose(){let t=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let t=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||(this.createTracks(),this.createSegment()),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),m(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos(),a=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(a,ca),this.segmentDuration.data=new at(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),this.seekHead.data[0].data[1].data=this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset,this.seekHead.data[1].data[1].data=this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset,this.seekHead.data[2].data[1].data=this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset,this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(r)}t()}};var Ai={1:[-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],2:[-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],3:[-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1]},Ri={1:[-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],2:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1],3:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1]},Fi={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},ot=1483304551,Dr=1231971951,Vr=(i,e,t,r)=>Math.floor(i===3?(12*e/t+r)*4:144*e/t+r),ct=(i,e)=>i===3?e===3?21:36:e===3?13:21,Ur=(i,e)=>{let t=e.pos,r=i>>>24,a=i>>>16&255,n=i>>>8&255,s=i&255;if(r!==255&&a!==255&&n!==255&&s!==255)return e.pos+=4,null;if(e.pos+=1,r!==255||(a&224)!==224)return null;let o=a>>3&3,c=a>>1&3,u=n>>4&15,d=n>>2&3,l=n>>1&1,p=s>>6&3,h=s>>4&3,f=s>>3&1,b=s>>2&1,g=s&3,k=o===3?Ai[c]?.[u]:Ri[c]?.[u];if(!k||k===-1)return null;let y=k*1e3,C=Fi[o]?.[d];if(!C||C===-1)return null;let S=Vr(c,y,C,l);if(e.fileSize!==null&&e.fileSize-t<S)return null;let w;return o===3?w=c===3?384:1152:c===3?w=384:c===2?w=1152:w=576,{startPos:t,totalSize:S,mpegVersionId:o,layer:c,bitrate:y,frequencyIndex:d,sampleRate:C,channel:p,modeExtension:h,copyright:f,original:b,emphasis:g,audioSamplesInFrame:w}};var zr=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),r=255,a=224|e.mpegVersionId<<3|e.layer<<1,s=(e.mpegVersionId===3?Ai:Ri)?.[e.layer];if(!s)throw new Error("Invalid MPEG version and layer combination.");let o=Fi[e.mpegVersionId]?.[e.frequencyIndex];if(!o||o===-1)throw new Error("Invalid MPEG version and frequency index combination.");let c=0,u=155,d=s.findIndex(g=>Vr(e.layer,1e3*g,o,c)>=u);if(d===-1)throw new Error("No suitable bitrate found.");let l=d<<4|e.frequencyIndex<<2|c<<1,p=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=r,this.helper[1]=a,this.helper[2]=l,this.helper[3]=p,this.writer.write(this.helper.subarray(0,4));let h=ct(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(ot);let f=0;e.frameCount!==null&&(f|=1),e.fileSize!==null&&(f|=2),e.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let b=Vr(e.layer,1e3*s[d],o,c);this.writer.seek(t+b)}};var Nr=class extends se{constructor(t,r){super(t);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.format=r,this.writer=t._writer,this.mp3Writer=new zr(t._writer)}async start(){}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(t,r){let a=await this.mutex.acquire();try{if(!this.xingFrameData){let n=Y(r.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=n.getUint32(0,!1),o=Ur(s,{pos:0,fileSize:null});if(!o)throw new Error("Invalid MP3 header in sample.");let c=ct(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){let u=n.getUint32(c,!1);if(u===ot||u===Dr)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(t,r.timestamp,r.type==="key"),this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData)return;let t=await this.mutex.acquire(),r=this.writer.getPos();this.writer.seek(0);let a=new Uint8Array(100);for(let n=0;n<100;n++){let s=Math.floor(this.framePositions.length*(n/100));m(s!==-1&&s<this.framePositions.length);let o=this.framePositions[s];a[n]=256*(o/r)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,s)}this.writer.seek(r),t()}};var At=1399285583,po=79764919,la=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^po:e<<1;la[i]=e>>>0&4294967295}var Wr=i=>{let e=Y(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let a=0;a<i.length;a++){let n=i[a];r=(r<<8^la[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},Lr=(i,e,t)=>{let r=0,a=null;if(i.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,o=(1<<Sn(n-1))-1<<1,c=(i[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=t,d=e.vorbisInfo.modeBlockflags[c];if(a=e.vorbisInfo.blocksizes[d],d===1){let l=(o|1)+1,p=i[0]&l?1:0;u=e.vorbisInfo.blocksizes[p]}r=u!==null?u+a>>2:0}else e.codec==="opus"&&(r=Ln(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:a}},Hr=i=>{let e="audio/ogg";if(i.codecStrings){let t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var ut=27,He=282,Kr=He+255*255,dt=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos+=1,e.getUint8(t)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!0)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!0)}readI64(){let e=this.readU32();return this.readI32()*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readPageHeader(){let e=this.pos;if(this.readU32()!==At)return null;this.pos+=1;let r=this.readU8(),a=this.readI64(),n=this.readU32(),s=this.readU32(),o=this.readU32(),c=this.readU8(),u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=this.readU8();let d=27+c,l=u.reduce((h,f)=>h+f,0),p=d+l;return{headerStartPos:e,totalSize:p,dataStartPos:e+d,dataSize:l,headerType:r,granulePosition:a,serialNumber:n,sequenceNumber:s,checksum:o,lacingValues:u}}findNextPageHeader(e){for(;this.pos<e-3;){let t=this.readU32(),r=t&255,a=t>>>8&255,n=t>>>16&255,s=t>>>24&255,o=79;if(!(r!==o&&a!==o&&n!==o&&s!==o)){if(this.pos-=4,t===At)return!0;this.pos+=1}}return!1}};var ho=8192,Qr=class extends se{constructor(t,r){super(t);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=z();this.pageBytes=new Uint8Array(Kr);this.pageView=new DataView(this.pageBytes.buffer);this.format=r,this.writer=t._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,Hr({codecStrings:this.trackDatas.map(t=>t.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(t,r){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;let n;do n=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===n));m(t.source._codec==="vorbis"||t.source._codec==="opus"),Fe(r),m(r),m(r.decoderConfig);let s={track:t,serialNumber:n,internalSampleRate:t.source._codec==="opus"?et:r.decoderConfig.sampleRate,codecInfo:{codec:t.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(t,r){if(m(r.decoderConfig),t.track.source._codec==="vorbis"){m(r.decoderConfig.description);let a=L(r.decoderConfig.description);if(a[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let n=1,s=()=>{let b=0;for(;;){let g=a[n++];if(g===void 0)throw new TypeError("Vorbis decoder description is too short.");if(b+=g,g<255)return b}},o=s(),c=s();if(a.length-n<=0)throw new TypeError("Vorbis decoder description is too short.");let d=a.subarray(n,n+=o),l=a.subarray(n,n+=c),p=a.subarray(n);t.packetQueue.push({data:d,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:l,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:p,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let f=Y(d).getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:vr(p).modeBlockflags}}else if(t.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let a=L(r.decoderConfig.description),n=new Uint8Array(16),s=new DataView(n.buffer);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1),s.setUint32(8,0,!0),s.setUint32(12,0,!0),t.packetQueue.push({data:a,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:n,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),t.codecInfo.opusInfo={preSkip:Oe(a).preSkip}}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=Lr(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u,s.packetQueue.push({data:r.data,endGranulePosition:s.currentTimestampInSamples,timestamp:o/s.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{n()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async interleavePages(t=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let a=r.packetQueue.shift();if(this.writePacket(r,a,!1),a.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,a=1/0;for(let o of this.trackDatas){if(!t&&o.packetQueue.length<=1&&!o.track.source._closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestamp<a&&(r=o,a=o.packetQueue[0].timestamp)}if(!r)break;let n=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,n,s)}t||await this.writer.flush()}writePacket(t,r,a){let n=r.data.length,s=0,o=0;for(;;){t.currentLacingValues.length===0&&s>0&&(t.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,n);t.currentLacingValues.push(u),t.currentPageSize++,o+=u;let d=n<255;if(t.currentLacingValues.length===255){let l=r.data.subarray(s,o);if(s=o,t.currentPageData.push(l),t.currentPageSize+=l.length,this.writePage(t,a&&d),d)return}if(d)break;n-=255}let c=r.data.subarray(s);t.currentPageData.push(c),t.currentPageSize+=c.length,t.currentGranulePosition=r.endGranulePosition,(t.currentPageSize>=ho||r.forcePageFlush)&&this.writePage(t,a)}writePage(t,r){this.pageView.setUint32(0,At,!0),this.pageView.setUint8(4,0);let a=0;t.currentPageStartsWithFreshPacket||(a|=1),t.pagesWritten===0&&(a|=2),r&&(a|=4),this.pageView.setUint8(5,a);let n=t.currentLacingValues.every(u=>u===255)?-1:t.currentGranulePosition;yn(this.pageView,6,n,!0),this.pageView.setUint32(14,t.serialNumber,!0),this.pageView.setUint32(18,t.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,t.currentLacingValues.length),this.pageBytes.set(t.currentLacingValues,27);let s=27+t.currentLacingValues.length;for(let u of t.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=Wr(o);if(this.pageView.setUint32(22,c,!0),t.pagesWritten++,t.currentLacingValues.length=0,t.currentPageData.length=0,t.currentPageSize=27,t.currentPageStartsWithFreshPacket=!0,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:u,start:d}=this.writer.stopTrackingWrites();this.format._options.onPage(u,d,t.track.source)}}async onTrackClose(){let t=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){let t=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);t()}};var oe=class{constructor(e){this.input=e}};var ee=new Uint8Array(0),D=class i{constructor(e,t,r,a,n=-1,s){this.data=e;this.type=t;this.timestamp=r;this.duration=a;this.sequenceNumber=n;if(e===ee&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=s}get isMetadataOnly(){return this.data===ee}get microsecondTimestamp(){return Math.trunc(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*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})}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){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let t=new Uint8Array(e.byteLength);return e.copyTo(t),new i(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}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 i(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var ma=i=>{let r=i,a=4096,n=0,s=12,o=0;for(r<0&&(r=-r,n=128),r+=33,r>8191&&(r=8191);(r&a)!==a&&s>=5;)a>>=1,s--;return o=r>>s-4&15,~(n|s-5<<4|o)&255},fa=i=>{let t=0,r=0,a=~i;a&128&&(a&=-129,t=-1),r=((a&240)>>4)+5;let n=(1<<r|(a&15)<<r-4|1<<r-5)-33;return t===0?n:-n},pa=i=>{let t=2048,r=0,a=11,n=0,s=i;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&a>=5;)t>>=1,a--;return n=s>>(a===4?1:a-4)&15,(r|a-4<<4|n)^85},ha=i=>{let e=0,t=0,r=i^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let a=0;return t!==4?a=1<<t|(r&15)<<t-4|1<<t-5:a=r<<1|1,e===0?a:-a};var ce=class i{constructor(e,t){this._closed=!1;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=L(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=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(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new i(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*me),duration:Math.trunc((t.duration??0)*me)}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(r,a),s=n.getContext("2d",{alpha:!1,willReadFrequently:!0});m(s),s.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=r,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}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(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*this.duration)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Rt(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration}):this._data instanceof Uint8Array?new i(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace}):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace})}close(){this._closed||(Rt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Rt(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!Ge(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),Rt(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)L(e).set(this._data);else{let r=this._data.getContext("2d",{alpha:!1});m(r);let a=r.getImageData(0,0,this.codedWidth,this.codedHeight);L(e).set(a.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Rt(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,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,r,a,n,s,o,c,u){let d=0,l=0,p=this.displayWidth,h=this.displayHeight,f=0,b=0,g=this.displayWidth,k=this.displayHeight;if(s!==void 0?(d=t,l=r,p=a,h=n,f=s,b=o,c!==void 0?(g=c,k=u):(g=p,k=h)):(f=t,b=r,a!==void 0&&(g=a,k=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(k)||k<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[d,l,p,h]=[l,this.codedHeight-d-p,h,p]:this.rotation===180?[d,l]=[this.codedWidth-d-p,this.codedHeight-l-h]:this.rotation===270&&([d,l,p,h]=[this.codedWidth-l-h,d,h,p]);let y=this.toCanvasImageSource();e.save();let C=f+g/2,S=b+k/2;e.translate(C,S),e.rotate(this.rotation*Math.PI/180);let w=this.rotation%180===0?1:g/k;e.scale(1/w,w),e.drawImage(y,d,l,p,h,-g/2,-k/2,g,k),e.restore()}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Uint8Array){let 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}},Rt=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Oi=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),ie=class i{constructor(e){this._closed=!1;if(Ot(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(!Oi.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.");let t=e.data.byteLength/(Ft(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let r;if(e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let a=this.numberOfFrames*this.numberOfChannels*Ft(this.format);if(r.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}get microsecondTimestamp(){return Math.trunc(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*this.duration)}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&&!Oi.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.");let t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let a=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(a>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let n=Ft(t),s=$r(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?a:a*this.numberOfChannels)*n}copyTo(e,t){if(!Ge(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Oi.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:r,format:a,frameCount:n,frameOffset:s}=t,o=a??this.format;if(!o)throw new Error("Destination format not determined");let c=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=c)throw new RangeError("frameOffset out of range");let l=n!==void 0?n:c-d;if(l>c-d)throw new RangeError("frameCount out of range");let p=Ft(o),h=$r(o);if(h&&r>=u)throw new RangeError("planeIndex out of range");if(!h&&r!==0)throw new RangeError("planeIndex out of range");let b=(h?l:l*u)*p;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");let g=Y(e),k=bo(o);if(Ot(this._data))if(h)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});else{let y=new ArrayBuffer(l*4),C=new Float32Array(y);this._data.copyTo(C,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});let S=new DataView(y);for(let w=0;w<l;w++){let T=w*p,x=S.getFloat32(w*4,!0);k(g,T,x)}}else{let y=u,C=new Float32Array(l);for(let S=0;S<y;S++){this._data.copyTo(C,{planeIndex:S,frameOffset:d,frameCount:l,format:"f32-planar"});for(let w=0;w<l;w++){let x=(w*y+S)*p;k(g,x,C[w])}}}else{let y=this._data,C=new DataView(y.buffer,y.byteOffset,y.byteLength),S=this.format,w=go(S),T=Ft(S),x=$r(S);for(let E=0;E<l;E++)if(h){let I=E*p,A;x?A=(r*c+(E+d))*T:A=((E+d)*u+r)*T;let _=w(C,A);k(g,I,_)}else for(let I=0;I<u;I++){let _=(E*u+I)*p,te;x?te=(I*c+(E+d))*T:te=((E+d)*u+I)*T;let ke=w(C,te);k(g,_,ke)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Ot(this._data)){let e=new i(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new i({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ot(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Ot(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if($r(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let 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})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}},Ft=i=>{switch(i){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")}},$r=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},go=i=>{switch(i){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},bo=i=>{switch(i){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,$((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,$(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,$(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Ot=i=>typeof AudioData<"u"&&i instanceof AudioData;var lt=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},ve=i=>{if(typeof i!="number"||Number.isNaN(i))throw new TypeError("timestamp must be a number.")},Mi=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let a=await i.determinePacketType(r);return a&&(r.type=a),r}):e,he=class{constructor(e){if(!(e instanceof Qe))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return lt(e),Mi(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return ve(e),lt(t),Mi(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");return lt(t),Mi(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(ve(e),lt(t),!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(lt(t),!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(e!==void 0&&!(e instanceof D))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof D))throw new TypeError("endPacket must be an EncodedPacket.");lt(r);let a=[],{promise:n,resolve:s}=z(),{promise:o,resolve:c}=z(),u=!1,d=!1,l=null,p=[],h=()=>Math.max(2,p.length);return(async()=>{let f=e??await this.getFirstPacket(r);for(;f&&!d&&!(t&&f.sequenceNumber>=t?.sequenceNumber);){if(a.length>h()){({promise:o,resolve:c}=z()),await o;continue}a.push(f),s(),{promise:n,resolve:s}=z(),f=await this.getNextPacket(f,r)}u=!0,s()})().catch(f=>{l||(l=f,s())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(l)throw l;if(a.length>0){let f=a.shift(),b=performance.now();for(p.push(b);p.length>0&&b-p[0]>=1e3;)p.shift();return c(),{value:f,done:!1}}else{if(u)return{value:void 0,done:!0};await n}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},Mt=class{constructor(e,t){this.onSample=e;this.onError=t}},Bt=class{mediaSamplesInRange(e=0,t=1/0){ve(e),ve(t);let r=[],a=!1,n=null,{promise:s,resolve:o}=z(),{promise:c,resolve:u}=z(),d=!1,l=!1,p=!1,h=null;return(async()=>{let f=new Error,b=await this._createDecoder(w=>{if(u(),w.timestamp>=t&&(l=!0),l){w.close();return}n&&(w.timestamp>e?(r.push(n),a=!0):n.close()),w.timestamp>=e&&(r.push(w),a=!0),n=a?null:w,r.length>0&&(o(),{promise:s,resolve:o}=z())},w=>{h||(w.stack=f.stack,h=w,o())}),g=this._createPacketSink(),k=await g.getKeyPacket(e,{verifyKeyPackets:!0})??await g.getFirstPacket();if(!k)return;let y=k,C;if(t<1/0){let w=await g.getPacket(t),T=w?w.type==="key"&&w.timestamp===t?w:await g.getNextKeyPacket(w,{verifyKeyPackets:!0}):null;T&&(C=T)}let S=g.packets(k,C);for(await S.next();y&&!l;){let w=ga(r.length);if(r.length+b.getDecodeQueueSize()>w){({promise:c,resolve:u}=z()),await c;continue}b.decode(y);let T=await S.next();if(T.done)break;y=T.value}await S.return(),p||await b.flush(),b.close(),!a&&n&&r.push(n),d=!0,o()})().catch(f=>{h||(h=f,o())}),{async next(){for(;;){if(p)return{value:void 0,done:!0};if(h)throw h;if(r.length>0){let f=r.shift();return u(),{value:f,done:!1}}else if(!d)await s;else return{value:void 0,done:!0}}},async return(){p=!0,l=!0,u(),o(),n?.close();for(let f of r)f.close();return{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){kn(e);let t=bn(e),r=[],a=[],{promise:n,resolve:s}=z(),{promise:o,resolve:c}=z(),u=!1,d=!1,l=null,p=h=>{a.push(h),s(),{promise:n,resolve:s}=z()};return(async()=>{let h=new Error,f=await this._createDecoder(w=>{if(c(),d){w.close();return}let T=0;for(;r.length>0&&w.timestamp-r[0]>-1e-10;)T++,r.shift();if(T>0)for(let x=0;x<T;x++)p(x<T-1?w.clone():w);else w.close()},w=>{l||(w.stack=h.stack,l=w,s())}),b=this._createPacketSink(),g=null,k=null,y=-1,C=async()=>{m(k);let w=k;for(f.decode(w);w.sequenceNumber<y;){let T=ga(a.length);for(;a.length+f.getDecodeQueueSize()>T&&!d;)({promise:o,resolve:c}=z()),await o;if(d)break;let x=await b.getNextPacket(w);m(x),w=x,f.decode(x)}y=-1},S=async()=>{await f.flush();for(let w=0;w<r.length;w++)p(null);r.length=0};for await(let w of t){if(ve(w),d)break;let T=await b.getPacket(w),x=T&&await b.getKeyPacket(w,{verifyKeyPackets:!0});if(!x){y!==-1&&(await C(),await S()),p(null),g=null;continue}g&&(x.sequenceNumber!==k.sequenceNumber||T.timestamp<g.timestamp)&&(await C(),await S()),r.push(T.timestamp),y=Math.max(T.sequenceNumber,y),g=T,k=x}d||(y!==-1&&await C(),await S()),f.close(),u=!0,s()})().catch(h=>{l||(l=h,s())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(l)throw l;if(a.length>0){let h=a.shift();return m(h!==void 0),c(),{value:h,done:!1}}else if(!u)await n;else return{value:void 0,done:!0}}},async return(){d=!0,c(),s();for(let h of a)h?.close();return{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},ga=i=>i===0?40:8,Bi=class extends Mt{constructor(t,r,a,n,s,o){super(t,r);this.rotation=s;this.timeResolution=o;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new _e;this.customDecoderQueueSize=0;this.sampleQueue=[];let c=d=>{if(this.sampleQueue.length>0&&d.timestamp>=V(this.sampleQueue).timestamp){for(let p of this.sampleQueue)this.finalizeAndEmitSample(p);this.sampleQueue.length=0}let l=F(this.sampleQueue,d.timestamp,p=>p.timestamp);this.sampleQueue.splice(l+1,0,d)},u=yt.find(d=>d.supports(a,n));u?(this.customDecoder=new u,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=d=>{if(!(d instanceof ce))throw new TypeError("The argument passed to onSample must be a VideoSample.");c(d)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new VideoDecoder({output:d=>c(new ce(d)),error:r}),this.decoder.configure(n))}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(t.toEncodedVideoChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await this.decoder.flush());for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close());for(let t of this.sampleQueue)t.close();this.sampleQueue.length=0}},mt=class extends Bt{constructor(e){if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._videoTrack=e}async _createDecoder(e,t){if(!await this._videoTrack.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._videoTrack.codec,a=this._videoTrack.rotation,n=await this._videoTrack.getDecoderConfig(),s=this._videoTrack.timeResolution;return m(r&&n),new Bi(e,t,r,n,a,s)}_createPacketSink(){return new he(this._videoTrack)}async getSample(e){ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},Dt=class{constructor(e,t={}){this._nextCanvasIndex=0;if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[a,n]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=a/n;t.width!==void 0&&t.height===void 0?(a=t.width,n=Math.round(a/s)):t.width===void 0&&t.height!==void 0?(n=t.height,a=Math.round(n*s)):t.width!==void 0&&t.height!==void 0&&(a=t.width,n=t.height),this._videoTrack=e,this._width=a,this._height=n,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new mt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex];t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t)),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext("2d",{alpha:!1});m(r),r.resetTransform();let a,n,s,o;if(this._fit==="fill")a=0,n=0,s=this._width,o=this._height;else{let[d,l]=this._rotation%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],p=this._fit==="contain"?Math.min(this._width/d,this._height/l):Math.max(this._width/d,this._height/l);s=d*p,o=l*p,a=(this._width-s)/2,n=(this._height-o)/2}let c=this._rotation%180===0?1:s/o;r.translate(this._width/2,this._height/2),r.rotate(this._rotation*Math.PI/180),r.scale(1/c,c),r.translate(-this._width/2,-this._height/2),r.drawImage(e.toCanvasImageSource(),a,n,s,o);let u={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),u}async getCanvas(e){ve(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return wt(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return wt(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},Di=class extends Mt{constructor(t,r,a,n){super(t,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new _e;this.customDecoderQueueSize=0;let s=c=>{let u=n.sampleRate;c.setTimestamp(Math.round(c.timestamp*u)/u),t(c)},o=St.find(c=>c.supports(a,n));o?(this.customDecoder=new o,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof ie))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:c=>s(new ie(c)),error:r}),this.decoder.configure(n))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(t.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}},Vi=class extends Mt{constructor(t,r,a){super(t,r);this.decoderConfig=a;this.currentTimestamp=null;m(U.includes(a.codec)),this.codec=a.codec;let{dataType:n,sampleSize:s,littleEndian:o}=G(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:n==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):n==="ulaw"?this.readInputValue=(c,u)=>fa(c.getUint8(u)):n==="alaw"?this.readInputValue=(c,u)=>ha(c.getUint8(u)):m(!1);break;case 2:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:n==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):m(!1);break;case 3:n==="unsigned"?this.readInputValue=(c,u)=>pi(c,u,o)-2**23:n==="signed"?this.readInputValue=(c,u)=>wn(c,u,o):m(!1);break;case 4:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:n==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):n==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):m(!1);break;case 8:n==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):m(!1);break;default:Re(s),m(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,d)=>c.setUint8(u,d+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0);break;default:Re(s),m(!1)}}getDecodeQueueSize(){return 0}decode(t){let r=Y(t.data),a=t.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=a*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),o=new DataView(s);for(let l=0;l<a*this.decoderConfig.numberOfChannels;l++){let p=l*this.inputSampleSize,h=l*this.outputSampleSize,f=this.readInputValue(r,p);this.writeOutputValue(o,h,f)}let c=a/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=t.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let d=new ie({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:a,timestamp:u});this.onSample(d)}async flush(){}close(){}},Ke=class extends Bt{constructor(e){if(!(e instanceof X))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._audioTrack=e}async _createDecoder(e,t){if(!await this._audioTrack.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._audioTrack.codec,a=await this._audioTrack.getDecoderConfig();return m(r&&a),U.includes(a.codec)?new Vi(e,t,a):new Di(e,t,r,a)}_createPacketSink(){return new he(this._audioTrack)}async getSample(e){ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},Ui=class{constructor(e){if(!(e instanceof X))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ke(e)}_audioSampleToWrappedArrayBuffer(e){return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}async getBuffer(e){ve(e);let t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return wt(this._audioSampleSink.samples(e,t),r=>this._audioSampleToWrappedArrayBuffer(r))}buffersAtTimestamps(e){return wt(this._audioSampleSink.samplesAtTimestamps(e),t=>t&&this._audioSampleToWrappedArrayBuffer(t))}};var Qe=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof le}isAudioTrack(){return this instanceof X}get id(){return this._backing.getId()}get languageCode(){return this._backing.getLanguageCode()}get timeResolution(){return this._backing.getTimeResolution()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new he(this),r=1/0,a=-1/0,n=0,s=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),n++,s+=o.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(a-r)).toPrecision(16)):0,averageBitrate:n?Number((8*s/(a-r)).toPrecision(16)):0}}},le=class extends Qe{constructor(e){super(e),this._backing=e}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return m(t!==null),yt.some(a=>a.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");return this.codec===null?null:Hn(this,e)}},X=class extends Qe{constructor(e){super(e),this._backing=e}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return m(t!==null),St.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var de=class{constructor(e,t=1/0){this.source=e;this.maxStorableBytes=t;this.loadedSegments=[];this.loadingSegments=[];this.sourceSizePromise=null;this.nextAge=0;this.totalStoredBytes=0}async loadRange(e,t){if(t=Math.min(t,await this.source.getSize()),e>=t)return;let r=this.loadingSegments.find(c=>c.start<=e&&c.end>=t);if(r){await r.promise;return}let a=F(this.loadedSegments,e,c=>c.start);if(a!==-1)for(let c=a;c<this.loadedSegments.length;c++){let u=this.loadedSegments[c];if(u.start>e)break;if(u.end>=t)return}this.source.onread?.(e,t);let n=this.source._read(e,t),s={start:e,end:t,promise:n};this.loadingSegments.push(s);let o=await n;gn(this.loadingSegments,s),this.insertIntoLoadedSegments(e,o)}rangeIsLoaded(e,t){if(t<=e)return!0;let r=F(this.loadedSegments,e,a=>a.start);if(r===-1)return!1;for(let a=r;a<this.loadedSegments.length;a++){let n=this.loadedSegments[a];if(n.start>e)break;if(n.end>=t)return!0}return!1}insertIntoLoadedSegments(e,t){let r={start:e,end:e+t.byteLength,bytes:t,view:new DataView(t.buffer),age:this.nextAge++},a=F(this.loadedSegments,e,n=>n.start);(a===-1||this.loadedSegments[a].start<r.start)&&a++,this.loadedSegments.splice(a,0,r),this.totalStoredBytes+=t.byteLength;for(let n=a+1;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>=r.end)break;r.start<=s.start&&s.end<=r.end&&(this.loadedSegments.splice(n,1),n--)}for(;this.totalStoredBytes>this.maxStorableBytes&&this.loadedSegments.length>1;){let n=null,s=-1;for(let o=0;o<this.loadedSegments.length;o++){let c=this.loadedSegments[o];(!n||c.age<n.age)&&(n=c,s=o)}m(n),this.totalStoredBytes-=n.bytes.byteLength,this.loadedSegments.splice(s,1)}}getViewAndOffset(e,t){let r=F(this.loadedSegments,e,n=>n.start),a=null;if(r!==-1)for(let n=r;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>e)break;if(t<=s.end){a=s;break}}if(!a)throw new Error(`No segment loaded for range [${e}, ${t}).`);return a.age=this.nextAge++,{view:a.view,offset:a.bytes.byteOffset+e-a.start}}forgetRange(e,t){if(t<=e)return;let r=F(this.loadedSegments,e,n=>n.start);if(r===-1)return;let a=this.loadedSegments[r];a.start!==e||a.end!==t||(this.loadedSegments.splice(r,1),this.totalStoredBytes-=a.bytes.byteLength)}};var $e=class{constructor(e){this.reader=e;this.pos=0;this.littleEndian=!0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,this.littleEndian)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,this.littleEndian)}readU64(){let e,t;return this.littleEndian?(e=this.readU32(),t=this.readU32()):(t=this.readU32(),e=this.readU32()),t*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}};var qr=class extends oe{constructor(t){super(t);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.tracks=[];this.metadataReader=new $e(t._mainReader),this.chunkReader=new $e(new de(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.metadataReader.reader.source.getSize(),r=this.metadataReader.readAscii(4);this.metadataReader.littleEndian=r!=="RIFX";let a=r==="RF64",n=this.metadataReader.readU32(),s=a?t:Math.min(n+8,t);if(this.metadataReader.readAscii(4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");this.metadataReader.pos=12;let c=0,u=null;for(;this.metadataReader.pos<s;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+8);let l=this.metadataReader.readAscii(4),p=this.metadataReader.readU32(),h=this.metadataReader.pos;if(a&&c===0&&l!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(l==="fmt ")await this.parseFmtChunk(p);else if(l==="data")u??=p,this.dataStart=this.metadataReader.pos,this.dataSize=Math.min(u,s-this.dataStart);else if(l==="ds64"){let f=this.metadataReader.readU64();u=this.metadataReader.readU64(),s=Math.min(f+8,t)}this.metadataReader.pos=h+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new X(new zi(this)))})()}async parseFmtChunk(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+t);let r=this.metadataReader.readU16(),a=this.metadataReader.readU16(),n=this.metadataReader.readU32();this.metadataReader.pos+=4;let s=this.metadataReader.readU16(),o;if(t===14?o=8:o=this.metadataReader.readU16(),t>=18&&r!==357){let c=this.metadataReader.readU16(),u=t-18;if(Math.min(u,c)>=22&&r===65534){this.metadataReader.pos+=6;let l=this.metadataReader.readBytes(16);r=l[0]|l[1]<<8}}(r===7||r===6)&&(o=8),this.audioInfo={format:r,numberOfChannels:a,sampleRate:n,sampleSizeInBytes:Math.ceil(o/8),blockSizeInBytes:s}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===3&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){return await this.readMetadata(),m(this.audioInfo),this.dataSize/this.audioInfo.blockSizeInBytes/this.audioInfo.sampleRate}async getTracks(){return await this.readMetadata(),this.tracks}},ft=2048,zi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(m(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}computeDuration(){return this.demuxer.computeDuration()}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getLanguageCode(){return Z}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){m(this.demuxer.audioInfo);let r=e*ft*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let a=Math.min(ft*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r),n;if(t.metadataOnly)n=ee;else{let c=ft*this.demuxer.audioInfo.blockSizeInBytes,u=Math.ceil(2**19/c)*c,d=Math.floor(r/u)*u,l=d+u;await this.demuxer.chunkReader.reader.loadRange(this.demuxer.dataStart+d,this.demuxer.dataStart+l),this.demuxer.chunkReader.pos=this.demuxer.dataStart+r,n=this.demuxer.chunkReader.readBytes(a)}let s=e*ft/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return new D(n,"key",s,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){m(this.demuxer.audioInfo);let r=Math.floor(e*this.demuxer.audioInfo.sampleRate/ft);return this.getPacketAtIndex(r,t)}getNextPacket(e,t){m(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ft);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var jr=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}};var Gr=class extends se{constructor(t,r){super(t);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.format=r,this.writer=t._writer,this.riffWriter=new jr(t._writer),this.isRf64=!!r._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{if(this.headerWritten||(Fe(a),m(a),m(a.decoderConfig),this.writeHeader(t,a.decoderConfig),this.sampleRate=a.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(t,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(t,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let a,n=t.source._codec,s=G(n);s.dataType==="ulaw"?a=7:s.dataType==="alaw"?a=6:s.dataType==="float"?a=3:a=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(a),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.format._options.onHeader){let{data:d,start:l}=this.writer.stopTrackingWrites();this.format._options.onHeader(d,l)}}async finalize(){let t=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(this.writer.seek(20),this.riffWriter.writeU64(r-8),this.writer.seek(28),this.riffWriter.writeU64(this.dataSize),this.writer.seek(36),this.riffWriter.writeU64(this.sampleCount)):(this.writer.seek(4),this.riffWriter.writeU32(r-8),this.writer.seek(40),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(r),t()}};var ge=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>q.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>j.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ae.includes(e))}_codecUnsupportedHint(e){return""}},Vt=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError('options.fastStart, when provided, must be false, "in-memory", 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.");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 Rr(e,this)}},Xr=class extends Vt{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...q,...Ce,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ae]}_codecUnsupportedHint(e){return new it().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},it=class extends Vt{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...q,...j]}_codecUnsupportedHint(e){return new Xr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},Ut=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Br(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...q,...Ce,...U.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...ae]}get supportsVideoRotationMetadata(){return!1}},st=class extends Ut{getSupportedCodecs(){return[...q.filter(e=>["vp8","vp9","av1"].includes(e)),...j.filter(e=>["opus","vorbis"].includes(e)),...ae]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Ut().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Ni=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Nr(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}},Wi=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Gr(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...U.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}},Li=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Qr(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:1/0},subtitle:{min:0,max:0},total:{min:1,max:2**32}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...j.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}};var pt=class{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.")}_start(){}async _flushAndClose(){}close(){if(this._closingPromise)return;let 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(),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForClose(){return this._closingPromise?this._closingPromise:this._flushAndClose()}},Pe=class extends pt{constructor(t){super();this._connectedTrack=null;if(!q.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${q.join(", ")}.`);this._codec=t}},zt=class extends Pe{constructor(e){super(e)}add(e,t){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},ji=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!q.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${q.join(", ")}.`);if(!(i.bitrate instanceof H)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(i.latencyMode!==void 0&&!["quality","realtime"].includes(i.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},Nt=class{constructor(e,t){this.source=e;this.encodingConfig=t;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.lastWidth=null;this.lastHeight=null;this.customEncoder=null;this.customEncoderCallSerializer=new _e;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t,r){if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastWidth!==null&&this.lastHeight!==null){if(e.codedWidth!==this.lastWidth||e.codedHeight!==this.lastHeight)throw new Error(`Video sample size must remain constant. Expected ${this.lastWidth}x${this.lastHeight}, got ${e.codedWidth}x${e.codedHeight}.`)}else this.lastWidth=e.codedWidth,this.lastHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);let a=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/a),s={...r,keyFrame:r?.keyFrame||a===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;let o=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,s)).then(()=>{this.customEncoderQueueSize--,t&&e.close()}).catch(c=>{this.encoderError??=c});this.customEncoderQueueSize>=4&&await o}else{m(this.encoder);let o=e.toVideoFrame();this.encoder.encode(o,s),o.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}async ensureEncoder(e){if(!this.encoder)return this.ensureEncoderPromise=(async()=>{let t=e.codedWidth,r=e.codedHeight,a=this.encodingConfig.bitrate instanceof H?this.encodingConfig.bitrate._toVideoBitrate(this.encodingConfig.codec,t,r):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??nr(this.encodingConfig.codec,t,r,a),width:t,height:r,bitrate:a,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.encodingConfig.latencyMode,...sr(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=Ze.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof D))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(!(await VideoEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.width}x${n.height}) is not supported by this browser. Consider using another codec or changing your video parameters.`);this.encoder=new VideoEncoder({output:(c,u)=>{let d=D.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(d,u),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,d,u)},error:c=>{this.encoderError??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(){this.checkForEncoderError(),this.customEncoder?(this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError.stack=new Error().stack,this.encoderError}},ht=class extends Pe{constructor(e){ji(e),super(e.codec),this._encoder=new Nt(this,e)}add(e,t){if(!(e instanceof ce))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(){return this._encoder.flushAndClose()}},Hi=class extends Pe{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ji(t),super(t.codec),this._encoder=new Nt(this,t),this._canvas=e}add(e,t=0,r){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let a=new ce(this._canvas,{timestamp:e,duration:t});return this._encoder.add(a,!0,r)}_flushAndClose(){return this._encoder.flushAndClose()}},Ki=class extends Pe{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");ji(r),r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._encoder=new Nt(this,r),this._track=t}_start(){this._abortController=new AbortController;let t=!1,r=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:n=>{if(t||(ba(this,n),t=!0),this._encoder.getQueueSize()>=4){n.close();return}this._encoder.add(new ce(n),!0).catch(s=>{throw this._abortController?.abort(),s})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(n=>{n instanceof DOMException&&n.name==="AbortError"||console.error("Pipe error:",n)})}async _flushAndClose(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flushAndClose()}},Ee=class extends pt{constructor(t){super();this._connectedTrack=null;if(!j.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${j.join(", ")}.`);this._codec=t}},Wt=class extends Ee{constructor(e){super(e)}add(e,t){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Gi=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!j.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${j.join(", ")}.`);if(i.bitrate===void 0&&(!U.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(i.bitrate!==void 0&&!(i.bitrate instanceof H)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},Lt=class{constructor(e,t){this.source=e;this.encodingConfig=t;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new _e;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t){if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized),this.customEncoder){this.customEncoderQueueSize++;let r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e)).then(()=>{this.customEncoderQueueSize--,t&&e.close()}).catch(a=>{this.encoderError??=a});this.customEncoderQueueSize>=4&&await r,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{m(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(a=>this.encoder.addEventListener("dequeue",a,{once:!0})),await this.muxer.mutex.currentPromise}}async doPcmEncoding(e,t){m(this.outputSampleSize),m(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:a,sampleRate:n,timestamp:s}=e,o=2048,c=[];for(let p=0;p<a;p+=o){let h=Math.min(o,e.numberOfFrames-p),f=h*r*this.outputSampleSize,b=new ArrayBuffer(f),g=new DataView(b);c.push({frameCount:h,view:g})}let u=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let p=0;p<r;p++){e.copyTo(d,{planeIndex:p,format:"f32-planar"});for(let h=0;h<c.length;h++){let{frameCount:f,view:b}=c[h];for(let g=0;g<f;g++)this.writeOutputValue(b,(g*r+p)*this.outputSampleSize,d[h*o+g])}}t&&e.close();let l={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:n}};for(let p=0;p<c.length;p++){let{frameCount:h,view:f}=c[p],b=f.buffer,g=p*o,k=new D(new Uint8Array(b),"key",s+g/n,h/n);this.encodingConfig.onEncodedPacket?.(k,l),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,k,l)}}ensureEncoder(e){if(!this.encoderInitialized)return this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,a=this.encodingConfig.bitrate instanceof H?this.encodingConfig.bitrate._toAudioBitrate(this.encodingConfig.codec):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??ar(this.encodingConfig.codec,t,r),numberOfChannels:t,sampleRate:r,bitrate:a,...or(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=Je.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof D))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else if(U.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,u)=>{let d=D.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(d,u),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,u)},error:c=>{this.encoderError??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:a}=G(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint8(s,$((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,s,o)=>{n.setInt8(s,$(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,s,o)=>{let c=$(Math.floor(o*32767),-32768,32767);n.setUint8(s,ma(c))}:t==="alaw"?this.writeOutputValue=(n,s,o)=>{let c=$(Math.floor(o*32767),-32768,32767);n.setUint8(s,pa(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint16(s,$((o+1)*32767.5,0,65535),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt16(s,$(Math.round(o*32767),-32768,32767),a):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,s,o)=>hi(n,s,$((o+1)*83886075e-1,0,16777215),a):t==="signed"?this.writeOutputValue=(n,s,o)=>Tn(n,s,$(Math.round(o*8388607),-8388608,8388607),a):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint32(s,$((o+1)*21474836475e-1,0,4294967295),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt32(s,$(Math.round(o*2147483647),-2147483648,2147483647),a):t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat32(s,o,a):m(!1);break;case 8:t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat64(s,o,a):m(!1);break;default:Re(r),m(!1)}}async flushAndClose(){this.checkForEncoderError(),this.customEncoder?(this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError.stack=new Error().stack,this.encoderError}},gt=class extends Ee{constructor(e){Gi(e),super(e.codec),this._encoder=new Lt(this,e)}add(e){if(!(e instanceof ie))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(){return this._encoder.flushAndClose()}},Qi=class extends Ee{constructor(t){Gi(t);super(t.codec);this._accumulatedFrameCount=0;this._encoder=new Lt(this,t)}add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=64*1024*1024,a=t.numberOfChannels,n=t.sampleRate,s=t.length,o=Math.floor(r/a),c=0,u=s,d=[];for(;u>0;){let l=Math.min(o,u),p=new Float32Array(a*l);for(let f=0;f<a;f++)t.copyFromChannel(p.subarray(f*l,f*l+l),f,c);let h=new ie({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:a,timestamp:(this._accumulatedFrameCount+c)/n,data:p});d.push(this._encoder.add(h,!0)),c+=l,u-=l}return this._accumulatedFrameCount+=s,Promise.all(d)}_flushAndClose(){return this._encoder.flushAndClose()}},$i=class extends Ee{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");Gi(r);super(r.codec);this._abortController=null;this._encoder=new Lt(this,r),this._track=t}_start(){this._abortController=new AbortController;let t=!1,r=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:n=>{if(t||(ba(this,n),t=!0),this._encoder.getQueueSize()>=4){n.close();return}this._encoder.add(new ie(n),!0).catch(s=>{throw this._abortController?.abort(),s})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(n=>{n instanceof DOMException&&n.name==="AbortError"||console.error("Pipe error:",n)})}async _flushAndClose(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flushAndClose()}},ba=(i,e)=>{let t=e.timestamp/1e6;m(i._connectedTrack);let r=i._connectedTrack.output._muxer;r.firstMediaStreamTimestamp===null&&(r.firstMediaStreamTimestamp=t),i._timestampOffset=-Math.min(r.firstMediaStreamTimestamp,t)},bt=class extends pt{constructor(t){super();this._connectedTrack=null;if(!ae.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${ae.join(", ")}.`);this._codec=t}},qi=class extends bt{constructor(e){super(e),this._parser=new br({codec:e,output:(t,r)=>this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,t,r)})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._ensureValidAdd(),this._parser.parse(e),this._connectedTrack.output._muxer.mutex.currentPromise}};var ka=["video","audio","subtitle"],Xi=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!Ye(i.languageCode))throw new TypeError("metadata.languageCode must be a three-letter, ISO 639-2/T language code.")},Ht=class{constructor(e){this.state="pending";this._tracks=[];this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new ne;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ge))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ze))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof Pe))throw new TypeError("source must be a VideoSource.");if(Xi(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof Ee))throw new TypeError("source must be an AudioSource.");Xi(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof bt))throw new TypeError("source must be a SubtitleSource.");Xi(t),this._addTrack("subtitle",e,t)}_addTrack(e,t,r){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");let a=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((u,d)=>u+(d.type===e?1:0),0),s=a[e].max;if(n===s)throw new Error(s===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track${s===1?"":"s"}.`);let o=a.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if(c.type==="video"){let u=this.format.getSupportedVideoCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let u=this.format.getSupportedAudioCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let u=this.format.getSupportedSubtitleCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),t._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let r of ka){let a=this._tracks.reduce((s,o)=>s+(o.type===r?1:0),0),n=e[r].min;if(a<n)throw new Error(n===e[r].max?`${this.format._name} requires exactly ${n} ${r} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${r} track${n===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let r=await this._mutex.acquire();await this._muxer.start();for(let a of this._tracks)a.source._start();r()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire(),t=this._tracks.map(r=>r.source._flushOrWaitForClose());await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire(),t=this._tracks.map(r=>r.source._flushOrWaitForClose());await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};var Ie=class{constructor(){this._sizePromise=null;this.onread=null}getSize(){return this._sizePromise??=this._retrieveSize()}},Yi=class extends Ie{constructor(e){if(!(e instanceof ArrayBuffer)&&!(e instanceof Uint8Array))throw new TypeError("buffer must be an ArrayBuffer or Uint8Array.");super(),this._bytes=e instanceof Uint8Array?e:new Uint8Array(e)}async _read(e,t){return this._bytes.subarray(e,t)}async _retrieveSize(){return this._bytes.byteLength}},Zi=class extends Ie{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");super(),this._options=e}async _read(e,t){return this._options.read(e,t)}async _retrieveSize(){return this._options.getSize()}},Ji=class extends Ie{constructor(e){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");super(),this._blob=e}async _read(e,t){let a=await this._blob.slice(e,t).arrayBuffer();return new Uint8Array(a)}async _retrieveSize(){return this._blob.size}},en=class extends Ie{constructor(t,r={}){if(typeof t!="string"&&!(t instanceof URL))throw new TypeError("url must be a string or URL.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");super();this._fullData=null;this._url=t,this._options=r}async _makeRequest(t){let r={};t&&(r.Range=`bytes=${t.start}-${t.end-1}`);let a=await gi(this._url,Jt(this._options.requestInit??{},{method:"GET",headers:r}),this._options.getRetryDelay??(()=>null));if(!a.ok)throw new Error(`Error fetching ${this._url}: ${a.status} ${a.statusText}`);let n=await a.arrayBuffer();return t||(this._fullData=n),{response:n,statusCode:a.status}}async _read(t,r){if(this._fullData)return new Uint8Array(this._fullData,t,r-t);let{response:a,statusCode:n}=await this._makeRequest({start:t,end:r});return n===200?new Uint8Array(a).subarray(t,r):new Uint8Array(a)}async _retrieveSize(){if(this._fullData)return this._fullData.byteLength;let t=await gi(this._url,Jt(this._options.requestInit??{},{method:"GET",headers:{Range:"bytes=0-0"}}),this._options.getRetryDelay??(()=>null));if(t.status===206){let a=t.headers.get("Content-Range");if(a){let n=a.match(/bytes \d+-\d+\/(\d+)/);if(n&&n[1])return parseInt(n[1],10)}}let{response:r}=await this._makeRequest();return r.byteLength}};var wa=8,Kt=16,qe=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos++,e.getUint8(t)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readI16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getInt16(t,!1)}readU24(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+3);this.pos+=3;let r=e.getUint16(t,!1),a=e.getUint8(t+2);return r*256+a}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!1)}readU64(){let e=this.readU32(),t=this.readU32();return e*4294967296+t}readI64(){let e=this.readI32(),t=this.readU32();return e*4294967296+t}readF64(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+8);return this.pos+=8,e.getFloat64(t,!1)}readFixed_16_16(){return this.readI32()/65536}readFixed_2_30(){return this.readI32()/1073741824}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readIsomVariableInteger(){let e=0;for(let t=0;t<4;t++){e<<=7;let r=this.readU8();if(e|=r&127,(r&128)===0)break}return e}readBoxHeader(){let e=this.readU32(),t=this.readAscii(4),r=8;return e===1&&(e=this.readU64(),r=16),{name:t,totalSize:e,headerSize:r,contentSize:e-r}}};var Yr=class extends oe{constructor(t){super(t);this.currentTrack=null;this.tracks=[];this.metadataPromise=null;this.movieTimescale=-1;this.movieDurationInTimescale=-1;this.isQuickTime=!1;this.isFragmented=!1;this.fragmentTrackDefaults=[];this.fragments=[];this.currentFragment=null;this.fragmentLookupMutex=new ne;this.metadataReader=new qe(t._mainReader),this.chunkReader=new qe(new de(t.source,64*2**20))}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(t=>t.inputTrack)}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Ar({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:t.filter(Boolean)})}readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.metadataReader.reader.source.getSize();for(;this.metadataReader.pos<t;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Kt);let r=this.metadataReader.pos,a=this.metadataReader.readBoxHeader();if(a.name==="ftyp"){let n=this.metadataReader.readAscii(4);this.isQuickTime=n==="qt "}else if(a.name==="moov"){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+a.contentSize),this.readContiguousBoxes(a.contentSize);for(let n of this.tracks){let s=n.editListPreviousSegmentDurations/this.movieTimescale;n.editListOffset-=Math.round(s*n.timescale)}break}this.metadataReader.pos=r+a.totalSize}if(this.isFragmented){await this.metadataReader.reader.loadRange(t-4,t),this.metadataReader.pos=t-4;let r=this.metadataReader.readU32(),a=t-r;if(a>=0&&a<t){await this.metadataReader.reader.loadRange(a,t),this.metadataReader.pos=a;let n=this.metadataReader.readBoxHeader();n.name==="mfra"&&this.readContiguousBoxes(n.contentSize)}}})()}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(t.sampleTable=r,this.metadataReader.pos=t.sampleTableByteOffset,this.currentTrack=t,this.traverseBox(),this.currentTrack=null,t.info?.type==="audio"&&t.info.codec&&U.includes(t.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(t.info?.type==="audio");let n=G(t.info.codec),s=[],o=[];for(let c=0;c<r.sampleToChunk.length;c++){let u=r.sampleToChunk[c],d=r.sampleToChunk[c+1],l=(d?d.startChunkIndex:r.chunkOffsets.length)-u.startChunkIndex;for(let p=0;p<l;p++){let h=u.startSampleIndex+p*u.samplesPerChunk,f=h+u.samplesPerChunk,b=F(r.sampleTimingEntries,h,E=>E.startIndex),g=r.sampleTimingEntries[b],k=F(r.sampleTimingEntries,f,E=>E.startIndex),y=r.sampleTimingEntries[k],C=g.startDecodeTimestamp+(h-g.startIndex)*g.delta,w=y.startDecodeTimestamp+(f-y.startIndex)*y.delta-C,T=V(s);T&&T.delta===w?T.count++:s.push({startIndex:u.startChunkIndex+p,startDecodeTimestamp:C,count:1,delta:w});let x=u.samplesPerChunk*n.sampleSize*t.info.numberOfChannels;o.push(x)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=s,r.sampleSizes=o}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let n of r.sampleTimingEntries)for(let s=0;s<n.count;s++)r.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+s*n.delta,sampleIndex:n.startIndex+s});for(let n of r.sampleCompositionTimeOffsets)for(let s=0;s<n.count;s++){let o=n.startIndex+s,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}r.presentationTimestamps.sort((n,s)=>n.presentationTimestamp-s.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let n=0;n<r.presentationTimestamps.length;n++)r.presentationTimestampIndexMap[r.presentationTimestamps[n].sampleIndex]=n}return r}async readFragment(){let t=this.metadataReader.pos;await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Kt);let r=this.metadataReader.readBoxHeader();m(r.name==="moof");let a=this.metadataReader.pos;await this.metadataReader.reader.loadRange(a,a+r.contentSize),this.metadataReader.pos=t,this.traverseBox();let n=W(this.fragments,t,o=>o.moofOffset);m(n!==-1);let s=this.fragments[n];m(s.moofOffset===t),this.metadataReader.reader.forgetRange(a,a+r.contentSize);for(let[o,c]of s.trackData){if(c.startTimestampIsFinal)continue;let u=this.tracks.find(f=>f.id===o);this.metadataReader.pos=0;let d=null,l=null,p=F(u.fragments,t-1,f=>f.moofOffset);p!==-1&&(d=u.fragments[p],l=d,this.metadataReader.pos=d.moofOffset+d.moofSize);let h=this.metadataReader.pos===0;for(;this.metadataReader.pos<t;){if(d?.nextFragment)d=d.nextFragment,this.metadataReader.pos=d.moofOffset+d.moofSize;else{await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Kt);let f=this.metadataReader.pos,b=this.metadataReader.readBoxHeader();if(b.name==="moof"){let g=W(this.fragments,f,y=>y.moofOffset),k;g===-1?(this.metadataReader.pos=f,k=await this.readFragment()):k=this.fragments[g],d&&(d.nextFragment=k),d=k,h&&(k.isKnownToBeFirstFragment=!0,h=!1)}this.metadataReader.pos=f+b.totalSize}d&&d.trackData.has(o)&&(l=d)}if(l){let f=l.trackData.get(o);m(f.startTimestampIsFinal),ya(c,f.endTimestamp)}c.startTimestampIsFinal=!0}return s}readContiguousBoxes(t){let r=this.metadataReader.pos;for(;this.metadataReader.pos-r<=t-wa;)this.traverseBox()}traverseBox(){let t=this.metadataReader.pos,r=this.metadataReader.readBoxHeader(),a=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(r.contentSize);break;case"mvhd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3,n===1?(this.metadataReader.pos+=16,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU64()):(this.metadataReader.pos+=8,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU32())}break;case"trak":{let n={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=n,this.readContiguousBoxes(r.contentSize),n.id!==-1&&n.timescale!==-1&&n.info!==null){if(n.info.type==="video"&&n.info.width!==-1){let s=n;n.inputTrack=new le(new tn(s)),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){let s=n;n.inputTrack=new X(new rn(s)),this.tracks.push(n)}}this.currentTrack=null}break;case"tkhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();if(!((this.metadataReader.readU24()&1)!==0))break;if(s===0)this.metadataReader.pos+=8,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU32();else if(s===1)this.metadataReader.pos+=16,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU64();else throw new Error(`Incorrect track header version ${s}.`);this.metadataReader.pos+=2*4+2+2+2+2;let u=[this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30()],d=Ae(Tt(yo(u),90));m(d===0||d===90||d===180||d===270),n.rotation=d}break;case"elst":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=!1,c=0,u=this.metadataReader.readU32();for(let d=0;d<u;d++){let l=s===1?this.metadataReader.readU64():this.metadataReader.readU32(),p=s===1?this.metadataReader.readI64():this.metadataReader.readI32(),h=this.metadataReader.readFixed_16_16();if(l!==0){if(o){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){c+=l;continue}if(h!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}n.editListPreviousSegmentDurations=c,n.editListOffset=p,o=!0}}}break;case"mdhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3,s===0?(this.metadataReader.pos+=8,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU32()):s===1&&(this.metadataReader.pos+=16,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU64());let o=this.metadataReader.readU16();if(o>0){n.languageCode="";for(let c=0;c<3;c++)n.languageCode=String.fromCharCode(96+(o&31))+n.languageCode,o>>=5;Ye(n.languageCode)||(n.languageCode=Z)}}break;case"hdlr":{let n=this.currentTrack;m(n),this.metadataReader.pos+=8;let s=this.metadataReader.readAscii(4);s==="vide"?n.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:s==="soun"&&(n.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let n=this.currentTrack;m(n),n.sampleTableByteOffset=t,this.readContiguousBoxes(r.contentSize)}break;case"stsd":{let n=this.currentTrack;if(m(n),n.info===null||n.sampleTable)break;let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=this.metadataReader.readU32();for(let c=0;c<o;c++){let u=this.metadataReader.pos,d=this.metadataReader.readBoxHeader(),l=d.name.toLowerCase();if(n.info.type==="video")l==="avc1"?n.info.codec="avc":l==="hvc1"||l==="hev1"?n.info.codec="hevc":l==="vp08"?n.info.codec="vp8":l==="vp09"?n.info.codec="vp9":l==="av01"?n.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),this.metadataReader.pos+=6*1+2+2+2+3*4,n.info.width=this.metadataReader.readU16(),n.info.height=this.metadataReader.readU16(),this.metadataReader.pos+=50,this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos);else{l==="mp4a"||(l==="opus"?n.info.codec="opus":l==="flac"?n.info.codec="flac":l==="twos"||l==="sowt"||l==="raw "||l==="in24"||l==="in32"||l==="fl32"||l==="fl64"||l==="lpcm"||l==="ipcm"||l==="fpcm"||(l==="ulaw"?n.info.codec="ulaw":l==="alaw"?n.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),this.metadataReader.pos+=6*1+2;let p=this.metadataReader.readU16();this.metadataReader.pos+=3*2;let h=this.metadataReader.readU16(),f=this.metadataReader.readU16();this.metadataReader.pos+=2*2;let b=this.metadataReader.readU32()/65536;if(s===0&&p>0){if(p===1)this.metadataReader.pos+=4,f=8*this.metadataReader.readU32(),this.metadataReader.pos+=2*4;else if(p===2){this.metadataReader.pos+=4,b=this.metadataReader.readF64(),h=this.metadataReader.readU32(),this.metadataReader.pos+=4,f=this.metadataReader.readU32();let g=this.metadataReader.readU32();if(this.metadataReader.pos+=2*4,l==="lpcm"){let k=f+7>>3,y=!!(g&1),C=!!(g&2),S=g&4?-1:0;f>0&&f<=64&&(y?f===32&&(n.info.codec=C?"pcm-f32be":"pcm-f32"):S&1<<k-1?k===1?n.info.codec="pcm-s8":k===2?n.info.codec=C?"pcm-s16be":"pcm-s16":k===3?n.info.codec=C?"pcm-s24be":"pcm-s24":k===4&&(n.info.codec=C?"pcm-s32be":"pcm-s32"):k===1&&(n.info.codec="pcm-u8")),n.info.codec===null&&console.warn("Unsupported PCM format.")}}}n.info.numberOfChannels=h,n.info.sampleRate=b,l==="twos"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${f} for codec 'twos'.`),n.info.codec=null):l==="sowt"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${f} for codec 'sowt'.`),n.info.codec=null):l==="raw "?n.info.codec="pcm-u8":l==="in24"?n.info.codec="pcm-s24be":l==="in32"?n.info.codec="pcm-s32be":l==="fl32"?n.info.codec="pcm-f32be":l==="fl64"?n.info.codec="pcm-f64be":l==="ipcm"?n.info.codec="pcm-s16be":l==="fpcm"&&(n.info.codec="pcm-f32be"),this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos)}}}break;case"avcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"hvcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"vpcC":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8(),o=this.metadataReader.readU8(),c=this.metadataReader.readU8(),u=c>>4,d=c>>1&7,l=c&1,p=this.metadataReader.readU8(),h=this.metadataReader.readU8(),f=this.metadataReader.readU8();n.info.vp9CodecInfo={profile:s,level:o,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:l,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:f}}break;case"av1C":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=s>>5,c=s&31,u=this.metadataReader.readU8(),d=u>>7,l=u>>6&1,p=u>>5&1,h=u>>4&1,f=u>>3&1,b=u>>2&1,g=u&3,k=o==2&&l?p?12:10:l?10:8;n.info.av1CodecInfo={profile:o,level:c,tier:d,bitDepth:k,monochrome:h,chromaSubsamplingX:f,chromaSubsamplingY:b,chromaSamplePosition:g}}break;case"colr":{let n=this.currentTrack;if(m(n&&n.info?.type==="video"),this.metadataReader.readAscii(4)!=="nclx")break;let o=this.metadataReader.readU16(),c=this.metadataReader.readU16(),u=this.metadataReader.readU16(),d=!!(this.metadataReader.readU8()&128);n.info.colorSpace={primaries:jt[o],transfer:Gt[c],matrix:Xt[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(r.contentSize);break;case"esds":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8();m(s===3),this.metadataReader.readIsomVariableInteger(),this.metadataReader.pos+=2;let o=this.metadataReader.readU8(),c=(o&128)!==0,u=(o&64)!==0,d=(o&32)!==0;if(c&&(this.metadataReader.pos+=2),u){let b=this.metadataReader.readU8();this.metadataReader.pos+=b}d&&(this.metadataReader.pos+=2);let l=this.metadataReader.readU8();m(l===4);let p=this.metadataReader.readIsomVariableInteger(),h=this.metadataReader.pos,f=this.metadataReader.readU8();if(f===64||f===103?(n.info.codec="aac",n.info.aacCodecInfo={isMpeg2:f===103}):f===105||f===107?n.info.codec="mp3":f===221?n.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${f}) - discarding track.`),this.metadataReader.pos+=12,p>this.metadataReader.pos-h){let b=this.metadataReader.readU8();m(b===5);let g=this.metadataReader.readIsomVariableInteger();if(n.info.codecDescription=this.metadataReader.readBytes(g),n.info.codec==="aac"){let k=bi(n.info.codecDescription);k.numberOfChannels!==null&&(n.info.numberOfChannels=k.numberOfChannels),k.sampleRate!==null&&(n.info.sampleRate=k.sampleRate)}}}break;case"enda":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.readU16()&255&&(n.info.codec==="pcm-s16be"?n.info.codec="pcm-s16":n.info.codec==="pcm-s24be"?n.info.codec="pcm-s24":n.info.codec==="pcm-s32be"?n.info.codec="pcm-s32":n.info.codec==="pcm-f32be"?n.info.codec="pcm-f32":n.info.codec==="pcm-f64be"&&(n.info.codec="pcm-f64"))}break;case"pcmC":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let o=!!(this.metadataReader.readU8()&1),c=this.metadataReader.readU8();n.info.codec==="pcm-s16be"?o?c===16?n.info.codec="pcm-s16":c===24?n.info.codec="pcm-s24":c===32?n.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):c===16?n.info.codec="pcm-s16be":c===24?n.info.codec="pcm-s24be":c===32?n.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):n.info.codec==="pcm-f32be"&&(o?c===32?n.info.codec="pcm-f32":c===64?n.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null):c===32?n.info.codec="pcm-f32be":c===64?n.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null));break}case"dOps":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=this.metadataReader.readU16(),c=this.metadataReader.readU32(),u=this.metadataReader.readI16(),d=this.metadataReader.readU8(),l;d!==0?l=this.metadataReader.readBytes(2+s):l=new Uint8Array(0);let p=new Uint8Array(19+l.byteLength),h=new DataView(p.buffer);h.setUint32(0,1332770163,!1),h.setUint32(4,1214603620,!1),h.setUint8(8,1),h.setUint8(9,s),h.setUint16(10,o,!0),h.setUint32(12,c,!0),h.setInt16(16,u,!0),h.setUint8(18,d),p.set(l,19),n.info.codecDescription=p,n.info.numberOfChannels=s,n.info.sampleRate=c}break;case"dfLa":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=127,o=128,c=this.metadataReader.pos;for(;this.metadataReader.pos<a;){let h=this.metadataReader.readU8(),f=this.metadataReader.readU24();if((h&s)===0){this.metadataReader.pos+=10;let g=this.metadataReader.readU32(),k=g>>>12,y=(g>>9&7)+1;n.info.sampleRate=k,n.info.numberOfChannels=y,this.metadataReader.pos+=20}else this.metadataReader.pos+=f;if(h&o)break}let u=this.metadataReader.pos;this.metadataReader.pos=c;let d=this.metadataReader.readBytes(u-c),l=new Uint8Array(4+d.byteLength);new DataView(l.buffer).setUint32(0,1716281667,!1),l.set(d,4),n.info.codecDescription=l}break;case"stts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0,c=0;for(let u=0;u<s;u++){let d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleTimingEntries.push({startIndex:o,startDecodeTimestamp:c,count:d,delta:l}),o+=d,c+=d*l}}break;case"ctts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0;for(let c=0;c<s;c++){let u=this.metadataReader.readU32(),d=this.metadataReader.readI32();n.sampleTable.sampleCompositionTimeOffsets.push({startIndex:o,count:u,offset:d}),o+=u}}break;case"stsz":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=this.metadataReader.readU32();if(s===0)for(let c=0;c<o;c++){let u=this.metadataReader.readU32();n.sampleTable.sampleSizes.push(u)}else n.sampleTable.sampleSizes.push(s)}break;case"stz2":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,this.metadataReader.pos+=3;let s=this.metadataReader.readU8(),o=this.metadataReader.readU32(),c=this.metadataReader.readBytes(Math.ceil(o*s/8)),u=new K(c);for(let d=0;d<o;d++){let l=u.readBits(s);n.sampleTable.sampleSizes.push(l)}}break;case"stss":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,n.sampleTable.keySampleIndices=[];let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32()-1;n.sampleTable.keySampleIndices.push(c)}}break;case"stsc":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let c=0;c<s;c++){let u=this.metadataReader.readU32()-1,d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:l})}let o=0;for(let c=0;c<n.sampleTable.sampleToChunk.length;c++)if(n.sampleTable.sampleToChunk[c].startSampleIndex=o,c<n.sampleTable.sampleToChunk.length-1){let d=n.sampleTable.sampleToChunk[c+1].startChunkIndex-n.sampleTable.sampleToChunk[c].startChunkIndex;o+=d*n.sampleTable.sampleToChunk[c].samplesPerChunk}}break;case"stco":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32();n.sampleTable.chunkOffsets.push(c)}}break;case"co64":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU64();n.sampleTable.chunkOffsets.push(c)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(r.contentSize);break;case"mehd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=n===1?this.metadataReader.readU64():this.metadataReader.readU32();this.movieDurationInTimescale=s}break;case"trex":{this.metadataReader.pos+=4;let n=this.metadataReader.readU32(),s=this.metadataReader.readU32(),o=this.metadataReader.readU32(),c=this.metadataReader.readU32(),u=this.metadataReader.readU32();this.fragmentTrackDefaults.push({trackId:n,defaultSampleDescriptionIndex:s,defaultSampleDuration:o,defaultSampleSize:c,defaultSampleFlags:u})}break;case"tfra":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=this.metadataReader.readU32(),o=this.tracks.find(y=>y.id===s);if(!o)break;o.fragmentLookupTable=[];let c=this.metadataReader.readU32(),u=(c&48)>>4,d=(c&12)>>2,l=c&3,p=this.metadataReader,h=[p.readU8.bind(p),p.readU16.bind(p),p.readU24.bind(p),p.readU32.bind(p)],f=h[u],b=h[d],g=h[l],k=this.metadataReader.readU32();for(let y=0;y<k;y++){let C=n===1?this.metadataReader.readU64():this.metadataReader.readU32(),S=n===1?this.metadataReader.readU64():this.metadataReader.readU32(),w=f(),T=b(),x=g();o.fragmentLookupTable.push({timestamp:C,moofOffset:S})}}break;case"moof":{this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,dataStart:1/0,dataEnd:0,nextFragment:null,isKnownToBeFirstFragment:!1},this.readContiguousBoxes(r.contentSize);let n=F(this.fragments,this.currentFragment.moofOffset,s=>s.moofOffset);this.fragments.splice(n+1,0,this.currentFragment);for(let[,s]of this.currentFragment.trackData){let o=s.samples[0],c=V(s.samples);this.currentFragment.dataStart=Math.min(this.currentFragment.dataStart,o.byteOffset),this.currentFragment.dataEnd=Math.max(this.currentFragment.dataEnd,c.byteOffset+c.byteSize)}this.currentFragment=null}break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(r.contentSize),this.currentTrack){let n=this.currentFragment.trackData.get(this.currentTrack.id);if(n){let s=F(this.currentTrack.fragments,this.currentFragment.moofOffset,u=>u.moofOffset);if(this.currentTrack.fragments.splice(s+1,0,this.currentFragment),n.firstKeyFrameTimestamp!==null){let u=F(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment.moofOffset,d=>d.moofOffset);this.currentTrack.fragmentsWithKeyFrame.splice(u+1,0,this.currentFragment)}let{currentFragmentState:c}=this.currentTrack;m(c),c.startTimestamp!==null&&(ya(n,c.startTimestamp),n.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),this.metadataReader.pos+=1;let n=this.metadataReader.readU24(),s=!!(n&1),o=!!(n&2),c=!!(n&8),u=!!(n&16),d=!!(n&32),l=!!(n&65536),p=!!(n&131072),h=this.metadataReader.readU32(),f=this.tracks.find(g=>g.id===h);if(!f)break;let b=this.fragmentTrackDefaults.find(g=>g.trackId===h);this.currentTrack=f,f.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:b?.defaultSampleDescriptionIndex??null,defaultSampleDuration:b?.defaultSampleDuration??null,defaultSampleSize:b?.defaultSampleSize??null,defaultSampleFlags:b?.defaultSampleFlags??null,startTimestamp:null},s?f.currentFragmentState.baseDataOffset=this.metadataReader.readU64():p&&(f.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),o&&(f.currentFragmentState.sampleDescriptionIndex=this.metadataReader.readU32()),c&&(f.currentFragmentState.defaultSampleDuration=this.metadataReader.readU32()),u&&(f.currentFragmentState.defaultSampleSize=this.metadataReader.readU32()),d&&(f.currentFragmentState.defaultSampleFlags=this.metadataReader.readU32()),l&&(f.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let n=this.currentTrack;if(!n)break;m(n.currentFragmentState);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=s===0?this.metadataReader.readU32():this.metadataReader.readU64();n.currentFragmentState.startTimestamp=o}break;case"trun":{let n=this.currentTrack;if(!n)break;if(m(this.currentFragment),m(n.currentFragmentState),this.currentFragment.trackData.has(n.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let s=this.metadataReader.readU8(),o=this.metadataReader.readU24(),c=!!(o&1),u=!!(o&4),d=!!(o&256),l=!!(o&512),p=!!(o&1024),h=!!(o&2048),f=this.metadataReader.readU32(),b=n.currentFragmentState.baseDataOffset;c&&(b+=this.metadataReader.readI32());let g=null;u&&(g=this.metadataReader.readU32());let k=b;if(f===0){this.currentFragment.implicitBaseDataOffset=k;break}let y=0,C={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(n.id,C);for(let T=0;T<f;T++){let x;d?x=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleDuration!==null),x=n.currentFragmentState.defaultSampleDuration);let E;l?E=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleSize!==null),E=n.currentFragmentState.defaultSampleSize);let I;p?I=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleFlags!==null),I=n.currentFragmentState.defaultSampleFlags),T===0&&g!==null&&(I=g);let A=0;h&&(s===0?A=this.metadataReader.readU32():A=this.metadataReader.readI32());let _=!(I&65536);C.samples.push({presentationTimestamp:y+A,duration:x,byteOffset:k,byteSize:E,isKeyFrame:_}),k+=E,y+=x}C.presentationTimestamps=C.samples.map((T,x)=>({presentationTimestamp:T.presentationTimestamp,sampleIndex:x})).sort((T,x)=>T.presentationTimestamp-x.presentationTimestamp);for(let T=0;T<C.presentationTimestamps.length;T++){let x=C.presentationTimestamps[T],E=C.samples[x.sampleIndex];if(C.firstKeyFrameTimestamp===null&&E.isKeyFrame&&(C.firstKeyFrameTimestamp=E.presentationTimestamp),T<C.presentationTimestamps.length-1){let I=C.presentationTimestamps[T+1];E.duration=I.presentationTimestamp-x.presentationTimestamp}}let S=C.samples[C.presentationTimestamps[0].sampleIndex],w=C.samples[V(C.presentationTimestamps).sampleIndex];C.startTimestamp=S.presentationTimestamp,C.endTimestamp=w.presentationTimestamp+w.duration,this.currentFragment.implicitBaseDataOffset=k}break}this.metadataReader.pos=a}},Zr=class{constructor(e){this.internalTrack=e;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){return this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(()=>{let t=this.internalTrack.demuxer.fragments[0]??null;if(t?.isKnownToBeFirstFragment){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{fragmentIndex:W(this.internalTrack.fragments,r.moofOffset,n=>n.moofOffset),sampleIndex:0,correctSampleFound:!0};r=r.nextFragment}}return{fragmentIndex:-1,sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e):this.fetchPacketForSampleIndex(0,e)}mapTimestampIntoTimescale(e){return Xe(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e);if(this.internalTrack.demuxer.isFragmented)return this.performFragmentedLookup(()=>this.findSampleInFragmentsForTimestamp(r),r,r,t);{let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ta(a,r);return this.fetchPacketForSampleIndex(n,t)}}async getNextPacket(e,t){if(this.internalTrack.demuxer.isFragmented){let a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");let n=a.fragment.trackData.get(this.internalTrack.id),s=n.samples[a.sampleIndex],o=W(this.internalTrack.fragments,a.fragment.moofOffset,c=>c.moofOffset);return m(o!==-1),this.performFragmentedLookup(()=>{if(a.sampleIndex+1<n.samples.length)return{fragmentIndex:o,sampleIndex:a.sampleIndex+1,correctSampleFound:!0};{let c=a.fragment;for(;c.nextFragment;)if(c=c.nextFragment,c.trackData.get(this.internalTrack.id)){let d=W(this.internalTrack.fragments,c.moofOffset,l=>l.moofOffset);return m(d!==-1),{fragmentIndex:d,sampleIndex:0,correctSampleFound:!0}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},s.presentationTimestamp,1/0,t)}let r=this.packetToSampleIndex.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.fetchPacketForSampleIndex(r+1,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e);if(this.internalTrack.demuxer.isFragmented)return this.performFragmentedLookup(()=>this.findKeySampleInFragmentsForTimestamp(r),r,r,t);let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ta(a,r),s=n===-1?-1:wo(a,n);return this.fetchPacketForSampleIndex(s,t)}async getNextKeyPacket(e,t){if(this.internalTrack.demuxer.isFragmented){let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let o=s.fragment.trackData.get(this.internalTrack.id),c=o.samples[s.sampleIndex],u=W(this.internalTrack.fragments,s.fragment.moofOffset,d=>d.moofOffset);return m(u!==-1),this.performFragmentedLookup(()=>{let d=o.samples.findIndex((l,p)=>l.isKeyFrame&&p>s.sampleIndex);if(d!==-1)return{fragmentIndex:u,sampleIndex:d,correctSampleFound:!0};{let l=s.fragment;for(;l.nextFragment;){l=l.nextFragment;let p=l.trackData.get(this.internalTrack.id);if(p&&p.firstKeyFrameTimestamp!==null){let h=W(this.internalTrack.fragments,l.moofOffset,b=>b.moofOffset);m(h!==-1);let f=p.samples.findIndex(b=>b.isKeyFrame);return m(f!==-1),{fragmentIndex:h,sampleIndex:f,correctSampleFound:!0}}}return{fragmentIndex:u,sampleIndex:-1,correctSampleFound:!1}}},c.presentationTimestamp,1/0,t)}let r=this.packetToSampleIndex.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=To(a,r);return this.fetchPacketForSampleIndex(n,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ko(r,e);if(!a)return null;let n;t.metadataOnly?n=ee:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(a.chunkOffset,a.chunkOffset+a.chunkSize),this.internalTrack.demuxer.chunkReader.pos=a.sampleOffset,n=this.internalTrack.demuxer.chunkReader.readBytes(a.sampleSize));let s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new D(n,a.isKeyFrame?"key":"delta",s,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];m(n);let s;r.metadataOnly?s=ee:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(e.dataStart,e.dataEnd),this.internalTrack.demuxer.chunkReader.pos=n.byteOffset,s=this.internalTrack.demuxer.chunkReader.readBytes(n.byteSize));let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,u=new D(s,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}findSampleInFragmentsForTimestamp(e){let t=F(this.internalTrack.fragments,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.fragments[t].trackData.get(this.internalTrack.id),o=F(s.presentationTimestamps,e,c=>c.presentationTimestamp);m(o!==-1),r=s.presentationTimestamps[o].sampleIndex,a=e<s.endTimestamp}return{fragmentIndex:t,sampleIndex:r,correctSampleFound:a}}findKeySampleInFragmentsForTimestamp(e){let t=F(this.internalTrack.fragmentsWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=-1,n=!1;if(t!==-1){let s=this.internalTrack.fragmentsWithKeyFrame[t];r=W(this.internalTrack.fragments,s.moofOffset,d=>d.moofOffset),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=Zt(o.presentationTimestamps,d=>o.samples[d.sampleIndex].isKeyFrame&&d.presentationTimestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].sampleIndex,n=e<o.endTimestamp}return{fragmentIndex:r,sampleIndex:a,correctSampleFound:n}}async performFragmentedLookup(e,t,r,a){let n=this.internalTrack.demuxer,s=await n.fragmentLookupMutex.acquire();try{let{fragmentIndex:o,sampleIndex:c,correctSampleFound:u}=e();if(u){let S=this.internalTrack.fragments[o];return this.fetchPacketInFragment(S,c,a)}let d=n.metadataReader,l=await d.reader.source.getSize(),p=null,h=o,f=c,b=this.internalTrack.fragmentLookupTable?F(this.internalTrack.fragmentLookupTable,t,S=>S.timestamp):-1,g=b!==-1?this.internalTrack.fragmentLookupTable[b]:null,k=!1;if(o===-1)d.pos=g?.moofOffset??0,k=d.pos===0;else{let S=this.internalTrack.fragments[o];!g||S.moofOffset>=g.moofOffset?(d.pos=S.moofOffset+S.moofSize,p=S):d.pos=g.moofOffset}for(;d.pos<l;){if(p){let T=p.trackData.get(this.internalTrack.id);if(T&&T.startTimestamp>r)break;if(p.nextFragment){d.pos=p.nextFragment.moofOffset+p.nextFragment.moofSize,p=p.nextFragment;continue}}await d.reader.loadRange(d.pos,d.pos+Kt);let S=d.pos,w=d.readBoxHeader();if(w.name==="moof"){let T=W(n.fragments,S,_=>_.moofOffset),x;T===-1?(d.pos=S,x=await n.readFragment()):x=n.fragments[T],p&&(p.nextFragment=x),p=x,k&&(x.isKnownToBeFirstFragment=!0,k=!1);let{fragmentIndex:E,sampleIndex:I,correctSampleFound:A}=e();if(A){let _=this.internalTrack.fragments[E];return this.fetchPacketInFragment(_,I,a)}E!==-1&&(h=E,f=I)}d.pos=S+w.totalSize}let y=null,C=h!==-1?this.internalTrack.fragments[h]:null;if(C&&(y=await this.fetchPacketInFragment(C,f,a)),!y&&g&&(!C||C.moofOffset<g.moofOffset)){let w=this.internalTrack.fragmentLookupTable[b-1]?.timestamp??-1/0;return this.performFragmentedLookup(e,w,r,a)}return y}finally{s()}}},tn=class extends Zr{constructor(t){super(t);this.decoderConfigPromise=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Cr(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&xr(t.data)}return{codec:dr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},rn=class extends Zr{constructor(t){super(t);this.decoderConfig=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:ur(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Ta=(i,e)=>{if(i.presentationTimestamps){let t=F(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{let t=F(i.sampleTimingEntries,e,a=>a.startDecodeTimestamp);if(t===-1)return-1;let r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},ko=(i,e)=>{let t=F(i.sampleTimingEntries,e,k=>k.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=F(i.sampleCompositionTimeOffsets,e,k=>k.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&e-o.startIndex<o.count&&(n+=o.offset);let c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],u=F(i.sampleToChunk,e,k=>k.startSampleIndex),d=i.sampleToChunk[u];m(d);let l=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),p=i.chunkOffsets[l],h=d.startSampleIndex+(l-d.startChunkIndex)*d.samplesPerChunk,f=0,b=p;if(i.sampleSizes.length===1)b+=c*(e-h),f+=c*d.samplesPerChunk;else for(let k=h;k<h+d.samplesPerChunk;k++){let y=i.sampleSizes[k];k<e&&(b+=y),f+=y}let g=r.delta;if(i.presentationTimestamps){let k=i.presentationTimestampIndexMap[e];m(k!==void 0),k<i.presentationTimestamps.length-1&&(g=i.presentationTimestamps[k+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:g,sampleOffset:b,sampleSize:c,chunkOffset:p,chunkSize:f,isKeyFrame:i.keySampleIndices?W(i.keySampleIndices,e,k=>k)!==-1:!0}},wo=(i,e)=>{if(!i.keySampleIndices)return e;let t=F(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t]??-1},To=(i,e)=>{if(!i.keySampleIndices)return e+1;let t=F(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},ya=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(let t of i.samples)t.presentationTimestamp+=e;for(let t of i.presentationTimestamps)t.presentationTimestamp+=e},yo=i=>{let[e,,,t]=i,r=Math.hypot(e,t),a=e/r,n=t/r;return-Math.atan2(n,a)*(180/Math.PI)};var nn=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],Jr=class extends oe{constructor(t){super(t);this.readMetadataPromise=null;this.segments=[];this.currentSegment=null;this.currentTrack=null;this.currentCluster=null;this.currentBlock=null;this.currentCueTime=null;this.isWebM=!1;this.metadataReader=new We(t._mainReader),this.clusterReader=new We(new de(t.source,64*2**20))}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(t=>t.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.getCodecParameterString()));return Mr({isWebM:this.isWebM,hasVideo:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="audio")),codecStrings:r.filter(Boolean)})}readMetadata(){return this.readMetadataPromise??=(async()=>{this.metadataReader.pos=0;let t=await this.input.source.getSize();for(;this.metadataReader.pos<=t-Or;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let{id:r,size:a}=this.metadataReader.readElementHeader(),n=this.metadataReader.pos;if(r===440786851)Le(a),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+a),this.readContiguousElements(this.metadataReader,a);else if(r===408125543&&(await this.readSegment(a),a===null))break;Le(a),this.metadataReader.pos=n+a}})()}async readSegment(t){let r=this.metadataReader.pos;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:r,elementEndPos:t===null?await this.input.source.getSize():r+t,clusterSeekStartPos:r,clusters:[],clusterLookupMutex:new ne},this.segments.push(this.currentSegment),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+2**14);let a=!1;for(;this.metadataReader.pos<this.currentSegment.elementEndPos;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let u=this.metadataReader.pos,{id:d,size:l}=this.metadataReader.readElementHeader(),p=this.metadataReader.pos,h=nn.findIndex(f=>f.id===d);if(h!==-1){let f=nn[h].flag;this.currentSegment[f]=!0,Le(l),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+l),this.readContiguousElements(this.metadataReader,l)}else d===524531317&&(a||(a=!0,this.currentSegment.clusterSeekStartPos=u));if(this.currentSegment.infoSeen&&this.currentSegment.tracksSeen&&this.currentSegment.cuesSeen)break;if(this.currentSegment.seekHeadSeen){let f=this.currentSegment.infoSeen,b=this.currentSegment.tracksSeen,g=this.currentSegment.cuesSeen;for(let k of this.currentSegment.seekEntries)k.id===357149030?f=!0:k.id===374648427?b=!0:k.id===475249515&&(g=!0);if(f&&b&&g)break}if(l===null)break;this.metadataReader.pos=p+l,a||(this.currentSegment.clusterSeekStartPos=this.metadataReader.pos)}for(let u of nn){if(this.currentSegment[u.flag])continue;let d=this.currentSegment.seekEntries.find(h=>h.id===u.id);if(!d)continue;this.metadataReader.pos=r+d.segmentPosition,await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+2**12);let{id:l,size:p}=this.metadataReader.readElementHeader();l===u.id&&(Le(p),this.currentSegment[u.flag]=!0,await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+p),this.readContiguousElements(this.metadataReader,p))}this.currentSegment.tracks.sort((u,d)=>Number(d.isDefault)-Number(u.isDefault)),this.currentSegment.cuePoints.sort((u,d)=>u.clusterPosition-d.clusterPosition);let n=this.currentSegment.tracks.map(u=>u.id),s=new Set,o=null,c=null;for(let u of this.currentSegment.cuePoints){if(u.clusterPosition!==o){for(let l of s)m(c),this.currentSegment.tracks.find(h=>h.id===l).cuePoints.push(c);for(let l of n)s.add(l)}if(c=u,!s.has(u.trackId))continue;this.currentSegment.tracks.find(l=>l.id===u.trackId).cuePoints.push(u),s.delete(u.trackId),o=u.clusterPosition}for(let u of s)m(c),this.currentSegment.tracks.find(l=>l.id===u).cuePoints.push(c);for(let u of this.currentSegment.tracks)u.cuePoints.sort((d,l)=>d.time-l.time);this.currentSegment=null}async readCluster(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let r=this.metadataReader.pos,a=this.metadataReader.readElementHeader(),n=a.id,s=a.size,o=this.metadataReader.pos;s===null&&(this.clusterReader.pos=o,s=(await this.clusterReader.searchForNextElementId(_i,t.elementEndPos)??t.elementEndPos)-o),m(n===524531317),this.clusterReader.pos=o,await this.clusterReader.reader.loadRange(this.clusterReader.pos,this.clusterReader.pos+s);let c={elementStartPos:r,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map,nextCluster:null,isKnownToBeFirstCluster:!1};this.currentCluster=c,this.readContiguousElements(this.clusterReader,s);for(let[d,l]of c.trackData){let p=!1;m(l.blocks.length>0);for(let g=0;g<l.blocks.length;g++){let k=l.blocks[g];k.timestamp+=c.timestamp,p||=k.referencedTimestamps.length>0}p&&(l.blocks=So(l.blocks)),l.presentationTimestamps=l.blocks.map((g,k)=>({timestamp:g.timestamp,blockIndex:k})).sort((g,k)=>g.timestamp-k.timestamp);for(let g=0;g<l.presentationTimestamps.length;g++){let k=l.presentationTimestamps[g],y=l.blocks[k.blockIndex];if(l.firstKeyFrameTimestamp===null&&y.isKeyFrame&&(l.firstKeyFrameTimestamp=y.timestamp),g<l.presentationTimestamps.length-1){let C=l.presentationTimestamps[g+1];y.duration=C.timestamp-y.timestamp}}let h=l.blocks[l.presentationTimestamps[0].blockIndex],f=l.blocks[V(l.presentationTimestamps).blockIndex];l.startTimestamp=h.timestamp,l.endTimestamp=f.timestamp+f.duration;let b=t.tracks.find(g=>g.id===d);if(b){let g=F(b.clusters,c.elementStartPos,y=>y.elementStartPos);if(b.clusters.splice(g+1,0,c),l.firstKeyFrameTimestamp!==null){let y=F(b.clustersWithKeyFrame,c.elementStartPos,C=>C.elementStartPos);b.clustersWithKeyFrame.splice(y+1,0,c)}}}let u=F(t.clusters,r,d=>d.elementStartPos);return t.clusters.splice(u+1,0,c),this.currentCluster=null,c}getTrackDataInCluster(t,r){let a=t.trackData.get(r);return a||(a={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},t.trackData.set(r,a)),a}readContiguousElements(t,r){let a=t.pos;for(;t.pos-a<=r-Or;)this.traverseElement(t)}traverseElement(t){let{id:r,size:a}=t.readElementHeader(),n=t.pos;switch(Le(a),r){case 17026:this.isWebM=t.readString(a)==="webm";break;case 19899:{if(!this.currentSegment)break;let s={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(s),this.readContiguousElements(t,a),(s.id===-1||s.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let s=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!s)break;s.id=t.readUnsignedInt(a)}break;case 21420:{let s=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!s)break;s.segmentPosition=t.readUnsignedInt(a)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=t.readUnsignedInt(a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=t.readFloat(a)}break;case 174:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusters:[],clustersWithKeyFrame:[],cuePoints:[],isDefault:!1,inputTrack:null,codecId:null,codecPrivate:null,languageCode:Z,info:null},this.readContiguousElements(t,a),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let s=this.currentTrack.codecId.indexOf("/"),o=s===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,s);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===re.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===re.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.vp8?this.currentTrack.info.codec="vp8":o===re.vp9?this.currentTrack.info.codec="vp9":o===re.av1&&(this.currentTrack.info.codec="av1");let c=this.currentTrack,u=new le(new an(c));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){o===re.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===re.mp3?this.currentTrack.info.codec="mp3":o===re.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let c=this.currentTrack,u=new X(new sn(c));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=t.readUnsignedInt(a)}break;case 131:{if(!this.currentTrack)break;let s=t.readUnsignedInt(a);s===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null}:s===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case 185:{if(!this.currentTrack)break;t.readUnsignedInt(a)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!t.readUnsignedInt(a)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=t.readString(a)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=t.readBytes(a)}break;case 2274716:{if(!this.currentTrack)break;this.currentTrack.languageCode=t.readString(a),Ye(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,a)}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=t.readUnsignedInt(a)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=t.readUnsignedInt(a)}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(t,a)}break;case 21937:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=Xt[s]??null;this.currentTrack.info.colorSpace.matrix=o}break;case 21945:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=t.readUnsignedInt(a)===2}break;case 21946:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=Gt[s]??null;this.currentTrack.info.colorSpace.transfer=o}break;case 21947:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=jt[s]??null;this.currentTrack.info.colorSpace.primaries=o}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,a)}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let o=-t.readFloat(a);try{this.currentTrack.info.rotation=Ae(o)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(t,a)}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=t.readFloat(a)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=t.readUnsignedInt(a)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=t.readUnsignedInt(a)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(t,a),this.currentCueTime=null}break;case 179:this.currentCueTime=t.readUnsignedInt(a);break;case 183:{if(this.currentCueTime===null)break;m(this.currentSegment);let s={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(s),this.readContiguousElements(t,a),(s.trackId===-1||s.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let s=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!s)break;s.trackId=t.readUnsignedInt(a)}break;case 241:{let s=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!s)break;m(this.currentSegment),s.clusterPosition=this.currentSegment.dataStartPos+t.readUnsignedInt(a)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=t.readUnsignedInt(a)}break;case 163:{if(!this.currentCluster)break;let s=t.readVarInt(),o=t.readS16(),u=!!(t.readU8()&128);this.getTrackDataInCluster(this.currentCluster,s).blocks.push({timestamp:o,duration:0,isKeyFrame:u,referencedTimestamps:[],data:t.readBytes(a-(t.pos-n))})}break;case 160:{if(!this.currentCluster)break;if(this.readContiguousElements(t,a),this.currentBlock){for(let s=0;s<this.currentBlock.referencedTimestamps.length;s++)this.currentBlock.referencedTimestamps[s]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case 161:{if(!this.currentCluster)break;let s=t.readVarInt(),o=t.readS16(),c=t.readU8(),u=this.getTrackDataInCluster(this.currentCluster,s);this.currentBlock={timestamp:o,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:t.readBytes(a-(t.pos-n))},u.blocks.push(this.currentBlock)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=t.readUnsignedInt(a)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let s=t.readSignedInt(a);this.currentBlock.referencedTimestamps.push(s)}break}t.pos=n+a}},ei=class{constructor(e){this.internalTrack=e;this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}async getFirstPacket(e){return this.performClusterLookup(()=>{let t=this.internalTrack.segment.clusters[0]??null;if(t?.isKnownToBeFirstCluster){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{clusterIndex:W(this.internalTrack.clusters,r.elementStartPos,n=>n.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return Xe(e*this.internalTrack.segment.timestampFactor,14)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findBlockInClustersForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=r.cluster.trackData.get(this.internalTrack.id),n=a.blocks[r.blockIndex],s=W(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return m(s!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<a.blocks.length)return{clusterIndex:s,blockIndex:r.blockIndex+1,correctBlockFound:!0};{let o=r.cluster;for(;o.nextCluster;)if(o=o.nextCluster,o.trackData.get(this.internalTrack.id)){let u=W(this.internalTrack.clusters,o.elementStartPos,d=>d.elementStartPos);return m(u!==-1),{clusterIndex:u,blockIndex:0,correctBlockFound:!0}}return{clusterIndex:s,blockIndex:-1,correctBlockFound:!1}}},n.timestamp,1/0,t)}async getKeyPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findKeyBlockInClustersForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=r.cluster.trackData.get(this.internalTrack.id),n=a.blocks[r.blockIndex],s=W(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return m(s!==-1),this.performClusterLookup(()=>{let o=a.blocks.findIndex((c,u)=>c.isKeyFrame&&u>r.blockIndex);if(o!==-1)return{clusterIndex:s,blockIndex:o,correctBlockFound:!0};{let c=r.cluster;for(;c.nextCluster;){c=c.nextCluster;let u=c.trackData.get(this.internalTrack.id);if(u&&u.firstKeyFrameTimestamp!==null){let d=W(this.internalTrack.clusters,c.elementStartPos,p=>p.elementStartPos);m(d!==-1);let l=u.blocks.findIndex(p=>p.isKeyFrame);return m(l!==-1),{clusterIndex:d,blockIndex:l,correctBlockFound:!0}}}return{clusterIndex:s,blockIndex:-1,correctBlockFound:!1}}},n.timestamp,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];m(n);let s=r.metadataOnly?ee:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,u=new D(s,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}findBlockInClustersForTimestamp(e){let t=F(this.internalTrack.clusters,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.clusters[t].trackData.get(this.internalTrack.id),o=F(s.presentationTimestamps,e,c=>c.timestamp);m(o!==-1),r=s.presentationTimestamps[o].blockIndex,a=e<s.endTimestamp}return{clusterIndex:t,blockIndex:r,correctBlockFound:a}}findKeyBlockInClustersForTimestamp(e){let t=F(this.internalTrack.clustersWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).firstKeyFrameTimestamp),r=-1,a=-1,n=!1;if(t!==-1){let s=this.internalTrack.clustersWithKeyFrame[t];r=W(this.internalTrack.clusters,s.elementStartPos,d=>d.elementStartPos),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=Zt(o.presentationTimestamps,d=>o.blocks[d.blockIndex].isKeyFrame&&d.timestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].blockIndex,n=e<o.endTimestamp}return{clusterIndex:r,blockIndex:a,correctBlockFound:n}}async performClusterLookup(e,t,r,a){let{demuxer:n,segment:s}=this.internalTrack,o=await s.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:u,correctBlockFound:d}=e();if(d){let w=this.internalTrack.clusters[c];return this.fetchPacketInCluster(w,u,a)}let l=n.metadataReader,p=n.clusterReader,h=null,f=c,b=u,g=F(this.internalTrack.cuePoints,t,w=>w.time),k=g!==-1?this.internalTrack.cuePoints[g]:null,y=!1;if(c===-1)l.pos=k?.clusterPosition??s.clusterSeekStartPos,y=l.pos===s.clusterSeekStartPos;else{let w=this.internalTrack.clusters[c];!k||w.elementStartPos>=k.clusterPosition?(l.pos=w.elementEndPos,h=w):l.pos=k.clusterPosition}for(;l.pos<s.elementEndPos;){if(h){let A=h.trackData.get(this.internalTrack.id);if(A&&A.startTimestamp>r)break;if(h.nextCluster){l.pos=h.nextCluster.elementEndPos,h=h.nextCluster;continue}}await l.reader.loadRange(l.pos,l.pos+Ne);let w=l.pos,T=l.readElementHeader(),x=T.id,E=T.size,I=l.pos;if(x===524531317){let A=W(s.clusters,w,di=>di.elementStartPos),_;A===-1?(l.pos=w,_=await n.readCluster(s)):_=s.clusters[A],h&&(h.nextCluster=_),h=_,y&&(_.isKnownToBeFirstCluster=!0,y=!1);let{clusterIndex:te,blockIndex:ke,correctBlockFound:Fa}=e();if(Fa){let di=this.internalTrack.clusters[te];return this.fetchPacketInCluster(di,ke,a)}te!==-1&&(f=te,b=ke)}if(E===null){x===524531317?(m(h),E=h.elementEndPos-I):(p.pos=I,E=(await p.searchForNextElementId(_i,s.elementEndPos)??s.elementEndPos)-I);let A=I+E;if(A>s.elementEndPos-Or)break;if(p.pos=A,p.readElementId()===408125543){s.elementEndPos=A;break}}l.pos=I+E}let C=null,S=f!==-1?this.internalTrack.clusters[f]:null;if(S&&(C=await this.fetchPacketInCluster(S,b,a)),!C&&k&&(!S||S.elementStartPos<k.clusterPosition)){let T=this.internalTrack.cuePoints[g-1]?.time??-1/0;return this.performClusterLookup(e,T,r,a)}return C}finally{o()}}},an=class extends ei{constructor(t){super(t);this.decoderConfigPromise=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let t=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(t=await this.getFirstPacket({})),{codec:dr({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcCodecInfo:this.internalTrack.info.codec==="avc"&&t?yr(t.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&t?Sr(t.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&t?Cr(t.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&t?xr(t.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},sn=class extends ei{constructor(t){super(t);this.decoderConfig=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:ur({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},So=i=>{let e=new Map;for(let n=0;n<i.length;n++){let s=i[n];e.set(s.timestamp,s)}let t=new Set,r=[],a=n=>{if(!t.has(n)){t.add(n);for(let s=0;s<n.referencedTimestamps.length;s++){let o=n.referencedTimestamps[s],c=e.get(o);c&&a(c)}r.push(n)}};for(let n=0;n<i.length;n++)a(i[n]);return r};var kt=class{constructor(e){this.reader=e;this.pos=0;this.fileSize=null}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readId3(){return this.readAscii(3)!=="ID3"?(this.pos-=3,null):(this.pos+=3,{size:Co(this.readU32())})}readNextFrameHeader(e){for(m(this.fileSize),e??=this.fileSize;this.pos<=e-4;){let t=this.readU32();this.pos-=4;let r=Ur(t,this);if(r)return r}return null}},Co=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var ti=class extends oe{constructor(t){super(t);this.metadataPromise=null;this.firstFrameHeader=null;this.allSamples=[];this.tracks=[];this.reader=new kt(t._mainReader)}async readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.input.source.getSize();this.reader.fileSize=t,await this.reader.reader.loadRange(0,t);let r=this.reader.readId3();r&&(this.reader.pos+=r.size);let a=0;for(;;){let n=this.reader.readNextFrameHeader();if(!n)break;let s=ct(n.mpegVersionId,n.channel);this.reader.pos=n.startPos+s;let o=this.reader.readU32(),c=o===ot||o===Dr;if(this.reader.pos=n.startPos+n.totalSize-1,c)continue;this.firstFrameHeader||(this.firstFrameHeader=n);let u=n.audioSamplesInFrame/n.sampleRate,d={timestamp:a/n.sampleRate,duration:u,dataStart:n.startPos,dataSize:n.totalSize};this.allSamples.push(d),a+=n.audioSamplesInFrame}if(!this.firstFrameHeader)throw new Error("No MP3 frames found.");this.tracks=[new X(new cn(this))]})()}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let t=V(this.allSamples);return m(t),t.timestamp+t.duration}},cn=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}computeDuration(){return this.demuxer.computeDuration()}getLanguageCode(){return Z}getCodec(){return"mp3"}getNumberOfChannels(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.allSamples[e];if(!r)return null;let a;return t.metadataOnly?a=ee:(this.demuxer.reader.pos=r.dataStart,a=this.demuxer.reader.readBytes(r.dataSize)),new D(a,"key",r.timestamp,r.duration,e,r.dataSize)}async getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=W(this.demuxer.allSamples,e.timestamp,a=>a.timestamp);if(r===-1)throw new Error("Packet was not created from this track.");return this.getPacketAtIndex(r+1,t)}async getPacket(e,t){let r=F(this.demuxer.allSamples,e,a=>a.timestamp);return this.getPacketAtIndex(r,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ri=class extends oe{constructor(t){super(t);this.readingMutex=new ne;this.metadataPromise=null;this.fileSize=null;this.bitstreams=[];this.tracks=[];this.reader=new dt(new de(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{for(this.fileSize=await this.input.source.getSize();this.reader.pos<this.fileSize-ut;){await this.reader.reader.loadRange(this.reader.pos,this.reader.pos+He);let t=this.reader.readPageHeader();if(!t||!!!(t.headerType&2))break;this.bitstreams.push({serialNumber:t.serialNumber,bosPage:t,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),this.reader.pos=t.headerStartPos+t.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(this.reader,t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new X(new dn(t,this))))}})()}async readVorbisMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n||(a=await this.findNextPacketStart(this.reader,n),!a))return;let s=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;let o=[],c=p=>{for(;o.push(Math.min(255,p)),!(p<255);)p-=255};c(t.data.length),c(n.data.length);let u=new Uint8Array(1+o.length+t.data.length+n.data.length+s.data.length);u[0]=o.length,u.set(o,1),u.set(t.data,1+o.length),u.set(n.data,1+o.length+t.data.length),u.set(s.data,1+o.length+t.data.length+n.data.length),r.codecInfo.codec="vorbis",r.description=u,r.lastMetadataPacket=s;let d=Y(t.data);r.numberOfChannels=d.getUint8(11),r.sampleRate=d.getUint32(12,!0);let l=d.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:vr(s.data).modeBlockflags}}async readOpusMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n)return;r.codecInfo.codec="opus",r.description=t.data,r.lastMetadataPacket=n;let s=Oe(t.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=s.inputSampleRate,r.codecInfo.opusInfo={preSkip:s.preSkip}}async readPacket(t,r,a){m(a<r.lacingValues.length),m(this.fileSize);let n=0;for(let h=0;h<a;h++)n+=r.lacingValues[h];let s=r,o=n,c=a,u=[];e:for(;;){await t.reader.loadRange(s.dataStartPos,s.dataStartPos+s.dataSize),t.pos=s.dataStartPos;let h=t.readBytes(s.dataSize);for(;;){if(c===s.lacingValues.length){u.push(h.subarray(n,o));break}let f=s.lacingValues[c];if(o+=f,f<255){u.push(h.subarray(n,o));break e}c++}for(;;){if(t.pos=s.headerStartPos+s.totalSize,t.pos>=this.fileSize-ut)return null;await t.reader.loadRange(t.pos,t.pos+He);let f=t.readPageHeader();if(!f)return null;if(s=f,s.serialNumber===r.serialNumber)break}n=0,o=0,c=0}let d=u.reduce((h,f)=>h+f.length,0),l=new Uint8Array(d),p=0;for(let h=0;h<u.length;h++){let f=u[h];l.set(f,p),p+=f.length}return{data:l,endPage:s,endSegmentIndex:c}}async findNextPacketStart(t,r){if(m(this.fileSize!==null),r.endSegmentIndex<r.endPage.lacingValues.length-1)return{startPage:r.endPage,startSegmentIndex:r.endSegmentIndex+1};if(!!(r.endPage.headerType&4))return null;for(t.pos=r.endPage.headerStartPos+r.endPage.totalSize;;){if(t.pos>=this.fileSize-ut)return null;await t.reader.loadRange(t.pos,t.pos+He);let n=t.readPageHeader();if(!n)return null;if(n.serialNumber===r.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};t.pos=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return Hr({codecStrings:t.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}},dn=class{constructor(e,t){this.bitstream=e;this.demuxer=t;this.encodedPacketToMetadata=new WeakMap;this.internalSampleRate=e.codecInfo.codec==="opus"?et:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}async getDecoderConfig(){return m(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getLanguageCode(){return Z}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(m(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:a,vorbisBlockSize:n}=Lr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new D(r.metadataOnly?ee:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisBlockSize:n}),s}async getFirstPacket(e,t=!0){let r=t?await this.demuxer.readingMutex.acquire():null;try{m(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.demuxer.reader,this.bitstream.lastMetadataPacket);if(!a)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(this.demuxer.reader,a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:null},e)}finally{r?.()}}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let a=this.encodedPacketToMetadata.get(e);if(!a)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(this.demuxer.reader,a.packet);if(!n)return null;let s=a.timestampInSamples+a.durationInSamples,o=await this.demuxer.readPacket(this.demuxer.reader,n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:s,vorbisLastBlocksize:a.vorbisBlockSize},t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{m(this.demuxer.fileSize!==null);let a=Xe(e*this.internalSampleRate,14);if(a===0)return this.getFirstPacket(t,!1);if(a<0)return null;let n=this.demuxer.reader;m(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(n,this.bitstream.lastMetadataPacket);if(!s)return null;let o=s.startPage,c=this.demuxer.fileSize,u=[o];e:for(;o.headerStartPos+o.totalSize<c;){let S=o.headerStartPos,w=Math.floor((S+c)/2),T=w;for(;;){let x=Math.min(T+Kr,c-ut);if(await n.reader.loadRange(T,x),n.pos=T,!n.findNextPageHeader(x)){c=w+ut;continue e}await n.reader.loadRange(n.pos,n.pos+He);let I=n.readPageHeader();m(I);let A=!1;if(I.serialNumber===this.bitstream.serialNumber)A=!0;else{await n.reader.loadRange(I.headerStartPos,I.headerStartPos+I.totalSize),n.pos=I.headerStartPos;let te=n.readBytes(I.totalSize);A=Wr(te)===I.checksum}if(!A){T=I.headerStartPos+4;continue}if(A&&I.serialNumber!==this.bitstream.serialNumber){T=I.headerStartPos+I.totalSize;continue}if(I.granulePosition===-1){T=I.headerStartPos+I.totalSize;continue}this.granulePositionToTimestampInSamples(I.granulePosition)>a?c=I.headerStartPos:(o=I,u.push(I));continue e}}let d=s.startPage;for(let S of u){if(S.granulePosition===o.granulePosition)break;(!d||S.headerStartPos>d.headerStartPos)&&(d=S)}let l=d,p=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===o.granulePosition);){n.pos=l.headerStartPos+l.totalSize,await n.reader.loadRange(n.pos,n.pos+He);let S=n.readPageHeader();m(S),l=S,l.serialNumber===this.bitstream.serialNumber&&p.push(l)}m(l.granulePosition!==-1);let h=null,f,b,g=l,k=0;if(l.headerStartPos===s.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),b=!0,h=0;else{f=0,b=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){h=T+1;break}if(h===null)throw new Error("Invalid page with granule position: no packets end on this page.");k=h-1;let S={data:ee,endPage:g,endSegmentIndex:k};if(await this.demuxer.findNextPacketStart(n,S)){let T=Ca(p,l,h);m(T);let x=Sa(p,T.page,T.segmentIndex);x&&(l=x.page,h=x.segmentIndex)}else for(;;){let T=Ca(p,l,h);if(!T)break;let x=Sa(p,T.page,T.segmentIndex);if(!x)break;if(l=x.page,h=x.segmentIndex,T.page.headerStartPos!==g.headerStartPos){g=T.page,k=T.segmentIndex;break}}}let y=null,C=null;for(;l!==null;){m(h!==null);let S=await this.demuxer.readPacket(n,l,h);if(!S)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&h<s.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:f,vorbisLastBlocksize:C?.vorbisBlockSize??null},t);m(x);let E=this.encodedPacketToMetadata.get(x);if(m(E),!b&&S.endPage.headerStartPos===g.headerStartPos&&S.endSegmentIndex===k?(f=this.granulePositionToTimestampInSamples(l.granulePosition),b=!0,x=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:f-E.durationInSamples,vorbisLastBlocksize:C?.vorbisBlockSize??null},t),m(x),E=this.encodedPacketToMetadata.get(x),m(E)):f+=E.durationInSamples,y=x,C=E,b&&(Math.max(f,0)>a||Math.max(E.timestampInSamples,0)===a))break}let T=await this.demuxer.findNextPacketStart(n,S);if(!T)break;l=T.startPage,h=T.startSegmentIndex}return y}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Sa=(i,e,t)=>{let r=e,a=t;e:for(;;){for(a--,a;a>=0;a--)if(r.lacingValues[a]<255){a++;break e}if(m(a===-1),!(r.headerType&1)){a=0;break}let s=fi(i,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,a=r.lacingValues.length}if(m(a!==-1),a===r.lacingValues.length){let n=i[i.indexOf(r)+1];m(n),r=n,a=0}return{page:r,segmentIndex:a}},Ca=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=fi(i,a=>a.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var be=class{},Qt=class extends be{async _getMajorBrand(e){if(await e._mainReader.source.getSize()<12)return null;let r=new qe(e._mainReader);return r.pos=4,r.readAscii(4)!=="ftyp"?null:r.readAscii(4)}_createDemuxer(e){return new Yr(e)}},ii=class extends Qt{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},ni=class extends Qt{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},$t=class extends be{async isSupportedEBMLOfDocType(e,t){if(await e._mainReader.source.getSize()<8)return!1;let a=new We(e._mainReader),n=a.readVarIntSize();if(n<1||n>8||a.readUnsignedInt(n)!==440786851)return!1;let o=a.readElementSize();if(o===null)return!1;let c=a.pos;for(;a.pos<c+o;){let{id:u,size:d}=a.readElementHeader(),l=a.pos;if(d===null)return!1;switch(u){case 17030:if(a.readUnsignedInt(d)!==1)return!1;break;case 17143:if(a.readUnsignedInt(d)!==1)return!1;break;case 17026:if(a.readString(d)!==t)return!1;break;case 17031:if(a.readUnsignedInt(d)>4)return!1;break}a.pos=l+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Jr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},ai=class extends $t{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},si=class extends be{async _canReadInput(e){let t=await e._mainReader.source.getSize();if(t<4)return!1;let r=new kt(e._mainReader);r.fileSize=t;let a=r.readId3();a&&(r.pos+=a.size);let n=r.pos;await r.reader.loadRange(r.pos,r.pos+4096);let s=r.readNextFrameHeader(Math.min(n+4096,t));if(!s)return!1;if(a)return!0;r.pos=s.startPos+s.totalSize,await r.reader.loadRange(r.pos,r.pos+4);let o=r.readNextFrameHeader(r.pos+4);return!(!o||s.channel!==o.channel||s.sampleRate!==o.sampleRate)}_createDemuxer(e){return new ti(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},oi=class extends be{async _canReadInput(e){if(await e._mainReader.source.getSize()<12)return!1;let r=new $e(e._mainReader),a=r.readAscii(4);return a!=="RIFF"&&a!=="RIFX"&&a!=="RF64"?!1:(r.pos=8,r.readAscii(4)==="WAVE")}_createDemuxer(e){return new qr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},ci=class extends be{async _canReadInput(e){return await e._mainReader.source.getSize()<4?!1:new dt(e._mainReader).readAscii(4)==="OggS"}_createDemuxer(e){return new ri(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},xa=new ii,va=new ni,Pa=new $t,Ea=new ai,Ia=new si,_a=new oi,Aa=new ci,xo=[xa,va,Pa,Ea,_a,Aa,Ia];var qt=class{constructor(e){this._demuxerPromise=null;this._format=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof be)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ie))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._mainReader=new de(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{await this._mainReader.loadRange(0,4096);for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}};var un=2,ln=48e3,mn=class i{constructor(e){this._addedCounts={video:0,audio:0,subtitle:0};this._totalTrackCount=0;this._trackPromises=[];this._executed=!1;this._synchronizer=new fn;this._totalDuration=null;this._maxTimestamps=new Map;this._canceled=!1;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this.utilizedTracks=[];this.discardedTracks=[];if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof qt))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Ht))throw new TypeError("options.output must be an Output.");if(e.output._tracks.length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks added and not started.");if(e.video!==void 0&&(!e.video||typeof e.video!="object"))throw new TypeError("options.video, when provided, must be an object.");if(e.video?.discard!==void 0&&typeof e.video.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(e.video?.forceTranscode!==void 0&&typeof e.video.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(e.video?.codec!==void 0&&!q.includes(e.video.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${q.join(", ")}.`);if(e.video?.bitrate!==void 0&&!(e.video.bitrate instanceof H)&&(!Number.isInteger(e.video.bitrate)||e.video.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(e.video?.width!==void 0&&(!Number.isInteger(e.video.width)||e.video.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(e.video?.height!==void 0&&(!Number.isInteger(e.video.height)||e.video.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(e.video?.fit!==void 0&&!["fill","contain","cover"].includes(e.video.fit))throw new TypeError('options.video.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.video?.width!==void 0&&e.video.height!==void 0&&e.video.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(e.video?.rotate!==void 0&&![0,90,180,270].includes(e.video.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(e.audio!==void 0&&(!e.audio||typeof e.audio!="object"))throw new TypeError("options.video, when provided, must be an object.");if(e.audio?.discard!==void 0&&typeof e.audio.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(e.audio?.forceTranscode!==void 0&&typeof e.audio.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(e.audio?.codec!==void 0&&!j.includes(e.audio.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${j.join(", ")}.`);if(e.audio?.bitrate!==void 0&&!(e.audio.bitrate instanceof H)&&(!Number.isInteger(e.audio.bitrate)||e.audio.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(e.audio?.numberOfChannels!==void 0&&(!Number.isInteger(e.audio.numberOfChannels)||e.audio.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(e.audio?.sampleRate!==void 0&&(!Number.isInteger(e.audio.sampleRate)||e.audio.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&(!Number.isFinite(e.trim.start)||e.trim.start<0))throw new TypeError("options.trim.start, when provided, must be a non-negative number.");if(e.trim?.end!==void 0&&(!Number.isFinite(e.trim.end)||e.trim.end<0))throw new TypeError("options.trim.end, when provided, must be a non-negative number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");this._options=e,this.input=e.input,this.output=e.output,this._startTimestamp=e.trim?.start??0,this._endTimestamp=e.trim?.end??1/0;let{promise:t,resolve:r}=z();this._started=t,this._start=r}static async init(e){let t=new i(e);return await t._init(),t}async _init(){let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts();for(let a of e){if(a.isVideoTrack()&&this._options.video?.discard){this.discardedTracks.push({track:a,reason:"discarded_by_user"});continue}if(a.isAudioTrack()&&this._options.audio?.discard){this.discardedTracks.push({track:a,reason:"discarded_by_user"});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:a,reason:"max_track_count_reached"});continue}if(this._addedCounts[a.type]===t[a.type].max){this.discardedTracks.push({track:a,reason:"max_track_count_of_type_reached"});continue}a.isVideoTrack()?await this._processVideoTrack(a):a.isAudioTrack()&&await this._processAudioTrack(a)}let r=this.discardedTracks.filter(a=>a.reason!=="discarded_by_user");r.length>0&&console.warn("Some tracks had to be discarded from the conversion:",r)}async execute(){if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0,this.onProgress&&(this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp),this.onProgress?.(0)),await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||await this.cancel(),e}this._canceled&&await new Promise(()=>{}),await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e){let t=e.codec;if(!t){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let r,a=Ae(e.rotation+(this._options.video?.rotate??0)),n=this.output.format.supportsVideoRotationMetadata,[s,o]=a%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],c=s,u=o,d=c/u,l=g=>Math.ceil(g/2)*2;this._options.video?.width!==void 0&&this._options.video.height===void 0?(c=l(this._options.video.width),u=l(Math.round(c/d))):this._options.video?.width===void 0&&this._options.video?.height!==void 0?(u=l(this._options.video.height),c=l(Math.round(u*d))):this._options.video?.width!==void 0&&this._options.video.height!==void 0&&(c=l(this._options.video.width),u=l(this._options.video.height));let p=await e.getFirstTimestamp(),h=!!this._options.video?.forceTranscode||this._startTimestamp>0||p<0,f=c!==s||u!==o||a!==0&&!n,b=this.output.format.getSupportedVideoCodecs();if(!h&&!this._options.video?.bitrate&&!f&&b.includes(t)&&(!this._options.video?.codec||this._options.video?.codec===t)){let g=new zt(t);r=g,this._trackPromises.push((async()=>{await this._started;let k=new he(e),C={decoderConfig:await e.getDecoderConfig()??void 0},S=Number.isFinite(this._endTimestamp)?await k.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let w of k.packets(void 0,S,{verifyKeyPackets:!0})){if(this._synchronizer.shouldWait(e.id,w.timestamp)&&await this._synchronizer.wait(w.timestamp),this._canceled)return;await g.add(w,C),this._reportProgress(e.id,w.timestamp+w.duration)}g.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}this._options.video?.codec&&(b=b.filter(S=>S===this._options.video?.codec));let k=this._options.video?.bitrate??lr,y=await wi(b,{width:c,height:u,bitrate:k});if(!y){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}let C={codec:y,bitrate:k,onEncodedPacket:S=>this._reportProgress(e.id,S.timestamp+S.duration)};if(f){let S=new ht(C);r=S,this._trackPromises.push((async()=>{await this._started;let T=new Dt(e,{width:c,height:u,fit:this._options.video?.fit??"fill",rotation:a,poolSize:1}).canvases(this._startTimestamp,this._endTimestamp);for await(let{canvas:x,timestamp:E,duration:I}of T){if(this._synchronizer.shouldWait(e.id,E)&&await this._synchronizer.wait(E),this._canceled)return;let A=new ce(x,{timestamp:Math.max(E-this._startTimestamp,0),duration:I});await S.add(A),A.close()}})())}else{let S=new ht(C);r=S,this._trackPromises.push((async()=>{await this._started;let w=new mt(e);for await(let T of w.samples(this._startTimestamp,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,T.timestamp)&&await this._synchronizer.wait(T.timestamp),T.setTimestamp(Math.max(T.timestamp-this._startTimestamp,0)),this._canceled)return;await S.add(T),T.close()}S.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addVideoTrack(r,{languageCode:e.languageCode,rotation:f?0:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _processAudioTrack(e){let t=e.codec;if(!t){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let r,a=e.numberOfChannels,n=e.sampleRate,s=await e.getFirstTimestamp(),o=this._options.audio?.numberOfChannels??a,c=this._options.audio?.sampleRate??n,u=o!==a||c!==n||this._startTimestamp>0||s<0,d=this.output.format.getSupportedAudioCodecs();if(!this._options.audio?.forceTranscode&&!this._options.audio?.bitrate&&!u&&d.includes(t)&&(!this._options.audio?.codec||this._options.audio.codec===t)){let l=new Wt(t);r=l,this._trackPromises.push((async()=>{await this._started;let p=new he(e),f={decoderConfig:await e.getDecoderConfig()??void 0},b=Number.isFinite(this._endTimestamp)?await p.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let g of p.packets(void 0,b)){if(this._synchronizer.shouldWait(e.id,g.timestamp)&&await this._synchronizer.wait(g.timestamp),this._canceled)return;await l.add(g,f),this._reportProgress(e.id,g.timestamp+g.duration)}l.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}let p=null;this._options.audio?.codec&&(d=d.filter(b=>b===this._options.audio.codec));let h=this._options.audio?.bitrate??lr,f=await Ct(d,{numberOfChannels:o,sampleRate:c,bitrate:h});if(!f.some(b=>Ce.includes(b))&&d.some(b=>Ce.includes(b))&&(o!==un||c!==ln)){let g=(await Ct(d,{numberOfChannels:un,sampleRate:ln,bitrate:h})).find(k=>Ce.includes(k));g&&(u=!0,p=g,o=un,c=ln)}else p=f[0]??null;if(p===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}if(u)r=this._resampleAudio(e,p,o,c,h);else{let b=new gt({codec:p,bitrate:h,onEncodedPacket:g=>this._reportProgress(e.id,g.timestamp+g.duration)});r=b,this._trackPromises.push((async()=>{await this._started;let g=new Ke(e);for await(let k of g.samples(void 0,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,k.timestamp)&&await this._synchronizer.wait(k.timestamp),this._canceled)return;await b.add(k),k.close()}b.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:e.languageCode}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}_resampleAudio(e,t,r,a,n){let s=new gt({codec:t,bitrate:n,onEncodedPacket:o=>this._reportProgress(e.id,o.timestamp+o.duration)});return this._trackPromises.push((async()=>{await this._started;let o=new pn({sourceNumberOfChannels:e.numberOfChannels,sourceSampleRate:e.sampleRate,targetNumberOfChannels:r,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:d=>s.add(d)}),u=new Ke(e).samples(this._startTimestamp,this._endTimestamp);for await(let d of u){if(this._synchronizer.shouldWait(e.id,d.timestamp)&&await this._synchronizer.wait(d.timestamp),this._canceled)return;await o.add(d)}await o.finalize(),s.close(),this._synchronizer.closeTrack(e.id)})()),s}_reportProgress(e,t){if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)??-1/0));let r=0;for(let[,s]of this._maxTimestamps)r+=s;let a=r/this._totalTrackCount,n=$(a/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},Ra=5,fn=class{constructor(){this.maxTimestamps=new Map;this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let r=this.resolvers[t];r.timestamp-e<Ra&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0));let r=this.computeMinAndMaybeResolve();return t-r>=Ra}wait(e){let{promise:t,resolve:r}=z();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},pn=class{constructor(e){this.sourceSampleRate=e.sourceSampleRate,this.targetSampleRate=e.targetSampleRate,this.sourceNumberOfChannels=e.sourceNumberOfChannels,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1,this.setupChannelMixer(),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels)}setupChannelMixer(){let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(r,a)=>r[a*e]:e===1&&t===4?this.channelMixer=(r,a,n)=>r[a*e]*+(n<2):e===1&&t===6?this.channelMixer=(r,a,n)=>r[a*e]*+(n===2):e===2&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .5*(r[n]+r[n+1])}:e===2&&t===4?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .25*(r[n]+r[n+1]+r[n+2]+r[n+3])}:e===4&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return .5*(r[s+n]+r[s+n+2])}:e===4&&t===6?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]:n===2||n===3?0:r[s+n-2]}:e===6&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return Math.SQRT1_2*(r[n]+r[n+1])+r[n+2]+.5*(r[n+4]+r[n+5])}:e===6&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return r[s+n]+Math.SQRT1_2*(r[s+2]+r[s+n+4])}:e===6&&t===4?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]+Math.SQRT1_2*r[s+2]:r[s+n+2]}:this.channelMixer=(r,a,n)=>n<e?r[a*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let r=new Float32Array(t);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(e){if(!e||e._closed)return;let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(a,{planeIndex:0,format:"f32"});let n=e.timestamp-this.startTime,s=e.numberOfFrames/this.sourceSampleRate,o=Math.min(n+s,this.endTime-this.startTime),c=Math.floor(n*this.targetSampleRate),u=Math.ceil(o*this.targetSampleRate);for(let d=c;d<u;d++){if(d<this.bufferStartFrame)continue;for(;d>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=d-this.bufferStartFrame;m(l<this.bufferSizeInFrames);let f=(d/this.targetSampleRate-n)*this.sourceSampleRate,b=Math.floor(f),g=Math.ceil(f),k=f-b;for(let y=0;y<this.targetNumberOfChannels;y++){let C=0,S=0;b>=0&&b<e.numberOfFrames&&(C=this.channelMixer(a,b,y)),g>=0&&g<e.numberOfFrames&&(S=this.channelMixer(a,g,y));let w=C+k*(S-C),T=l*this.targetNumberOfChannels+y;this.outputBuffer[T]+=w}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let r=this.bufferStartFrame/this.targetSampleRate,a=new ie({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:t});await this.onSample(a),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};export{xo as ALL_FORMATS,ka as ALL_TRACK_TYPES,j as AUDIO_CODECS,Ui as AudioBufferSink,Qi as AudioBufferSource,ie as AudioSample,Ke as AudioSampleSink,gt as AudioSampleSource,Ee as AudioSource,Bt as BaseMediaSampleSink,Ji as BlobSource,Yi as BufferSource,It as BufferTarget,Dt as CanvasSink,Hi as CanvasSource,mn as Conversion,tr as CustomAudioDecoder,ir as CustomAudioEncoder,er as CustomVideoDecoder,rr as CustomVideoEncoder,Wt as EncodedAudioPacketSource,D as EncodedPacket,he as EncodedPacketSink,zt as EncodedVideoPacketSource,qt as Input,X as InputAudioTrack,be as InputFormat,Qe as InputTrack,le as InputVideoTrack,Qt as IsobmffInputFormat,Vt as IsobmffOutputFormat,Pa as MATROSKA,Ia as MP3,xa as MP4,$t as MatroskaInputFormat,pt as MediaSource,$i as MediaStreamAudioTrackSource,Ki as MediaStreamVideoTrackSource,Ut as MkvOutputFormat,it as MovOutputFormat,si as Mp3InputFormat,Ni as Mp3OutputFormat,ii as Mp4InputFormat,Xr as Mp4OutputFormat,Ce as NON_PCM_AUDIO_CODECS,Aa as OGG,ci as OggInputFormat,Li as OggOutputFormat,Ht as Output,ge as OutputFormat,U as PCM_AUDIO_CODECS,va as QTFF,lr as QUALITY_HIGH,Va as QUALITY_LOW,Ua as QUALITY_MEDIUM,za as QUALITY_VERY_HIGH,Da as QUALITY_VERY_LOW,H as Quality,ni as QuickTimeInputFormat,ae as SUBTITLE_CODECS,Ie as Source,Zi as StreamSource,Ii as StreamTarget,bt as SubtitleSource,ze as Target,qi as TextSubtitleSource,en as UrlSource,q as VIDEO_CODECS,ce as VideoSample,mt as VideoSampleSink,ht as VideoSampleSource,Pe as VideoSource,_a as WAVE,Ea as WEBM,Wi as WavOutputFormat,oi as WaveInputFormat,ai as WebMInputFormat,st as WebMOutputFormat,$a as canEncode,hr as canEncodeAudio,gr as canEncodeSubtitles,pr as canEncodeVideo,Ct as getEncodableAudioCodecs,qa as getEncodableCodecs,Fn as getEncodableSubtitleCodecs,Rn as getEncodableVideoCodecs,ja as getFirstEncodableAudioCodec,Ga as getFirstEncodableSubtitleCodec,wi as getFirstEncodableVideoCodec,Ma as registerDecoder,Ba as registerEncoder};
|
|
16
|
+
${r.notes??""}`,p=this.createInternalChunk(d,o,r.duration,"key",l.trim()?ue.encode(l):null);s.chunkQueue.push(p),await this.interleaveChunks()}finally{n()}}async interleaveChunks(t=!1){if(!(!t&&!this.allTracksAreKnown())){e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.chunkQueue.length===0&&!s.track.source._closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<a&&(r=s,a=s.chunkQueue[0].timestamp)}if(!r)break;let n=r.chunkQueue.shift();this.writeBlock(r,n)}t||await this.writer.flush()}}fixVP9ColorSpace(t,r){if(r.type!=="key"||!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;let a=new K(r.data);a.skipBits(2);let n=a.readBits(1),o=(a.readBits(1)<<1)+n;if(o===3&&a.skipBits(1),a.readBits(1)||a.readBits(1)!==0||(a.skipBits(2),a.readBits(24)!==4817730))return;o>=2&&a.skipBits(1);let l={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];hn(r.data,a.pos,a.pos+3,l)}createInternalChunk(t,r,a,n,s=null){return{data:t,type:n,timestamp:r,duration:a,additions:s}}writeBlock(t,r){this.segment||(this.createTracks(),this.createSegment());let a=Math.round(1e3*r.timestamp),n=this.trackDatas.every(l=>{if(t===l)return r.type==="key";let p=l.chunkQueue[0];return p?p.type==="key":l.track.source._closed}),s=!1;if(!this.currentCluster)s=!0;else{m(this.currentClusterStartMsTimestamp!==null),m(this.currentClusterMaxMsTimestamp!==null);let l=a-this.currentClusterStartMsTimestamp;s=n&&a>this.currentClusterMaxMsTimestamp&&l>=1e3*(this.format._options.minimumClusterDuration??1)||l>mo}s&&this.createNewCluster(a);let o=a-this.currentClusterStartMsTimestamp;if(o<lo)return;let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|t.track.id),u.setInt16(1,o,!1);let d=Math.round(1e3*r.duration);if(d===0&&!r.additions){u.setUint8(3,+(r.type==="key")<<7);let l={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(l)}else{let l={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new At(t.lastWrittenMsTimestamp-a)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:165,data:r.additions},{id:238,data:1}]}]}:null,d>0?{id:155,data:d}:null]};this.ebmlWriter.writeEBML(l)}this.duration=Math.max(this.duration,a+d),t.lastWrittenMsTimestamp=a,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:a}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,a)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:da,data:[{id:231,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(m(this.currentCluster),!this.format._options.appendOnly){let n=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(n,da),this.writer.seek(s)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(n,s,this.currentClusterStartMsTimestamp/1e3)}let t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[n,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(n);let a=[...r.entries()].sort((n,s)=>n[0]-s[0]);for(let[n,s]of a)m(this.cues),this.cues.data.push({id:187,data:[{id:179,data:n},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:t}]}))]})}async onTrackClose(){let t=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let t=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||(this.createTracks(),this.createSegment()),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),m(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos(),a=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(a,ca),this.segmentDuration.data=new at(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),this.seekHead.data[0].data[1].data=this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset,this.seekHead.data[1].data[1].data=this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset,this.seekHead.data[2].data[1].data=this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset,this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(r)}t()}};var Ai={1:[-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],2:[-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],3:[-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1]},Ri={1:[-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],2:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1],3:[-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1]},Fi={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},ot=1483304551,Vr=1231971951,Ur=(i,e,t,r)=>Math.floor(i===3?(12*e/t+r)*4:144*e/t+r),ct=(i,e)=>i===3?e===3?21:36:e===3?13:21,zr=(i,e)=>{let t=e.pos,r=i>>>24,a=i>>>16&255,n=i>>>8&255,s=i&255;if(r!==255&&a!==255&&n!==255&&s!==255)return e.pos+=4,null;if(e.pos+=1,r!==255||(a&224)!==224)return null;let o=a>>3&3,c=a>>1&3,u=n>>4&15,d=n>>2&3,l=n>>1&1,p=s>>6&3,h=s>>4&3,f=s>>3&1,b=s>>2&1,g=s&3,k=o===3?Ai[c]?.[u]:Ri[c]?.[u];if(!k||k===-1)return null;let y=k*1e3,C=Fi[o]?.[d];if(!C||C===-1)return null;let S=Ur(c,y,C,l);if(e.fileSize!==null&&e.fileSize-t<S)return null;let w;return o===3?w=c===3?384:1152:c===3?w=384:c===2?w=1152:w=576,{startPos:t,totalSize:S,mpegVersionId:o,layer:c,bitrate:y,frequencyIndex:d,sampleRate:C,channel:p,modeExtension:h,copyright:f,original:b,emphasis:g,audioSamplesInFrame:w}};var Nr=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),r=255,a=224|e.mpegVersionId<<3|e.layer<<1,s=(e.mpegVersionId===3?Ai:Ri)?.[e.layer];if(!s)throw new Error("Invalid MPEG version and layer combination.");let o=Fi[e.mpegVersionId]?.[e.frequencyIndex];if(!o||o===-1)throw new Error("Invalid MPEG version and frequency index combination.");let c=0,u=155,d=s.findIndex(g=>Ur(e.layer,1e3*g,o,c)>=u);if(d===-1)throw new Error("No suitable bitrate found.");let l=d<<4|e.frequencyIndex<<2|c<<1,p=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=r,this.helper[1]=a,this.helper[2]=l,this.helper[3]=p,this.writer.write(this.helper.subarray(0,4));let h=ct(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(ot);let f=0;e.frameCount!==null&&(f|=1),e.fileSize!==null&&(f|=2),e.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let b=Ur(e.layer,1e3*s[d],o,c);this.writer.seek(t+b)}};var Wr=class extends se{constructor(t,r){super(t);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.format=r,this.writer=t._writer,this.mp3Writer=new Nr(t._writer)}async start(){}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(t,r){let a=await this.mutex.acquire();try{if(!this.xingFrameData){let n=Y(r.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=n.getUint32(0,!1),o=zr(s,{pos:0,fileSize:null});if(!o)throw new Error("Invalid MP3 header in sample.");let c=ct(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){let u=n.getUint32(c,!1);if(u===ot||u===Vr)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(t,r.timestamp,r.type==="key"),this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData)return;let t=await this.mutex.acquire(),r=this.writer.getPos();this.writer.seek(0);let a=new Uint8Array(100);for(let n=0;n<100;n++){let s=Math.floor(this.framePositions.length*(n/100));m(s!==-1&&s<this.framePositions.length);let o=this.framePositions[s];a[n]=256*(o/r)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,s)}this.writer.seek(r),t()}};var Rt=1399285583,po=79764919,la=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^po:e<<1;la[i]=e>>>0&4294967295}var Lr=i=>{let e=Y(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let a=0;a<i.length;a++){let n=i[a];r=(r<<8^la[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},Hr=(i,e,t)=>{let r=0,a=null;if(i.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,o=(1<<Sn(n-1))-1<<1,c=(i[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=t,d=e.vorbisInfo.modeBlockflags[c];if(a=e.vorbisInfo.blocksizes[d],d===1){let l=(o|1)+1,p=i[0]&l?1:0;u=e.vorbisInfo.blocksizes[p]}r=u!==null?u+a>>2:0}else e.codec==="opus"&&(r=Ln(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:a}},Kr=i=>{let e="audio/ogg";if(i.codecStrings){let t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var ut=27,He=282,Qr=He+255*255,dt=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos+=1,e.getUint8(t)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!0)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!0)}readI64(){let e=this.readU32();return this.readI32()*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readPageHeader(){let e=this.pos;if(this.readU32()!==Rt)return null;this.pos+=1;let r=this.readU8(),a=this.readI64(),n=this.readU32(),s=this.readU32(),o=this.readU32(),c=this.readU8(),u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=this.readU8();let d=27+c,l=u.reduce((h,f)=>h+f,0),p=d+l;return{headerStartPos:e,totalSize:p,dataStartPos:e+d,dataSize:l,headerType:r,granulePosition:a,serialNumber:n,sequenceNumber:s,checksum:o,lacingValues:u}}findNextPageHeader(e){for(;this.pos<e-3;){let t=this.readU32(),r=t&255,a=t>>>8&255,n=t>>>16&255,s=t>>>24&255,o=79;if(!(r!==o&&a!==o&&n!==o&&s!==o)){if(this.pos-=4,t===Rt)return!0;this.pos+=1}}return!1}};var ho=8192,$r=class extends se{constructor(t,r){super(t);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=z();this.pageBytes=new Uint8Array(Qr);this.pageView=new DataView(this.pageBytes.buffer);this.format=r,this.writer=t._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,Kr({codecStrings:this.trackDatas.map(t=>t.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(t,r){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;let n;do n=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===n));m(t.source._codec==="vorbis"||t.source._codec==="opus"),Fe(r),m(r),m(r.decoderConfig);let s={track:t,serialNumber:n,internalSampleRate:t.source._codec==="opus"?et:r.decoderConfig.sampleRate,codecInfo:{codec:t.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(t,r){if(m(r.decoderConfig),t.track.source._codec==="vorbis"){m(r.decoderConfig.description);let a=L(r.decoderConfig.description);if(a[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let n=1,s=()=>{let b=0;for(;;){let g=a[n++];if(g===void 0)throw new TypeError("Vorbis decoder description is too short.");if(b+=g,g<255)return b}},o=s(),c=s();if(a.length-n<=0)throw new TypeError("Vorbis decoder description is too short.");let d=a.subarray(n,n+=o),l=a.subarray(n,n+=c),p=a.subarray(n);t.packetQueue.push({data:d,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:l,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:p,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let f=Y(d).getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Pr(p).modeBlockflags}}else if(t.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let a=L(r.decoderConfig.description),n=new Uint8Array(16),s=new DataView(n.buffer);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1),s.setUint32(8,0,!0),s.setUint32(12,0,!0),t.packetQueue.push({data:a,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:n,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),t.codecInfo.opusInfo={preSkip:Oe(a).preSkip}}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=Hr(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u,s.packetQueue.push({data:r.data,endGranulePosition:s.currentTimestampInSamples,timestamp:o/s.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{n()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async interleavePages(t=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let a=r.packetQueue.shift();if(this.writePacket(r,a,!1),a.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,a=1/0;for(let o of this.trackDatas){if(!t&&o.packetQueue.length<=1&&!o.track.source._closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestamp<a&&(r=o,a=o.packetQueue[0].timestamp)}if(!r)break;let n=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,n,s)}t||await this.writer.flush()}writePacket(t,r,a){let n=r.data.length,s=0,o=0;for(;;){t.currentLacingValues.length===0&&s>0&&(t.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,n);t.currentLacingValues.push(u),t.currentPageSize++,o+=u;let d=n<255;if(t.currentLacingValues.length===255){let l=r.data.subarray(s,o);if(s=o,t.currentPageData.push(l),t.currentPageSize+=l.length,this.writePage(t,a&&d),d)return}if(d)break;n-=255}let c=r.data.subarray(s);t.currentPageData.push(c),t.currentPageSize+=c.length,t.currentGranulePosition=r.endGranulePosition,(t.currentPageSize>=ho||r.forcePageFlush)&&this.writePage(t,a)}writePage(t,r){this.pageView.setUint32(0,Rt,!0),this.pageView.setUint8(4,0);let a=0;t.currentPageStartsWithFreshPacket||(a|=1),t.pagesWritten===0&&(a|=2),r&&(a|=4),this.pageView.setUint8(5,a);let n=t.currentLacingValues.every(u=>u===255)?-1:t.currentGranulePosition;yn(this.pageView,6,n,!0),this.pageView.setUint32(14,t.serialNumber,!0),this.pageView.setUint32(18,t.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,t.currentLacingValues.length),this.pageBytes.set(t.currentLacingValues,27);let s=27+t.currentLacingValues.length;for(let u of t.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=Lr(o);if(this.pageView.setUint32(22,c,!0),t.pagesWritten++,t.currentLacingValues.length=0,t.currentPageData.length=0,t.currentPageSize=27,t.currentPageStartsWithFreshPacket=!0,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:u,start:d}=this.writer.stopTrackingWrites();this.format._options.onPage(u,d,t.track.source)}}async onTrackClose(){let t=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){let t=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);t()}};var oe=class{constructor(e){this.input=e}};var ee=new Uint8Array(0),D=class i{constructor(e,t,r,a,n=-1,s){this.data=e;this.type=t;this.timestamp=r;this.duration=a;this.sequenceNumber=n;if(e===ee&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=s}get isMetadataOnly(){return this.data===ee}get microsecondTimestamp(){return Math.trunc(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*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})}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){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let t=new Uint8Array(e.byteLength);return e.copyTo(t),new i(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}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 i(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var ma=i=>{let r=i,a=4096,n=0,s=12,o=0;for(r<0&&(r=-r,n=128),r+=33,r>8191&&(r=8191);(r&a)!==a&&s>=5;)a>>=1,s--;return o=r>>s-4&15,~(n|s-5<<4|o)&255},fa=i=>{let t=0,r=0,a=~i;a&128&&(a&=-129,t=-1),r=((a&240)>>4)+5;let n=(1<<r|(a&15)<<r-4|1<<r-5)-33;return t===0?n:-n},pa=i=>{let t=2048,r=0,a=11,n=0,s=i;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&a>=5;)t>>=1,a--;return n=s>>(a===4?1:a-4)&15,(r|a-4<<4|n)^85},ha=i=>{let e=0,t=0,r=i^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let a=0;return t!==4?a=1<<t|(r&15)<<t-4|1<<t-5:a=r<<1|1,e===0?a:-a};var ce=class i{constructor(e,t){this._closed=!1;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=L(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=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(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new i(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*me),duration:Math.trunc((t.duration??0)*me)}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(r,a),s=n.getContext("2d",{alpha:!1,willReadFrequently:!0});m(s),s.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=r,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}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(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*this.duration)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Ft(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration}):this._data instanceof Uint8Array?new i(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace}):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace})}close(){this._closed||(Ft(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Ft(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!Ge(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),Ft(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)L(e).set(this._data);else{let r=this._data.getContext("2d",{alpha:!1});m(r);let a=r.getImageData(0,0,this.codedWidth,this.codedHeight);L(e).set(a.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),Ft(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,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,r,a,n,s,o,c,u){let d=0,l=0,p=this.displayWidth,h=this.displayHeight,f=0,b=0,g=this.displayWidth,k=this.displayHeight;if(s!==void 0?(d=t,l=r,p=a,h=n,f=s,b=o,c!==void 0?(g=c,k=u):(g=p,k=h)):(f=t,b=r,a!==void 0&&(g=a,k=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(k)||k<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[d,l,p,h]=[l,this.codedHeight-d-p,h,p]:this.rotation===180?[d,l]=[this.codedWidth-d-p,this.codedHeight-l-h]:this.rotation===270&&([d,l,p,h]=[this.codedWidth-l-h,d,h,p]);let y=this.toCanvasImageSource();e.save();let C=f+g/2,S=b+k/2;e.translate(C,S),e.rotate(this.rotation*Math.PI/180);let w=this.rotation%180===0?1:g/k;e.scale(1/w,w),e.drawImage(y,d,l,p,h,-g/2,-k/2,g,k),e.restore()}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Uint8Array){let 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}},Ft=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Oi=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),ie=class i{constructor(e){this._closed=!1;if(Mt(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(!Oi.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.");let t=e.data.byteLength/(Ot(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let r;if(e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let a=this.numberOfFrames*this.numberOfChannels*Ot(this.format);if(r.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}get microsecondTimestamp(){return Math.trunc(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*this.duration)}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&&!Oi.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.");let t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let a=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(a>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let n=Ot(t),s=qr(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?a:a*this.numberOfChannels)*n}copyTo(e,t){if(!Ge(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Oi.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:r,format:a,frameCount:n,frameOffset:s}=t,o=a??this.format;if(!o)throw new Error("Destination format not determined");let c=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=c)throw new RangeError("frameOffset out of range");let l=n!==void 0?n:c-d;if(l>c-d)throw new RangeError("frameCount out of range");let p=Ot(o),h=qr(o);if(h&&r>=u)throw new RangeError("planeIndex out of range");if(!h&&r!==0)throw new RangeError("planeIndex out of range");let b=(h?l:l*u)*p;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");let g=Y(e),k=bo(o);if(Mt(this._data))if(h)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});else{let y=new ArrayBuffer(l*4),C=new Float32Array(y);this._data.copyTo(C,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});let S=new DataView(y);for(let w=0;w<l;w++){let T=w*p,x=S.getFloat32(w*4,!0);k(g,T,x)}}else{let y=u,C=new Float32Array(l);for(let S=0;S<y;S++){this._data.copyTo(C,{planeIndex:S,frameOffset:d,frameCount:l,format:"f32-planar"});for(let w=0;w<l;w++){let x=(w*y+S)*p;k(g,x,C[w])}}}else{let y=this._data,C=new DataView(y.buffer,y.byteOffset,y.byteLength),S=this.format,w=go(S),T=Ot(S),x=qr(S);for(let E=0;E<l;E++)if(h){let I=E*p,A;x?A=(r*c+(E+d))*T:A=((E+d)*u+r)*T;let _=w(C,A);k(g,I,_)}else for(let I=0;I<u;I++){let _=(E*u+I)*p,te;x?te=(I*c+(E+d))*T:te=((E+d)*u+I)*T;let ke=w(C,te);k(g,_,ke)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Mt(this._data)){let e=new i(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new i({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Mt(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Mt(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(qr(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let 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})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}},Ot=i=>{switch(i){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")}},qr=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},go=i=>{switch(i){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},bo=i=>{switch(i){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,$((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,$(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,$(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Mt=i=>typeof AudioData<"u"&&i instanceof AudioData;var lt=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},ve=i=>{if(typeof i!="number"||Number.isNaN(i))throw new TypeError("timestamp must be a number.")},Mi=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let a=await i.determinePacketType(r);return a&&(r.type=a),r}):e,he=class{constructor(e){if(!(e instanceof Qe))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return lt(e),Mi(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return ve(e),lt(t),Mi(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");return lt(t),Mi(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(ve(e),lt(t),!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(lt(t),!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return!r||r.type==="delta"?r:await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(e!==void 0&&!(e instanceof D))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof D))throw new TypeError("endPacket must be an EncodedPacket.");lt(r);let a=[],{promise:n,resolve:s}=z(),{promise:o,resolve:c}=z(),u=!1,d=!1,l=null,p=[],h=()=>Math.max(2,p.length);return(async()=>{let f=e??await this.getFirstPacket(r);for(;f&&!d&&!(t&&f.sequenceNumber>=t?.sequenceNumber);){if(a.length>h()){({promise:o,resolve:c}=z()),await o;continue}a.push(f),s(),{promise:n,resolve:s}=z(),f=await this.getNextPacket(f,r)}u=!0,s()})().catch(f=>{l||(l=f,s())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(l)throw l;if(a.length>0){let f=a.shift(),b=performance.now();for(p.push(b);p.length>0&&b-p[0]>=1e3;)p.shift();return c(),{value:f,done:!1}}else{if(u)return{value:void 0,done:!0};await n}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},Bt=class{constructor(e,t){this.onSample=e;this.onError=t}},Dt=class{mediaSamplesInRange(e=0,t=1/0){ve(e),ve(t);let r=[],a=!1,n=null,{promise:s,resolve:o}=z(),{promise:c,resolve:u}=z(),d=!1,l=!1,p=!1,h=null;return(async()=>{let f=new Error,b=await this._createDecoder(w=>{if(u(),w.timestamp>=t&&(l=!0),l){w.close();return}n&&(w.timestamp>e?(r.push(n),a=!0):n.close()),w.timestamp>=e&&(r.push(w),a=!0),n=a?null:w,r.length>0&&(o(),{promise:s,resolve:o}=z())},w=>{h||(w.stack=f.stack,h=w,o())}),g=this._createPacketSink(),k=await g.getKeyPacket(e,{verifyKeyPackets:!0})??await g.getFirstPacket();if(!k)return;let y=k,C;if(t<1/0){let w=await g.getPacket(t),T=w?w.type==="key"&&w.timestamp===t?w:await g.getNextKeyPacket(w,{verifyKeyPackets:!0}):null;T&&(C=T)}let S=g.packets(k,C);for(await S.next();y&&!l;){let w=ga(r.length);if(r.length+b.getDecodeQueueSize()>w){({promise:c,resolve:u}=z()),await c;continue}b.decode(y);let T=await S.next();if(T.done)break;y=T.value}await S.return(),p||await b.flush(),b.close(),!a&&n&&r.push(n),d=!0,o()})().catch(f=>{h||(h=f,o())}),{async next(){for(;;){if(p)return{value:void 0,done:!0};if(h)throw h;if(r.length>0){let f=r.shift();return u(),{value:f,done:!1}}else if(!d)await s;else return{value:void 0,done:!0}}},async return(){p=!0,l=!0,u(),o(),n?.close();for(let f of r)f.close();return{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){kn(e);let t=bn(e),r=[],a=[],{promise:n,resolve:s}=z(),{promise:o,resolve:c}=z(),u=!1,d=!1,l=null,p=h=>{a.push(h),s(),{promise:n,resolve:s}=z()};return(async()=>{let h=new Error,f=await this._createDecoder(w=>{if(c(),d){w.close();return}let T=0;for(;r.length>0&&w.timestamp-r[0]>-1e-10;)T++,r.shift();if(T>0)for(let x=0;x<T;x++)p(x<T-1?w.clone():w);else w.close()},w=>{l||(w.stack=h.stack,l=w,s())}),b=this._createPacketSink(),g=null,k=null,y=-1,C=async()=>{m(k);let w=k;for(f.decode(w);w.sequenceNumber<y;){let T=ga(a.length);for(;a.length+f.getDecodeQueueSize()>T&&!d;)({promise:o,resolve:c}=z()),await o;if(d)break;let x=await b.getNextPacket(w);m(x),w=x,f.decode(x)}y=-1},S=async()=>{await f.flush();for(let w=0;w<r.length;w++)p(null);r.length=0};for await(let w of t){if(ve(w),d)break;let T=await b.getPacket(w),x=T&&await b.getKeyPacket(w,{verifyKeyPackets:!0});if(!x){y!==-1&&(await C(),await S()),p(null),g=null;continue}g&&(x.sequenceNumber!==k.sequenceNumber||T.timestamp<g.timestamp)&&(await C(),await S()),r.push(T.timestamp),y=Math.max(T.sequenceNumber,y),g=T,k=x}d||(y!==-1&&await C(),await S()),f.close(),u=!0,s()})().catch(h=>{l||(l=h,s())}),{async next(){for(;;){if(d)return{value:void 0,done:!0};if(l)throw l;if(a.length>0){let h=a.shift();return m(h!==void 0),c(),{value:h,done:!1}}else if(!u)await n;else return{value:void 0,done:!0}}},async return(){d=!0,c(),s();for(let h of a)h?.close();return{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},ga=i=>i===0?40:8,Bi=class extends Bt{constructor(t,r,a,n,s,o){super(t,r);this.rotation=s;this.timeResolution=o;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new _e;this.customDecoderQueueSize=0;this.sampleQueue=[];let c=d=>{if(this.sampleQueue.length>0&&d.timestamp>=V(this.sampleQueue).timestamp){for(let p of this.sampleQueue)this.finalizeAndEmitSample(p);this.sampleQueue.length=0}let l=F(this.sampleQueue,d.timestamp,p=>p.timestamp);this.sampleQueue.splice(l+1,0,d)},u=St.find(d=>d.supports(a,n));u?(this.customDecoder=new u,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=d=>{if(!(d instanceof ce))throw new TypeError("The argument passed to onSample must be a VideoSample.");c(d)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new VideoDecoder({output:d=>c(new ce(d)),error:r}),this.decoder.configure(n))}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(t.toEncodedVideoChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await this.decoder.flush());for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close());for(let t of this.sampleQueue)t.close();this.sampleQueue.length=0}},mt=class extends Dt{constructor(e){if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._videoTrack=e}async _createDecoder(e,t){if(!await this._videoTrack.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._videoTrack.codec,a=this._videoTrack.rotation,n=await this._videoTrack.getDecoderConfig(),s=this._videoTrack.timeResolution;return m(r&&n),new Bi(e,t,r,n,a,s)}_createPacketSink(){return new he(this._videoTrack)}async getSample(e){ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},Vt=class{constructor(e,t={}){this._nextCanvasIndex=0;if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[a,n]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=a/n;t.width!==void 0&&t.height===void 0?(a=t.width,n=Math.round(a/s)):t.width===void 0&&t.height!==void 0?(n=t.height,a=Math.round(n*s)):t.width!==void 0&&t.height!==void 0&&(a=t.width,n=t.height),this._videoTrack=e,this._width=a,this._height=n,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new mt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex];t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t)),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext("2d",{alpha:!1});m(r),r.resetTransform();let a,n,s,o;if(this._fit==="fill")a=0,n=0,s=this._width,o=this._height;else{let[d,l]=this._rotation%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],p=this._fit==="contain"?Math.min(this._width/d,this._height/l):Math.max(this._width/d,this._height/l);s=d*p,o=l*p,a=(this._width-s)/2,n=(this._height-o)/2}let c=this._rotation%180===0?1:s/o;r.translate(this._width/2,this._height/2),r.rotate(this._rotation*Math.PI/180),r.scale(1/c,c),r.translate(-this._width/2,-this._height/2),r.drawImage(e.toCanvasImageSource(),a,n,s,o);let u={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),u}async getCanvas(e){ve(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return wt(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return wt(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},Di=class extends Bt{constructor(t,r,a,n){super(t,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new _e;this.customDecoderQueueSize=0;let s=c=>{let u=n.sampleRate;c.setTimestamp(Math.round(c.timestamp*u)/u),t(c)},o=Ct.find(c=>c.supports(a,n));o?(this.customDecoder=new o,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof ie))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:c=>s(new ie(c)),error:r}),this.decoder.configure(n))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(t.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}},Vi=class extends Bt{constructor(t,r,a){super(t,r);this.decoderConfig=a;this.currentTimestamp=null;m(U.includes(a.codec)),this.codec=a.codec;let{dataType:n,sampleSize:s,littleEndian:o}=G(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:n==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):n==="ulaw"?this.readInputValue=(c,u)=>fa(c.getUint8(u)):n==="alaw"?this.readInputValue=(c,u)=>ha(c.getUint8(u)):m(!1);break;case 2:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:n==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):m(!1);break;case 3:n==="unsigned"?this.readInputValue=(c,u)=>hi(c,u,o)-2**23:n==="signed"?this.readInputValue=(c,u)=>wn(c,u,o):m(!1);break;case 4:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:n==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):n==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):m(!1);break;case 8:n==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):m(!1);break;default:Re(s),m(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,d)=>c.setUint8(u,d+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0);break;default:Re(s),m(!1)}}getDecodeQueueSize(){return 0}decode(t){let r=Y(t.data),a=t.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=a*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),o=new DataView(s);for(let l=0;l<a*this.decoderConfig.numberOfChannels;l++){let p=l*this.inputSampleSize,h=l*this.outputSampleSize,f=this.readInputValue(r,p);this.writeOutputValue(o,h,f)}let c=a/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=t.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let d=new ie({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:a,timestamp:u});this.onSample(d)}async flush(){}close(){}},Ke=class extends Dt{constructor(e){if(!(e instanceof X))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._audioTrack=e}async _createDecoder(e,t){if(!await this._audioTrack.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._audioTrack.codec,a=await this._audioTrack.getDecoderConfig();return m(r&&a),U.includes(a.codec)?new Vi(e,t,a):new Di(e,t,r,a)}_createPacketSink(){return new he(this._audioTrack)}async getSample(e){ve(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},Ui=class{constructor(e){if(!(e instanceof X))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ke(e)}_audioSampleToWrappedArrayBuffer(e){return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}async getBuffer(e){ve(e);let t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return wt(this._audioSampleSink.samples(e,t),r=>this._audioSampleToWrappedArrayBuffer(r))}buffersAtTimestamps(e){return wt(this._audioSampleSink.samplesAtTimestamps(e),t=>t&&this._audioSampleToWrappedArrayBuffer(t))}};var Qe=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof le}isAudioTrack(){return this instanceof X}get id(){return this._backing.getId()}get languageCode(){return this._backing.getLanguageCode()}get timeResolution(){return this._backing.getTimeResolution()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new he(this),r=1/0,a=-1/0,n=0,s=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),n++,s+=o.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(a-r)).toPrecision(16)):0,averageBitrate:n?Number((8*s/(a-r)).toPrecision(16)):0}}},le=class extends Qe{constructor(e){super(e),this._backing=e}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return m(t!==null),St.some(a=>a.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");return this.codec===null?null:Hn(this,e)}},X=class extends Qe{constructor(e){super(e),this._backing=e}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return m(t!==null),Ct.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var de=class{constructor(e,t=1/0){this.source=e;this.maxStorableBytes=t;this.loadedSegments=[];this.loadingSegments=[];this.sourceSizePromise=null;this.nextAge=0;this.totalStoredBytes=0}async loadRange(e,t){if(t=Math.min(t,await this.source.getSize()),e>=t)return;let r=this.loadingSegments.find(c=>c.start<=e&&c.end>=t);if(r){await r.promise;return}let a=F(this.loadedSegments,e,c=>c.start);if(a!==-1)for(let c=a;c<this.loadedSegments.length;c++){let u=this.loadedSegments[c];if(u.start>e)break;if(u.end>=t)return}this.source.onread?.(e,t);let n=this.source._read(e,t),s={start:e,end:t,promise:n};this.loadingSegments.push(s);let o=await n;gn(this.loadingSegments,s),this.insertIntoLoadedSegments(e,o)}rangeIsLoaded(e,t){if(t<=e)return!0;let r=F(this.loadedSegments,e,a=>a.start);if(r===-1)return!1;for(let a=r;a<this.loadedSegments.length;a++){let n=this.loadedSegments[a];if(n.start>e)break;if(n.end>=t)return!0}return!1}insertIntoLoadedSegments(e,t){let r={start:e,end:e+t.byteLength,bytes:t,view:new DataView(t.buffer),age:this.nextAge++},a=F(this.loadedSegments,e,n=>n.start);(a===-1||this.loadedSegments[a].start<r.start)&&a++,this.loadedSegments.splice(a,0,r),this.totalStoredBytes+=t.byteLength;for(let n=a+1;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>=r.end)break;r.start<=s.start&&s.end<=r.end&&(this.loadedSegments.splice(n,1),n--)}for(;this.totalStoredBytes>this.maxStorableBytes&&this.loadedSegments.length>1;){let n=null,s=-1;for(let o=0;o<this.loadedSegments.length;o++){let c=this.loadedSegments[o];(!n||c.age<n.age)&&(n=c,s=o)}m(n),this.totalStoredBytes-=n.bytes.byteLength,this.loadedSegments.splice(s,1)}}getViewAndOffset(e,t){let r=F(this.loadedSegments,e,n=>n.start),a=null;if(r!==-1)for(let n=r;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>e)break;if(t<=s.end){a=s;break}}if(!a)throw new Error(`No segment loaded for range [${e}, ${t}).`);return a.age=this.nextAge++,{view:a.view,offset:a.bytes.byteOffset+e-a.start}}forgetRange(e,t){if(t<=e)return;let r=F(this.loadedSegments,e,n=>n.start);if(r===-1)return;let a=this.loadedSegments[r];a.start!==e||a.end!==t||(this.loadedSegments.splice(r,1),this.totalStoredBytes-=a.bytes.byteLength)}};var $e=class{constructor(e){this.reader=e;this.pos=0;this.littleEndian=!0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,this.littleEndian)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,this.littleEndian)}readU64(){let e,t;return this.littleEndian?(e=this.readU32(),t=this.readU32()):(t=this.readU32(),e=this.readU32()),t*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}};var jr=class extends oe{constructor(t){super(t);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.tracks=[];this.metadataReader=new $e(t._mainReader),this.chunkReader=new $e(new de(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.metadataReader.reader.source.getSize(),r=this.metadataReader.readAscii(4);this.metadataReader.littleEndian=r!=="RIFX";let a=r==="RF64",n=this.metadataReader.readU32(),s=a?t:Math.min(n+8,t);if(this.metadataReader.readAscii(4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");this.metadataReader.pos=12;let c=0,u=null;for(;this.metadataReader.pos<s;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+8);let l=this.metadataReader.readAscii(4),p=this.metadataReader.readU32(),h=this.metadataReader.pos;if(a&&c===0&&l!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(l==="fmt ")await this.parseFmtChunk(p);else if(l==="data")u??=p,this.dataStart=this.metadataReader.pos,this.dataSize=Math.min(u,s-this.dataStart);else if(l==="ds64"){let f=this.metadataReader.readU64();u=this.metadataReader.readU64(),s=Math.min(f+8,t)}this.metadataReader.pos=h+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new X(new zi(this)))})()}async parseFmtChunk(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+t);let r=this.metadataReader.readU16(),a=this.metadataReader.readU16(),n=this.metadataReader.readU32();this.metadataReader.pos+=4;let s=this.metadataReader.readU16(),o;if(t===14?o=8:o=this.metadataReader.readU16(),t>=18&&r!==357){let c=this.metadataReader.readU16(),u=t-18;if(Math.min(u,c)>=22&&r===65534){this.metadataReader.pos+=6;let l=this.metadataReader.readBytes(16);r=l[0]|l[1]<<8}}(r===7||r===6)&&(o=8),this.audioInfo={format:r,numberOfChannels:a,sampleRate:n,sampleSizeInBytes:Math.ceil(o/8),blockSizeInBytes:s}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===3&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){return await this.readMetadata(),m(this.audioInfo),this.dataSize/this.audioInfo.blockSizeInBytes/this.audioInfo.sampleRate}async getTracks(){return await this.readMetadata(),this.tracks}},ft=2048,zi=class{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(m(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}computeDuration(){return this.demuxer.computeDuration()}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getLanguageCode(){return Z}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){m(this.demuxer.audioInfo);let r=e*ft*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let a=Math.min(ft*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r),n;if(t.metadataOnly)n=ee;else{let c=ft*this.demuxer.audioInfo.blockSizeInBytes,u=Math.ceil(2**19/c)*c,d=Math.floor(r/u)*u,l=d+u;await this.demuxer.chunkReader.reader.loadRange(this.demuxer.dataStart+d,this.demuxer.dataStart+l),this.demuxer.chunkReader.pos=this.demuxer.dataStart+r,n=this.demuxer.chunkReader.readBytes(a)}let s=e*ft/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return new D(n,"key",s,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){m(this.demuxer.audioInfo);let r=Math.floor(e*this.demuxer.audioInfo.sampleRate/ft);return this.getPacketAtIndex(r,t)}getNextPacket(e,t){m(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/ft);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Gr=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}};var Xr=class extends se{constructor(t,r){super(t);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.format=r,this.writer=t._writer,this.riffWriter=new Gr(t._writer),this.isRf64=!!r._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{if(this.headerWritten||(Fe(a),m(a),m(a.decoderConfig),this.writeHeader(t,a.decoderConfig),this.sampleRate=a.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(t,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(t,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let a,n=t.source._codec,s=G(n);s.dataType==="ulaw"?a=7:s.dataType==="alaw"?a=6:s.dataType==="float"?a=3:a=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(a),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.format._options.onHeader){let{data:d,start:l}=this.writer.stopTrackingWrites();this.format._options.onHeader(d,l)}}async finalize(){let t=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(this.writer.seek(20),this.riffWriter.writeU64(r-8),this.writer.seek(28),this.riffWriter.writeU64(this.dataSize),this.writer.seek(36),this.riffWriter.writeU64(this.sampleCount)):(this.writer.seek(4),this.riffWriter.writeU32(r-8),this.writer.seek(40),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(r),t()}};var ge=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>q.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>j.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ae.includes(e))}_codecUnsupportedHint(e){return""}},Ut=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError('options.fastStart, when provided, must be false, "in-memory", 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.");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 Fr(e,this)}},Yr=class extends Ut{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...q,...Ce,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ae]}_codecUnsupportedHint(e){return new it().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},it=class extends Ut{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...q,...j]}_codecUnsupportedHint(e){return new Yr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},zt=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Dr(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...q,...Ce,...U.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...ae]}get supportsVideoRotationMetadata(){return!1}},st=class extends zt{getSupportedCodecs(){return[...q.filter(e=>["vp8","vp9","av1"].includes(e)),...j.filter(e=>["opus","vorbis"].includes(e)),...ae]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new zt().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Ni=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Wr(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}},Wi=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Xr(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...U.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}},Li=class extends ge{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new $r(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:1/0},subtitle:{min:0,max:0},total:{min:1,max:2**32}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...j.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}};var pt=class{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.")}_start(){}async _flushAndClose(){}close(){if(this._closingPromise)return;let 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(),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForClose(){return this._closingPromise?this._closingPromise:this._flushAndClose()}},Pe=class extends pt{constructor(t){super();this._connectedTrack=null;if(!q.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${q.join(", ")}.`);this._codec=t}},Nt=class extends Pe{constructor(e){super(e)}add(e,t){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},ji=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!q.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${q.join(", ")}.`);if(!(i.bitrate instanceof H)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(i.latencyMode!==void 0&&!["quality","realtime"].includes(i.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},Wt=class{constructor(e,t){this.source=e;this.encodingConfig=t;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.lastWidth=null;this.lastHeight=null;this.customEncoder=null;this.customEncoderCallSerializer=new _e;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t,r){if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastWidth!==null&&this.lastHeight!==null){if(e.codedWidth!==this.lastWidth||e.codedHeight!==this.lastHeight)throw new Error(`Video sample size must remain constant. Expected ${this.lastWidth}x${this.lastHeight}, got ${e.codedWidth}x${e.codedHeight}.`)}else this.lastWidth=e.codedWidth,this.lastHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);let a=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/a),s={...r,keyFrame:r?.keyFrame||a===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;let o=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,s)).then(()=>{this.customEncoderQueueSize--,t&&e.close()}).catch(c=>{this.encoderError??=c});this.customEncoderQueueSize>=4&&await o}else{m(this.encoder);let o=e.toVideoFrame();this.encoder.encode(o,s),o.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(c=>this.encoder.addEventListener("dequeue",c,{once:!0}))}await this.muxer.mutex.currentPromise}async ensureEncoder(e){if(!this.encoder)return this.ensureEncoderPromise=(async()=>{let t=e.codedWidth,r=e.codedHeight,a=this.encodingConfig.bitrate instanceof H?this.encodingConfig.bitrate._toVideoBitrate(this.encodingConfig.codec,t,r):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??ar(this.encodingConfig.codec,t,r,a),width:t,height:r,bitrate:a,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.encodingConfig.latencyMode,...or(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=Ze.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof D))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(!(await VideoEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.width}x${n.height}) is not supported by this browser. Consider using another codec or changing your video parameters.`);this.encoder=new VideoEncoder({output:(c,u)=>{let d=D.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(d,u),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,d,u)},error:c=>{this.encoderError??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(){this.checkForEncoderError(),this.customEncoder?(this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError.stack=new Error().stack,this.encoderError}},ht=class extends Pe{constructor(e){ji(e),super(e.codec),this._encoder=new Wt(this,e)}add(e,t){if(!(e instanceof ce))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(){return this._encoder.flushAndClose()}},Hi=class extends Pe{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ji(t),super(t.codec),this._encoder=new Wt(this,t),this._canvas=e}add(e,t=0,r){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let a=new ce(this._canvas,{timestamp:e,duration:t});return this._encoder.add(a,!0,r)}_flushAndClose(){return this._encoder.flushAndClose()}},Ki=class extends Pe{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");ji(r),r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._encoder=new Wt(this,r),this._track=t}_start(){this._abortController=new AbortController;let t=!1,r=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:n=>{if(t||(ba(this,n),t=!0),this._encoder.getQueueSize()>=4){n.close();return}this._encoder.add(new ce(n),!0).catch(s=>{throw this._abortController?.abort(),s})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(n=>{n instanceof DOMException&&n.name==="AbortError"||console.error("Pipe error:",n)})}async _flushAndClose(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flushAndClose()}},Ee=class extends pt{constructor(t){super();this._connectedTrack=null;if(!j.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${j.join(", ")}.`);this._codec=t}},Lt=class extends Ee{constructor(e){super(e)}add(e,t){if(!(e instanceof D))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Gi=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!j.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${j.join(", ")}.`);if(i.bitrate===void 0&&(!U.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(i.bitrate!==void 0&&!(i.bitrate instanceof H)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},Ht=class{constructor(e,t){this.source=e;this.encodingConfig=t;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new _e;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t){if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized),this.customEncoder){this.customEncoderQueueSize++;let r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e)).then(()=>{this.customEncoderQueueSize--,t&&e.close()}).catch(a=>{this.encoderError??=a});this.customEncoderQueueSize>=4&&await r,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{m(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(a=>this.encoder.addEventListener("dequeue",a,{once:!0})),await this.muxer.mutex.currentPromise}}async doPcmEncoding(e,t){m(this.outputSampleSize),m(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:a,sampleRate:n,timestamp:s}=e,o=2048,c=[];for(let p=0;p<a;p+=o){let h=Math.min(o,e.numberOfFrames-p),f=h*r*this.outputSampleSize,b=new ArrayBuffer(f),g=new DataView(b);c.push({frameCount:h,view:g})}let u=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let p=0;p<r;p++){e.copyTo(d,{planeIndex:p,format:"f32-planar"});for(let h=0;h<c.length;h++){let{frameCount:f,view:b}=c[h];for(let g=0;g<f;g++)this.writeOutputValue(b,(g*r+p)*this.outputSampleSize,d[h*o+g])}}t&&e.close();let l={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:n}};for(let p=0;p<c.length;p++){let{frameCount:h,view:f}=c[p],b=f.buffer,g=p*o,k=new D(new Uint8Array(b),"key",s+g/n,h/n);this.encodingConfig.onEncodedPacket?.(k,l),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,k,l)}}ensureEncoder(e){if(!this.encoderInitialized)return this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,a=this.encodingConfig.bitrate instanceof H?this.encodingConfig.bitrate._toAudioBitrate(this.encodingConfig.codec):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??sr(this.encodingConfig.codec,t,r),numberOfChannels:t,sampleRate:r,bitrate:a,...cr(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=Je.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof D))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else if(U.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,u)=>{let d=D.fromEncodedChunk(c);this.encodingConfig.onEncodedPacket?.(d,u),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,u)},error:c=>{this.encoderError??=c}}),this.encoder.configure(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:a}=G(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint8(s,$((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,s,o)=>{n.setInt8(s,$(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,s,o)=>{let c=$(Math.floor(o*32767),-32768,32767);n.setUint8(s,ma(c))}:t==="alaw"?this.writeOutputValue=(n,s,o)=>{let c=$(Math.floor(o*32767),-32768,32767);n.setUint8(s,pa(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint16(s,$((o+1)*32767.5,0,65535),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt16(s,$(Math.round(o*32767),-32768,32767),a):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,s,o)=>gi(n,s,$((o+1)*83886075e-1,0,16777215),a):t==="signed"?this.writeOutputValue=(n,s,o)=>Tn(n,s,$(Math.round(o*8388607),-8388608,8388607),a):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint32(s,$((o+1)*21474836475e-1,0,4294967295),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt32(s,$(Math.round(o*2147483647),-2147483648,2147483647),a):t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat32(s,o,a):m(!1);break;case 8:t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat64(s,o,a):m(!1);break;default:Re(r),m(!1)}}async flushAndClose(){this.checkForEncoderError(),this.customEncoder?(this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError.stack=new Error().stack,this.encoderError}},gt=class extends Ee{constructor(e){Gi(e),super(e.codec),this._encoder=new Ht(this,e)}add(e){if(!(e instanceof ie))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(){return this._encoder.flushAndClose()}},Qi=class extends Ee{constructor(t){Gi(t);super(t.codec);this._accumulatedFrameCount=0;this._encoder=new Ht(this,t)}add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=64*1024*1024,a=t.numberOfChannels,n=t.sampleRate,s=t.length,o=Math.floor(r/a),c=0,u=s,d=[];for(;u>0;){let l=Math.min(o,u),p=new Float32Array(a*l);for(let f=0;f<a;f++)t.copyFromChannel(p.subarray(f*l,f*l+l),f,c);let h=new ie({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:a,timestamp:(this._accumulatedFrameCount+c)/n,data:p});d.push(this._encoder.add(h,!0)),c+=l,u-=l}return this._accumulatedFrameCount+=s,Promise.all(d)}_flushAndClose(){return this._encoder.flushAndClose()}},$i=class extends Ee{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");Gi(r);super(r.codec);this._abortController=null;this._encoder=new Ht(this,r),this._track=t}_start(){this._abortController=new AbortController;let t=!1,r=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:n=>{if(t||(ba(this,n),t=!0),this._encoder.getQueueSize()>=4){n.close();return}this._encoder.add(new ie(n),!0).catch(s=>{throw this._abortController?.abort(),s})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(n=>{n instanceof DOMException&&n.name==="AbortError"||console.error("Pipe error:",n)})}async _flushAndClose(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flushAndClose()}},ba=(i,e)=>{let t=e.timestamp/1e6;m(i._connectedTrack);let r=i._connectedTrack.output._muxer;r.firstMediaStreamTimestamp===null&&(r.firstMediaStreamTimestamp=t),i._timestampOffset=-Math.min(r.firstMediaStreamTimestamp,t)},bt=class extends pt{constructor(t){super();this._connectedTrack=null;if(!ae.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${ae.join(", ")}.`);this._codec=t}},qi=class extends bt{constructor(e){super(e),this._parser=new kr({codec:e,output:(t,r)=>this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,t,r)})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._ensureValidAdd(),this._parser.parse(e),this._connectedTrack.output._muxer.mutex.currentPromise}};var ka=["video","audio","subtitle"],Xi=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!Ye(i.languageCode))throw new TypeError("metadata.languageCode must be a three-letter, ISO 639-2/T language code.")},Kt=class{constructor(e){this.state="pending";this._tracks=[];this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new ne;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ge))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ze))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof Pe))throw new TypeError("source must be a VideoSource.");if(Xi(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof Ee))throw new TypeError("source must be an AudioSource.");Xi(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof bt))throw new TypeError("source must be a SubtitleSource.");Xi(t),this._addTrack("subtitle",e,t)}_addTrack(e,t,r){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");let a=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((u,d)=>u+(d.type===e?1:0),0),s=a[e].max;if(n===s)throw new Error(s===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track${s===1?"":"s"}.`);let o=a.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if(c.type==="video"){let u=this.format.getSupportedVideoCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let u=this.format.getSupportedAudioCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let u=this.format.getSupportedSubtitleCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),t._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let r of ka){let a=this._tracks.reduce((s,o)=>s+(o.type===r?1:0),0),n=e[r].min;if(a<n)throw new Error(n===e[r].max?`${this.format._name} requires exactly ${n} ${r} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${r} track${n===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let r=await this._mutex.acquire();await this._muxer.start();for(let a of this._tracks)a.source._start();r()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire(),t=this._tracks.map(r=>r.source._flushOrWaitForClose());await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire(),t=this._tracks.map(r=>r.source._flushOrWaitForClose());await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};var Ie=class{constructor(){this._sizePromise=null;this.onread=null}getSize(){return this._sizePromise??=this._retrieveSize()}},Yi=class extends Ie{constructor(e){if(!(e instanceof ArrayBuffer)&&!(e instanceof Uint8Array))throw new TypeError("buffer must be an ArrayBuffer or Uint8Array.");super(),this._bytes=e instanceof Uint8Array?e:new Uint8Array(e)}async _read(e,t){return this._bytes.subarray(e,t)}async _retrieveSize(){return this._bytes.byteLength}},Zi=class extends Ie{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");super(),this._options=e}async _read(e,t){return this._options.read(e,t)}async _retrieveSize(){return this._options.getSize()}},Ji=class extends Ie{constructor(e){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");super(),this._blob=e}async _read(e,t){let a=await this._blob.slice(e,t).arrayBuffer();return new Uint8Array(a)}async _retrieveSize(){return this._blob.size}},en=class extends Ie{constructor(t,r={}){if(typeof t!="string"&&!(t instanceof URL))throw new TypeError("url must be a string or URL.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");super();this._fullData=null;this._url=t,this._options=r}async _makeRequest(t){let r={};t&&(r.Range=`bytes=${t.start}-${t.end-1}`);let a=await er(this._url,yt(this._options.requestInit??{},{method:"GET",headers:r}),this._options.getRetryDelay??(()=>null));if(!a.ok)throw new Error(`Error fetching ${this._url}: ${a.status} ${a.statusText}`);let n=await a.arrayBuffer();return a.status===200&&(this._fullData=n),{response:n,statusCode:a.status}}async _read(t,r){if(this._fullData)return new Uint8Array(this._fullData,t,r-t);let{response:a,statusCode:n}=await this._makeRequest({start:t,end:r});return n===200?new Uint8Array(a).subarray(t,r):new Uint8Array(a)}async _retrieveSize(){if(this._fullData)return this._fullData.byteLength;try{let a=await er(this._url,yt(this._options.requestInit??{},{method:"HEAD"}),this._options.getRetryDelay??(()=>null));if(a.ok){let n=a.headers.get("Content-Length");if(n)return parseInt(n)}}catch{}let t=await er(this._url,yt(this._options.requestInit??{},{method:"GET",headers:{Range:"bytes=0-0"}}),this._options.getRetryDelay??(()=>null));if(t.status===206){let a=t.headers.get("Content-Range");if(a){let n=a.match(/bytes \d+-\d+\/(\d+)/);if(n&&n[1])return parseInt(n[1])}}else if(t.status===200)return this._fullData=await t.arrayBuffer(),this._fullData.byteLength;let{response:r}=await this._makeRequest();return r.byteLength}};var wa=8,Qt=16,qe=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos++,e.getUint8(t)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readI16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getInt16(t,!1)}readU24(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+3);this.pos+=3;let r=e.getUint16(t,!1),a=e.getUint8(t+2);return r*256+a}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!1)}readU64(){let e=this.readU32(),t=this.readU32();return e*4294967296+t}readI64(){let e=this.readI32(),t=this.readU32();return e*4294967296+t}readF64(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+8);return this.pos+=8,e.getFloat64(t,!1)}readFixed_16_16(){return this.readI32()/65536}readFixed_2_30(){return this.readI32()/1073741824}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readIsomVariableInteger(){let e=0;for(let t=0;t<4;t++){e<<=7;let r=this.readU8();if(e|=r&127,(r&128)===0)break}return e}readBoxHeader(){let e=this.readU32(),t=this.readAscii(4),r=8;return e===1&&(e=this.readU64(),r=16),{name:t,totalSize:e,headerSize:r,contentSize:e-r}}};var Zr=class extends oe{constructor(t){super(t);this.currentTrack=null;this.tracks=[];this.metadataPromise=null;this.movieTimescale=-1;this.movieDurationInTimescale=-1;this.isQuickTime=!1;this.isFragmented=!1;this.fragmentTrackDefaults=[];this.fragments=[];this.currentFragment=null;this.fragmentLookupMutex=new ne;this.metadataReader=new qe(t._mainReader),this.chunkReader=new qe(new de(t.source,64*2**20))}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.tracks.map(t=>t.inputTrack)}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.inputTrack.getCodecParameterString()));return Rr({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:t.filter(Boolean)})}readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.metadataReader.reader.source.getSize();for(;this.metadataReader.pos<t;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Qt);let r=this.metadataReader.pos,a=this.metadataReader.readBoxHeader();if(a.name==="ftyp"){let n=this.metadataReader.readAscii(4);this.isQuickTime=n==="qt "}else if(a.name==="moov"){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+a.contentSize),this.readContiguousBoxes(a.contentSize);for(let n of this.tracks){let s=n.editListPreviousSegmentDurations/this.movieTimescale;n.editListOffset-=Math.round(s*n.timescale)}break}this.metadataReader.pos=r+a.totalSize}if(this.isFragmented){await this.metadataReader.reader.loadRange(t-4,t),this.metadataReader.pos=t-4;let r=this.metadataReader.readU32(),a=t-r;if(a>=0&&a<t){await this.metadataReader.reader.loadRange(a,t),this.metadataReader.pos=a;let n=this.metadataReader.readBoxHeader();n.name==="mfra"&&this.readContiguousBoxes(n.contentSize)}}})()}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(t.sampleTable=r,this.metadataReader.pos=t.sampleTableByteOffset,this.currentTrack=t,this.traverseBox(),this.currentTrack=null,t.info?.type==="audio"&&t.info.codec&&U.includes(t.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(t.info?.type==="audio");let n=G(t.info.codec),s=[],o=[];for(let c=0;c<r.sampleToChunk.length;c++){let u=r.sampleToChunk[c],d=r.sampleToChunk[c+1],l=(d?d.startChunkIndex:r.chunkOffsets.length)-u.startChunkIndex;for(let p=0;p<l;p++){let h=u.startSampleIndex+p*u.samplesPerChunk,f=h+u.samplesPerChunk,b=F(r.sampleTimingEntries,h,E=>E.startIndex),g=r.sampleTimingEntries[b],k=F(r.sampleTimingEntries,f,E=>E.startIndex),y=r.sampleTimingEntries[k],C=g.startDecodeTimestamp+(h-g.startIndex)*g.delta,w=y.startDecodeTimestamp+(f-y.startIndex)*y.delta-C,T=V(s);T&&T.delta===w?T.count++:s.push({startIndex:u.startChunkIndex+p,startDecodeTimestamp:C,count:1,delta:w});let x=u.samplesPerChunk*n.sampleSize*t.info.numberOfChannels;o.push(x)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=s,r.sampleSizes=o}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let n of r.sampleTimingEntries)for(let s=0;s<n.count;s++)r.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+s*n.delta,sampleIndex:n.startIndex+s});for(let n of r.sampleCompositionTimeOffsets)for(let s=0;s<n.count;s++){let o=n.startIndex+s,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}r.presentationTimestamps.sort((n,s)=>n.presentationTimestamp-s.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let n=0;n<r.presentationTimestamps.length;n++)r.presentationTimestampIndexMap[r.presentationTimestamps[n].sampleIndex]=n}return r}async readFragment(){let t=this.metadataReader.pos;await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Qt);let r=this.metadataReader.readBoxHeader();m(r.name==="moof");let a=this.metadataReader.pos;await this.metadataReader.reader.loadRange(a,a+r.contentSize),this.metadataReader.pos=t,this.traverseBox();let n=W(this.fragments,t,o=>o.moofOffset);m(n!==-1);let s=this.fragments[n];m(s.moofOffset===t),this.metadataReader.reader.forgetRange(a,a+r.contentSize);for(let[o,c]of s.trackData){if(c.startTimestampIsFinal)continue;let u=this.tracks.find(f=>f.id===o);this.metadataReader.pos=0;let d=null,l=null,p=F(u.fragments,t-1,f=>f.moofOffset);p!==-1&&(d=u.fragments[p],l=d,this.metadataReader.pos=d.moofOffset+d.moofSize);let h=this.metadataReader.pos===0;for(;this.metadataReader.pos<t;){if(d?.nextFragment)d=d.nextFragment,this.metadataReader.pos=d.moofOffset+d.moofSize;else{await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Qt);let f=this.metadataReader.pos,b=this.metadataReader.readBoxHeader();if(b.name==="moof"){let g=W(this.fragments,f,y=>y.moofOffset),k;g===-1?(this.metadataReader.pos=f,k=await this.readFragment()):k=this.fragments[g],d&&(d.nextFragment=k),d=k,h&&(k.isKnownToBeFirstFragment=!0,h=!1)}this.metadataReader.pos=f+b.totalSize}d&&d.trackData.has(o)&&(l=d)}if(l){let f=l.trackData.get(o);m(f.startTimestampIsFinal),ya(c,f.endTimestamp)}c.startTimestampIsFinal=!0}return s}readContiguousBoxes(t){let r=this.metadataReader.pos;for(;this.metadataReader.pos-r<=t-wa;)this.traverseBox()}traverseBox(){let t=this.metadataReader.pos,r=this.metadataReader.readBoxHeader(),a=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(r.contentSize);break;case"mvhd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3,n===1?(this.metadataReader.pos+=16,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU64()):(this.metadataReader.pos+=8,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU32())}break;case"trak":{let n={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=n,this.readContiguousBoxes(r.contentSize),n.id!==-1&&n.timescale!==-1&&n.info!==null){if(n.info.type==="video"&&n.info.width!==-1){let s=n;n.inputTrack=new le(new tn(s)),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){let s=n;n.inputTrack=new X(new rn(s)),this.tracks.push(n)}}this.currentTrack=null}break;case"tkhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();if(!((this.metadataReader.readU24()&1)!==0))break;if(s===0)this.metadataReader.pos+=8,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU32();else if(s===1)this.metadataReader.pos+=16,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU64();else throw new Error(`Incorrect track header version ${s}.`);this.metadataReader.pos+=2*4+2+2+2+2;let u=[this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30()],d=Ae(Tt(yo(u),90));m(d===0||d===90||d===180||d===270),n.rotation=d}break;case"elst":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=!1,c=0,u=this.metadataReader.readU32();for(let d=0;d<u;d++){let l=s===1?this.metadataReader.readU64():this.metadataReader.readU32(),p=s===1?this.metadataReader.readI64():this.metadataReader.readI32(),h=this.metadataReader.readFixed_16_16();if(l!==0){if(o){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){c+=l;continue}if(h!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}n.editListPreviousSegmentDurations=c,n.editListOffset=p,o=!0}}}break;case"mdhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3,s===0?(this.metadataReader.pos+=8,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU32()):s===1&&(this.metadataReader.pos+=16,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU64());let o=this.metadataReader.readU16();if(o>0){n.languageCode="";for(let c=0;c<3;c++)n.languageCode=String.fromCharCode(96+(o&31))+n.languageCode,o>>=5;Ye(n.languageCode)||(n.languageCode=Z)}}break;case"hdlr":{let n=this.currentTrack;m(n),this.metadataReader.pos+=8;let s=this.metadataReader.readAscii(4);s==="vide"?n.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:s==="soun"&&(n.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let n=this.currentTrack;m(n),n.sampleTableByteOffset=t,this.readContiguousBoxes(r.contentSize)}break;case"stsd":{let n=this.currentTrack;if(m(n),n.info===null||n.sampleTable)break;let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=this.metadataReader.readU32();for(let c=0;c<o;c++){let u=this.metadataReader.pos,d=this.metadataReader.readBoxHeader(),l=d.name.toLowerCase();if(n.info.type==="video")l==="avc1"?n.info.codec="avc":l==="hvc1"||l==="hev1"?n.info.codec="hevc":l==="vp08"?n.info.codec="vp8":l==="vp09"?n.info.codec="vp9":l==="av01"?n.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),this.metadataReader.pos+=6*1+2+2+2+3*4,n.info.width=this.metadataReader.readU16(),n.info.height=this.metadataReader.readU16(),this.metadataReader.pos+=50,this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos);else{l==="mp4a"||(l==="opus"?n.info.codec="opus":l==="flac"?n.info.codec="flac":l==="twos"||l==="sowt"||l==="raw "||l==="in24"||l==="in32"||l==="fl32"||l==="fl64"||l==="lpcm"||l==="ipcm"||l==="fpcm"||(l==="ulaw"?n.info.codec="ulaw":l==="alaw"?n.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),this.metadataReader.pos+=6*1+2;let p=this.metadataReader.readU16();this.metadataReader.pos+=3*2;let h=this.metadataReader.readU16(),f=this.metadataReader.readU16();this.metadataReader.pos+=2*2;let b=this.metadataReader.readU32()/65536;if(s===0&&p>0){if(p===1)this.metadataReader.pos+=4,f=8*this.metadataReader.readU32(),this.metadataReader.pos+=2*4;else if(p===2){this.metadataReader.pos+=4,b=this.metadataReader.readF64(),h=this.metadataReader.readU32(),this.metadataReader.pos+=4,f=this.metadataReader.readU32();let g=this.metadataReader.readU32();if(this.metadataReader.pos+=2*4,l==="lpcm"){let k=f+7>>3,y=!!(g&1),C=!!(g&2),S=g&4?-1:0;f>0&&f<=64&&(y?f===32&&(n.info.codec=C?"pcm-f32be":"pcm-f32"):S&1<<k-1?k===1?n.info.codec="pcm-s8":k===2?n.info.codec=C?"pcm-s16be":"pcm-s16":k===3?n.info.codec=C?"pcm-s24be":"pcm-s24":k===4&&(n.info.codec=C?"pcm-s32be":"pcm-s32"):k===1&&(n.info.codec="pcm-u8")),n.info.codec===null&&console.warn("Unsupported PCM format.")}}}n.info.numberOfChannels=h,n.info.sampleRate=b,l==="twos"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${f} for codec 'twos'.`),n.info.codec=null):l==="sowt"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${f} for codec 'sowt'.`),n.info.codec=null):l==="raw "?n.info.codec="pcm-u8":l==="in24"?n.info.codec="pcm-s24be":l==="in32"?n.info.codec="pcm-s32be":l==="fl32"?n.info.codec="pcm-f32be":l==="fl64"?n.info.codec="pcm-f64be":l==="ipcm"?n.info.codec="pcm-s16be":l==="fpcm"&&(n.info.codec="pcm-f32be"),this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos)}}}break;case"avcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"hvcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"vpcC":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8(),o=this.metadataReader.readU8(),c=this.metadataReader.readU8(),u=c>>4,d=c>>1&7,l=c&1,p=this.metadataReader.readU8(),h=this.metadataReader.readU8(),f=this.metadataReader.readU8();n.info.vp9CodecInfo={profile:s,level:o,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:l,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:f}}break;case"av1C":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=s>>5,c=s&31,u=this.metadataReader.readU8(),d=u>>7,l=u>>6&1,p=u>>5&1,h=u>>4&1,f=u>>3&1,b=u>>2&1,g=u&3,k=o==2&&l?p?12:10:l?10:8;n.info.av1CodecInfo={profile:o,level:c,tier:d,bitDepth:k,monochrome:h,chromaSubsamplingX:f,chromaSubsamplingY:b,chromaSamplePosition:g}}break;case"colr":{let n=this.currentTrack;if(m(n&&n.info?.type==="video"),this.metadataReader.readAscii(4)!=="nclx")break;let o=this.metadataReader.readU16(),c=this.metadataReader.readU16(),u=this.metadataReader.readU16(),d=!!(this.metadataReader.readU8()&128);n.info.colorSpace={primaries:Gt[o],transfer:Xt[c],matrix:Yt[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(r.contentSize);break;case"esds":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8();m(s===3),this.metadataReader.readIsomVariableInteger(),this.metadataReader.pos+=2;let o=this.metadataReader.readU8(),c=(o&128)!==0,u=(o&64)!==0,d=(o&32)!==0;if(c&&(this.metadataReader.pos+=2),u){let b=this.metadataReader.readU8();this.metadataReader.pos+=b}d&&(this.metadataReader.pos+=2);let l=this.metadataReader.readU8();m(l===4);let p=this.metadataReader.readIsomVariableInteger(),h=this.metadataReader.pos,f=this.metadataReader.readU8();if(f===64||f===103?(n.info.codec="aac",n.info.aacCodecInfo={isMpeg2:f===103}):f===105||f===107?n.info.codec="mp3":f===221?n.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${f}) - discarding track.`),this.metadataReader.pos+=12,p>this.metadataReader.pos-h){let b=this.metadataReader.readU8();m(b===5);let g=this.metadataReader.readIsomVariableInteger();if(n.info.codecDescription=this.metadataReader.readBytes(g),n.info.codec==="aac"){let k=bi(n.info.codecDescription);k.numberOfChannels!==null&&(n.info.numberOfChannels=k.numberOfChannels),k.sampleRate!==null&&(n.info.sampleRate=k.sampleRate)}}}break;case"enda":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.readU16()&255&&(n.info.codec==="pcm-s16be"?n.info.codec="pcm-s16":n.info.codec==="pcm-s24be"?n.info.codec="pcm-s24":n.info.codec==="pcm-s32be"?n.info.codec="pcm-s32":n.info.codec==="pcm-f32be"?n.info.codec="pcm-f32":n.info.codec==="pcm-f64be"&&(n.info.codec="pcm-f64"))}break;case"pcmC":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let o=!!(this.metadataReader.readU8()&1),c=this.metadataReader.readU8();n.info.codec==="pcm-s16be"?o?c===16?n.info.codec="pcm-s16":c===24?n.info.codec="pcm-s24":c===32?n.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):c===16?n.info.codec="pcm-s16be":c===24?n.info.codec="pcm-s24be":c===32?n.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):n.info.codec==="pcm-f32be"&&(o?c===32?n.info.codec="pcm-f32":c===64?n.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null):c===32?n.info.codec="pcm-f32be":c===64?n.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null));break}case"dOps":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=this.metadataReader.readU16(),c=this.metadataReader.readU32(),u=this.metadataReader.readI16(),d=this.metadataReader.readU8(),l;d!==0?l=this.metadataReader.readBytes(2+s):l=new Uint8Array(0);let p=new Uint8Array(19+l.byteLength),h=new DataView(p.buffer);h.setUint32(0,1332770163,!1),h.setUint32(4,1214603620,!1),h.setUint8(8,1),h.setUint8(9,s),h.setUint16(10,o,!0),h.setUint32(12,c,!0),h.setInt16(16,u,!0),h.setUint8(18,d),p.set(l,19),n.info.codecDescription=p,n.info.numberOfChannels=s,n.info.sampleRate=c}break;case"dfLa":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=127,o=128,c=this.metadataReader.pos;for(;this.metadataReader.pos<a;){let h=this.metadataReader.readU8(),f=this.metadataReader.readU24();if((h&s)===0){this.metadataReader.pos+=10;let g=this.metadataReader.readU32(),k=g>>>12,y=(g>>9&7)+1;n.info.sampleRate=k,n.info.numberOfChannels=y,this.metadataReader.pos+=20}else this.metadataReader.pos+=f;if(h&o)break}let u=this.metadataReader.pos;this.metadataReader.pos=c;let d=this.metadataReader.readBytes(u-c),l=new Uint8Array(4+d.byteLength);new DataView(l.buffer).setUint32(0,1716281667,!1),l.set(d,4),n.info.codecDescription=l}break;case"stts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0,c=0;for(let u=0;u<s;u++){let d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleTimingEntries.push({startIndex:o,startDecodeTimestamp:c,count:d,delta:l}),o+=d,c+=d*l}}break;case"ctts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0;for(let c=0;c<s;c++){let u=this.metadataReader.readU32(),d=this.metadataReader.readI32();n.sampleTable.sampleCompositionTimeOffsets.push({startIndex:o,count:u,offset:d}),o+=u}}break;case"stsz":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=this.metadataReader.readU32();if(s===0)for(let c=0;c<o;c++){let u=this.metadataReader.readU32();n.sampleTable.sampleSizes.push(u)}else n.sampleTable.sampleSizes.push(s)}break;case"stz2":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,this.metadataReader.pos+=3;let s=this.metadataReader.readU8(),o=this.metadataReader.readU32(),c=this.metadataReader.readBytes(Math.ceil(o*s/8)),u=new K(c);for(let d=0;d<o;d++){let l=u.readBits(s);n.sampleTable.sampleSizes.push(l)}}break;case"stss":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,n.sampleTable.keySampleIndices=[];let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32()-1;n.sampleTable.keySampleIndices.push(c)}}break;case"stsc":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let c=0;c<s;c++){let u=this.metadataReader.readU32()-1,d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:l})}let o=0;for(let c=0;c<n.sampleTable.sampleToChunk.length;c++)if(n.sampleTable.sampleToChunk[c].startSampleIndex=o,c<n.sampleTable.sampleToChunk.length-1){let d=n.sampleTable.sampleToChunk[c+1].startChunkIndex-n.sampleTable.sampleToChunk[c].startChunkIndex;o+=d*n.sampleTable.sampleToChunk[c].samplesPerChunk}}break;case"stco":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32();n.sampleTable.chunkOffsets.push(c)}}break;case"co64":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU64();n.sampleTable.chunkOffsets.push(c)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(r.contentSize);break;case"mehd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=n===1?this.metadataReader.readU64():this.metadataReader.readU32();this.movieDurationInTimescale=s}break;case"trex":{this.metadataReader.pos+=4;let n=this.metadataReader.readU32(),s=this.metadataReader.readU32(),o=this.metadataReader.readU32(),c=this.metadataReader.readU32(),u=this.metadataReader.readU32();this.fragmentTrackDefaults.push({trackId:n,defaultSampleDescriptionIndex:s,defaultSampleDuration:o,defaultSampleSize:c,defaultSampleFlags:u})}break;case"tfra":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=this.metadataReader.readU32(),o=this.tracks.find(y=>y.id===s);if(!o)break;o.fragmentLookupTable=[];let c=this.metadataReader.readU32(),u=(c&48)>>4,d=(c&12)>>2,l=c&3,p=this.metadataReader,h=[p.readU8.bind(p),p.readU16.bind(p),p.readU24.bind(p),p.readU32.bind(p)],f=h[u],b=h[d],g=h[l],k=this.metadataReader.readU32();for(let y=0;y<k;y++){let C=n===1?this.metadataReader.readU64():this.metadataReader.readU32(),S=n===1?this.metadataReader.readU64():this.metadataReader.readU32(),w=f(),T=b(),x=g();o.fragmentLookupTable.push({timestamp:C,moofOffset:S})}}break;case"moof":{this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,dataStart:1/0,dataEnd:0,nextFragment:null,isKnownToBeFirstFragment:!1},this.readContiguousBoxes(r.contentSize);let n=F(this.fragments,this.currentFragment.moofOffset,s=>s.moofOffset);this.fragments.splice(n+1,0,this.currentFragment);for(let[,s]of this.currentFragment.trackData){let o=s.samples[0],c=V(s.samples);this.currentFragment.dataStart=Math.min(this.currentFragment.dataStart,o.byteOffset),this.currentFragment.dataEnd=Math.max(this.currentFragment.dataEnd,c.byteOffset+c.byteSize)}this.currentFragment=null}break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(r.contentSize),this.currentTrack){let n=this.currentFragment.trackData.get(this.currentTrack.id);if(n){let s=F(this.currentTrack.fragments,this.currentFragment.moofOffset,u=>u.moofOffset);if(this.currentTrack.fragments.splice(s+1,0,this.currentFragment),n.firstKeyFrameTimestamp!==null){let u=F(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment.moofOffset,d=>d.moofOffset);this.currentTrack.fragmentsWithKeyFrame.splice(u+1,0,this.currentFragment)}let{currentFragmentState:c}=this.currentTrack;m(c),c.startTimestamp!==null&&(ya(n,c.startTimestamp),n.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),this.metadataReader.pos+=1;let n=this.metadataReader.readU24(),s=!!(n&1),o=!!(n&2),c=!!(n&8),u=!!(n&16),d=!!(n&32),l=!!(n&65536),p=!!(n&131072),h=this.metadataReader.readU32(),f=this.tracks.find(g=>g.id===h);if(!f)break;let b=this.fragmentTrackDefaults.find(g=>g.trackId===h);this.currentTrack=f,f.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:b?.defaultSampleDescriptionIndex??null,defaultSampleDuration:b?.defaultSampleDuration??null,defaultSampleSize:b?.defaultSampleSize??null,defaultSampleFlags:b?.defaultSampleFlags??null,startTimestamp:null},s?f.currentFragmentState.baseDataOffset=this.metadataReader.readU64():p&&(f.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),o&&(f.currentFragmentState.sampleDescriptionIndex=this.metadataReader.readU32()),c&&(f.currentFragmentState.defaultSampleDuration=this.metadataReader.readU32()),u&&(f.currentFragmentState.defaultSampleSize=this.metadataReader.readU32()),d&&(f.currentFragmentState.defaultSampleFlags=this.metadataReader.readU32()),l&&(f.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let n=this.currentTrack;if(!n)break;m(n.currentFragmentState);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=s===0?this.metadataReader.readU32():this.metadataReader.readU64();n.currentFragmentState.startTimestamp=o}break;case"trun":{let n=this.currentTrack;if(!n)break;if(m(this.currentFragment),m(n.currentFragmentState),this.currentFragment.trackData.has(n.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let s=this.metadataReader.readU8(),o=this.metadataReader.readU24(),c=!!(o&1),u=!!(o&4),d=!!(o&256),l=!!(o&512),p=!!(o&1024),h=!!(o&2048),f=this.metadataReader.readU32(),b=n.currentFragmentState.baseDataOffset;c&&(b+=this.metadataReader.readI32());let g=null;u&&(g=this.metadataReader.readU32());let k=b;if(f===0){this.currentFragment.implicitBaseDataOffset=k;break}let y=0,C={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(n.id,C);for(let T=0;T<f;T++){let x;d?x=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleDuration!==null),x=n.currentFragmentState.defaultSampleDuration);let E;l?E=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleSize!==null),E=n.currentFragmentState.defaultSampleSize);let I;p?I=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleFlags!==null),I=n.currentFragmentState.defaultSampleFlags),T===0&&g!==null&&(I=g);let A=0;h&&(s===0?A=this.metadataReader.readU32():A=this.metadataReader.readI32());let _=!(I&65536);C.samples.push({presentationTimestamp:y+A,duration:x,byteOffset:k,byteSize:E,isKeyFrame:_}),k+=E,y+=x}C.presentationTimestamps=C.samples.map((T,x)=>({presentationTimestamp:T.presentationTimestamp,sampleIndex:x})).sort((T,x)=>T.presentationTimestamp-x.presentationTimestamp);for(let T=0;T<C.presentationTimestamps.length;T++){let x=C.presentationTimestamps[T],E=C.samples[x.sampleIndex];if(C.firstKeyFrameTimestamp===null&&E.isKeyFrame&&(C.firstKeyFrameTimestamp=E.presentationTimestamp),T<C.presentationTimestamps.length-1){let I=C.presentationTimestamps[T+1];E.duration=I.presentationTimestamp-x.presentationTimestamp}}let S=C.samples[C.presentationTimestamps[0].sampleIndex],w=C.samples[V(C.presentationTimestamps).sampleIndex];C.startTimestamp=S.presentationTimestamp,C.endTimestamp=w.presentationTimestamp+w.duration,this.currentFragment.implicitBaseDataOffset=k}break}this.metadataReader.pos=a}},Jr=class{constructor(e){this.internalTrack=e;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){return this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(()=>{let t=this.internalTrack.demuxer.fragments[0]??null;if(t?.isKnownToBeFirstFragment){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{fragmentIndex:W(this.internalTrack.fragments,r.moofOffset,n=>n.moofOffset),sampleIndex:0,correctSampleFound:!0};r=r.nextFragment}}return{fragmentIndex:-1,sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e):this.fetchPacketForSampleIndex(0,e)}mapTimestampIntoTimescale(e){return Xe(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e);if(this.internalTrack.demuxer.isFragmented)return this.performFragmentedLookup(()=>this.findSampleInFragmentsForTimestamp(r),r,r,t);{let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ta(a,r);return this.fetchPacketForSampleIndex(n,t)}}async getNextPacket(e,t){if(this.internalTrack.demuxer.isFragmented){let a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");let n=a.fragment.trackData.get(this.internalTrack.id),s=n.samples[a.sampleIndex],o=W(this.internalTrack.fragments,a.fragment.moofOffset,c=>c.moofOffset);return m(o!==-1),this.performFragmentedLookup(()=>{if(a.sampleIndex+1<n.samples.length)return{fragmentIndex:o,sampleIndex:a.sampleIndex+1,correctSampleFound:!0};{let c=a.fragment;for(;c.nextFragment;)if(c=c.nextFragment,c.trackData.get(this.internalTrack.id)){let d=W(this.internalTrack.fragments,c.moofOffset,l=>l.moofOffset);return m(d!==-1),{fragmentIndex:d,sampleIndex:0,correctSampleFound:!0}}return{fragmentIndex:o,sampleIndex:-1,correctSampleFound:!1}}},s.presentationTimestamp,1/0,t)}let r=this.packetToSampleIndex.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.fetchPacketForSampleIndex(r+1,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e);if(this.internalTrack.demuxer.isFragmented)return this.performFragmentedLookup(()=>this.findKeySampleInFragmentsForTimestamp(r),r,r,t);let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ta(a,r),s=n===-1?-1:wo(a,n);return this.fetchPacketForSampleIndex(s,t)}async getNextKeyPacket(e,t){if(this.internalTrack.demuxer.isFragmented){let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let o=s.fragment.trackData.get(this.internalTrack.id),c=o.samples[s.sampleIndex],u=W(this.internalTrack.fragments,s.fragment.moofOffset,d=>d.moofOffset);return m(u!==-1),this.performFragmentedLookup(()=>{let d=o.samples.findIndex((l,p)=>l.isKeyFrame&&p>s.sampleIndex);if(d!==-1)return{fragmentIndex:u,sampleIndex:d,correctSampleFound:!0};{let l=s.fragment;for(;l.nextFragment;){l=l.nextFragment;let p=l.trackData.get(this.internalTrack.id);if(p&&p.firstKeyFrameTimestamp!==null){let h=W(this.internalTrack.fragments,l.moofOffset,b=>b.moofOffset);m(h!==-1);let f=p.samples.findIndex(b=>b.isKeyFrame);return m(f!==-1),{fragmentIndex:h,sampleIndex:f,correctSampleFound:!0}}}return{fragmentIndex:u,sampleIndex:-1,correctSampleFound:!1}}},c.presentationTimestamp,1/0,t)}let r=this.packetToSampleIndex.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=To(a,r);return this.fetchPacketForSampleIndex(n,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ko(r,e);if(!a)return null;let n;t.metadataOnly?n=ee:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(a.chunkOffset,a.chunkOffset+a.chunkSize),this.internalTrack.demuxer.chunkReader.pos=a.sampleOffset,n=this.internalTrack.demuxer.chunkReader.readBytes(a.sampleSize));let s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new D(n,a.isKeyFrame?"key":"delta",s,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];m(n);let s;r.metadataOnly?s=ee:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(e.dataStart,e.dataEnd),this.internalTrack.demuxer.chunkReader.pos=n.byteOffset,s=this.internalTrack.demuxer.chunkReader.readBytes(n.byteSize));let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,u=new D(s,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}findSampleInFragmentsForTimestamp(e){let t=F(this.internalTrack.fragments,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.fragments[t].trackData.get(this.internalTrack.id),o=F(s.presentationTimestamps,e,c=>c.presentationTimestamp);m(o!==-1),r=s.presentationTimestamps[o].sampleIndex,a=e<s.endTimestamp}return{fragmentIndex:t,sampleIndex:r,correctSampleFound:a}}findKeySampleInFragmentsForTimestamp(e){let t=F(this.internalTrack.fragmentsWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=-1,n=!1;if(t!==-1){let s=this.internalTrack.fragmentsWithKeyFrame[t];r=W(this.internalTrack.fragments,s.moofOffset,d=>d.moofOffset),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=Jt(o.presentationTimestamps,d=>o.samples[d.sampleIndex].isKeyFrame&&d.presentationTimestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].sampleIndex,n=e<o.endTimestamp}return{fragmentIndex:r,sampleIndex:a,correctSampleFound:n}}async performFragmentedLookup(e,t,r,a){let n=this.internalTrack.demuxer,s=await n.fragmentLookupMutex.acquire();try{let{fragmentIndex:o,sampleIndex:c,correctSampleFound:u}=e();if(u){let S=this.internalTrack.fragments[o];return this.fetchPacketInFragment(S,c,a)}let d=n.metadataReader,l=await d.reader.source.getSize(),p=null,h=o,f=c,b=this.internalTrack.fragmentLookupTable?F(this.internalTrack.fragmentLookupTable,t,S=>S.timestamp):-1,g=b!==-1?this.internalTrack.fragmentLookupTable[b]:null,k=!1;if(o===-1)d.pos=g?.moofOffset??0,k=d.pos===0;else{let S=this.internalTrack.fragments[o];!g||S.moofOffset>=g.moofOffset?(d.pos=S.moofOffset+S.moofSize,p=S):d.pos=g.moofOffset}for(;d.pos<l;){if(p){let T=p.trackData.get(this.internalTrack.id);if(T&&T.startTimestamp>r)break;if(p.nextFragment){d.pos=p.nextFragment.moofOffset+p.nextFragment.moofSize,p=p.nextFragment;continue}}await d.reader.loadRange(d.pos,d.pos+Qt);let S=d.pos,w=d.readBoxHeader();if(w.name==="moof"){let T=W(n.fragments,S,_=>_.moofOffset),x;T===-1?(d.pos=S,x=await n.readFragment()):x=n.fragments[T],p&&(p.nextFragment=x),p=x,k&&(x.isKnownToBeFirstFragment=!0,k=!1);let{fragmentIndex:E,sampleIndex:I,correctSampleFound:A}=e();if(A){let _=this.internalTrack.fragments[E];return this.fetchPacketInFragment(_,I,a)}E!==-1&&(h=E,f=I)}d.pos=S+w.totalSize}let y=null,C=h!==-1?this.internalTrack.fragments[h]:null;if(C&&(y=await this.fetchPacketInFragment(C,f,a)),!y&&g&&(!C||C.moofOffset<g.moofOffset)){let w=this.internalTrack.fragmentLookupTable[b-1]?.timestamp??-1/0;return this.performFragmentedLookup(e,w,r,a)}return y}finally{s()}}},tn=class extends Jr{constructor(t){super(t);this.decoderConfigPromise=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&xr(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&vr(t.data)}return{codec:ur(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},rn=class extends Jr{constructor(t){super(t);this.decoderConfig=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:lr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Ta=(i,e)=>{if(i.presentationTimestamps){let t=F(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{let t=F(i.sampleTimingEntries,e,a=>a.startDecodeTimestamp);if(t===-1)return-1;let r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},ko=(i,e)=>{let t=F(i.sampleTimingEntries,e,k=>k.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=F(i.sampleCompositionTimeOffsets,e,k=>k.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&e-o.startIndex<o.count&&(n+=o.offset);let c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],u=F(i.sampleToChunk,e,k=>k.startSampleIndex),d=i.sampleToChunk[u];m(d);let l=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),p=i.chunkOffsets[l],h=d.startSampleIndex+(l-d.startChunkIndex)*d.samplesPerChunk,f=0,b=p;if(i.sampleSizes.length===1)b+=c*(e-h),f+=c*d.samplesPerChunk;else for(let k=h;k<h+d.samplesPerChunk;k++){let y=i.sampleSizes[k];k<e&&(b+=y),f+=y}let g=r.delta;if(i.presentationTimestamps){let k=i.presentationTimestampIndexMap[e];m(k!==void 0),k<i.presentationTimestamps.length-1&&(g=i.presentationTimestamps[k+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:g,sampleOffset:b,sampleSize:c,chunkOffset:p,chunkSize:f,isKeyFrame:i.keySampleIndices?W(i.keySampleIndices,e,k=>k)!==-1:!0}},wo=(i,e)=>{if(!i.keySampleIndices)return e;let t=F(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t]??-1},To=(i,e)=>{if(!i.keySampleIndices)return e+1;let t=F(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},ya=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(let t of i.samples)t.presentationTimestamp+=e;for(let t of i.presentationTimestamps)t.presentationTimestamp+=e},yo=i=>{let[e,,,t]=i,r=Math.hypot(e,t),a=e/r,n=t/r;return-Math.atan2(n,a)*(180/Math.PI)};var nn=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],ei=class extends oe{constructor(t){super(t);this.readMetadataPromise=null;this.segments=[];this.currentSegment=null;this.currentTrack=null;this.currentCluster=null;this.currentBlock=null;this.currentCueTime=null;this.isWebM=!1;this.metadataReader=new We(t._mainReader),this.clusterReader=new We(new de(t.source,64*2**20))}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(t=>t.tracks.map(r=>r.inputTrack))}async getMimeType(){await this.readMetadata();let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.getCodecParameterString()));return Br({isWebM:this.isWebM,hasVideo:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="audio")),codecStrings:r.filter(Boolean)})}readMetadata(){return this.readMetadataPromise??=(async()=>{this.metadataReader.pos=0;let t=await this.input.source.getSize();for(;this.metadataReader.pos<=t-Mr;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let{id:r,size:a}=this.metadataReader.readElementHeader(),n=this.metadataReader.pos;if(r===440786851)Le(a),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+a),this.readContiguousElements(this.metadataReader,a);else if(r===408125543&&(await this.readSegment(a),a===null))break;Le(a),this.metadataReader.pos=n+a}})()}async readSegment(t){let r=this.metadataReader.pos;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:r,elementEndPos:t===null?await this.input.source.getSize():r+t,clusterSeekStartPos:r,clusters:[],clusterLookupMutex:new ne},this.segments.push(this.currentSegment),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+2**14);let a=!1;for(;this.metadataReader.pos<this.currentSegment.elementEndPos;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let u=this.metadataReader.pos,{id:d,size:l}=this.metadataReader.readElementHeader(),p=this.metadataReader.pos,h=nn.findIndex(f=>f.id===d);if(h!==-1){let f=nn[h].flag;this.currentSegment[f]=!0,Le(l),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+l),this.readContiguousElements(this.metadataReader,l)}else d===524531317&&(a||(a=!0,this.currentSegment.clusterSeekStartPos=u));if(this.currentSegment.infoSeen&&this.currentSegment.tracksSeen&&this.currentSegment.cuesSeen)break;if(this.currentSegment.seekHeadSeen){let f=this.currentSegment.infoSeen,b=this.currentSegment.tracksSeen,g=this.currentSegment.cuesSeen;for(let k of this.currentSegment.seekEntries)k.id===357149030?f=!0:k.id===374648427?b=!0:k.id===475249515&&(g=!0);if(f&&b&&g)break}if(l===null)break;this.metadataReader.pos=p+l,a||(this.currentSegment.clusterSeekStartPos=this.metadataReader.pos)}for(let u of nn){if(this.currentSegment[u.flag])continue;let d=this.currentSegment.seekEntries.find(h=>h.id===u.id);if(!d)continue;this.metadataReader.pos=r+d.segmentPosition,await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+2**12);let{id:l,size:p}=this.metadataReader.readElementHeader();l===u.id&&(Le(p),this.currentSegment[u.flag]=!0,await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+p),this.readContiguousElements(this.metadataReader,p))}this.currentSegment.tracks.sort((u,d)=>Number(d.isDefault)-Number(u.isDefault)),this.currentSegment.cuePoints.sort((u,d)=>u.clusterPosition-d.clusterPosition);let n=this.currentSegment.tracks.map(u=>u.id),s=new Set,o=null,c=null;for(let u of this.currentSegment.cuePoints){if(u.clusterPosition!==o){for(let l of s)m(c),this.currentSegment.tracks.find(h=>h.id===l).cuePoints.push(c);for(let l of n)s.add(l)}if(c=u,!s.has(u.trackId))continue;this.currentSegment.tracks.find(l=>l.id===u.trackId).cuePoints.push(u),s.delete(u.trackId),o=u.clusterPosition}for(let u of s)m(c),this.currentSegment.tracks.find(l=>l.id===u).cuePoints.push(c);for(let u of this.currentSegment.tracks)u.cuePoints.sort((d,l)=>d.time-l.time);this.currentSegment=null}async readCluster(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);let r=this.metadataReader.pos,a=this.metadataReader.readElementHeader(),n=a.id,s=a.size,o=this.metadataReader.pos;s===null&&(this.clusterReader.pos=o,s=(await this.clusterReader.searchForNextElementId(_i,t.elementEndPos)??t.elementEndPos)-o),m(n===524531317),this.clusterReader.pos=o,await this.clusterReader.reader.loadRange(this.clusterReader.pos,this.clusterReader.pos+s);let c={elementStartPos:r,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map,nextCluster:null,isKnownToBeFirstCluster:!1};this.currentCluster=c,this.readContiguousElements(this.clusterReader,s);for(let[d,l]of c.trackData){let p=!1;m(l.blocks.length>0);for(let g=0;g<l.blocks.length;g++){let k=l.blocks[g];k.timestamp+=c.timestamp,p||=k.referencedTimestamps.length>0}p&&(l.blocks=So(l.blocks)),l.presentationTimestamps=l.blocks.map((g,k)=>({timestamp:g.timestamp,blockIndex:k})).sort((g,k)=>g.timestamp-k.timestamp);for(let g=0;g<l.presentationTimestamps.length;g++){let k=l.presentationTimestamps[g],y=l.blocks[k.blockIndex];if(l.firstKeyFrameTimestamp===null&&y.isKeyFrame&&(l.firstKeyFrameTimestamp=y.timestamp),g<l.presentationTimestamps.length-1){let C=l.presentationTimestamps[g+1];y.duration=C.timestamp-y.timestamp}}let h=l.blocks[l.presentationTimestamps[0].blockIndex],f=l.blocks[V(l.presentationTimestamps).blockIndex];l.startTimestamp=h.timestamp,l.endTimestamp=f.timestamp+f.duration;let b=t.tracks.find(g=>g.id===d);if(b){let g=F(b.clusters,c.elementStartPos,y=>y.elementStartPos);if(b.clusters.splice(g+1,0,c),l.firstKeyFrameTimestamp!==null){let y=F(b.clustersWithKeyFrame,c.elementStartPos,C=>C.elementStartPos);b.clustersWithKeyFrame.splice(y+1,0,c)}}}let u=F(t.clusters,r,d=>d.elementStartPos);return t.clusters.splice(u+1,0,c),this.currentCluster=null,c}getTrackDataInCluster(t,r){let a=t.trackData.get(r);return a||(a={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},t.trackData.set(r,a)),a}readContiguousElements(t,r){let a=t.pos;for(;t.pos-a<=r-Mr;)this.traverseElement(t)}traverseElement(t){let{id:r,size:a}=t.readElementHeader(),n=t.pos;switch(Le(a),r){case 17026:this.isWebM=t.readString(a)==="webm";break;case 19899:{if(!this.currentSegment)break;let s={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(s),this.readContiguousElements(t,a),(s.id===-1||s.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let s=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!s)break;s.id=t.readUnsignedInt(a)}break;case 21420:{let s=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!s)break;s.segmentPosition=t.readUnsignedInt(a)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=t.readUnsignedInt(a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=t.readFloat(a)}break;case 174:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusters:[],clustersWithKeyFrame:[],cuePoints:[],isDefault:!1,inputTrack:null,codecId:null,codecPrivate:null,languageCode:Z,info:null},this.readContiguousElements(t,a),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let s=this.currentTrack.codecId.indexOf("/"),o=s===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,s);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===re.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===re.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.vp8?this.currentTrack.info.codec="vp8":o===re.vp9?this.currentTrack.info.codec="vp9":o===re.av1&&(this.currentTrack.info.codec="av1");let c=this.currentTrack,u=new le(new an(c));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){o===re.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===re.mp3?this.currentTrack.info.codec="mp3":o===re.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):o===re.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let c=this.currentTrack,u=new X(new sn(c));this.currentTrack.inputTrack=u,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=t.readUnsignedInt(a)}break;case 131:{if(!this.currentTrack)break;let s=t.readUnsignedInt(a);s===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null}:s===2&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case 185:{if(!this.currentTrack)break;t.readUnsignedInt(a)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!t.readUnsignedInt(a)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=t.readString(a)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=t.readBytes(a)}break;case 2274716:{if(!this.currentTrack)break;this.currentTrack.languageCode=t.readString(a),Ye(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,a)}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=t.readUnsignedInt(a)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=t.readUnsignedInt(a)}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(t,a)}break;case 21937:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=Yt[s]??null;this.currentTrack.info.colorSpace.matrix=o}break;case 21945:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=t.readUnsignedInt(a)===2}break;case 21946:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=Xt[s]??null;this.currentTrack.info.colorSpace.transfer=o}break;case 21947:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let s=t.readUnsignedInt(a),o=Gt[s]??null;this.currentTrack.info.colorSpace.primaries=o}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,a)}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let o=-t.readFloat(a);try{this.currentTrack.info.rotation=Ae(o)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(t,a)}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=t.readFloat(a)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=t.readUnsignedInt(a)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=t.readUnsignedInt(a)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(t,a),this.currentCueTime=null}break;case 179:this.currentCueTime=t.readUnsignedInt(a);break;case 183:{if(this.currentCueTime===null)break;m(this.currentSegment);let s={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(s),this.readContiguousElements(t,a),(s.trackId===-1||s.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let s=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!s)break;s.trackId=t.readUnsignedInt(a)}break;case 241:{let s=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!s)break;m(this.currentSegment),s.clusterPosition=this.currentSegment.dataStartPos+t.readUnsignedInt(a)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=t.readUnsignedInt(a)}break;case 163:{if(!this.currentCluster)break;let s=t.readVarInt(),o=t.readS16(),u=!!(t.readU8()&128);this.getTrackDataInCluster(this.currentCluster,s).blocks.push({timestamp:o,duration:0,isKeyFrame:u,referencedTimestamps:[],data:t.readBytes(a-(t.pos-n))})}break;case 160:{if(!this.currentCluster)break;if(this.readContiguousElements(t,a),this.currentBlock){for(let s=0;s<this.currentBlock.referencedTimestamps.length;s++)this.currentBlock.referencedTimestamps[s]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case 161:{if(!this.currentCluster)break;let s=t.readVarInt(),o=t.readS16(),c=t.readU8(),u=this.getTrackDataInCluster(this.currentCluster,s);this.currentBlock={timestamp:o,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:t.readBytes(a-(t.pos-n))},u.blocks.push(this.currentBlock)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=t.readUnsignedInt(a)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let s=t.readSignedInt(a);this.currentBlock.referencedTimestamps.push(s)}break}t.pos=n+a}},ti=class{constructor(e){this.internalTrack=e;this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}async getFirstPacket(e){return this.performClusterLookup(()=>{let t=this.internalTrack.segment.clusters[0]??null;if(t?.isKnownToBeFirstCluster){let r=t;for(;r;){if(r.trackData.get(this.internalTrack.id))return{clusterIndex:W(this.internalTrack.clusters,r.elementStartPos,n=>n.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return Xe(e*this.internalTrack.segment.timestampFactor,14)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findBlockInClustersForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=r.cluster.trackData.get(this.internalTrack.id),n=a.blocks[r.blockIndex],s=W(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return m(s!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<a.blocks.length)return{clusterIndex:s,blockIndex:r.blockIndex+1,correctBlockFound:!0};{let o=r.cluster;for(;o.nextCluster;)if(o=o.nextCluster,o.trackData.get(this.internalTrack.id)){let u=W(this.internalTrack.clusters,o.elementStartPos,d=>d.elementStartPos);return m(u!==-1),{clusterIndex:u,blockIndex:0,correctBlockFound:!0}}return{clusterIndex:s,blockIndex:-1,correctBlockFound:!1}}},n.timestamp,1/0,t)}async getKeyPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findKeyBlockInClustersForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=r.cluster.trackData.get(this.internalTrack.id),n=a.blocks[r.blockIndex],s=W(this.internalTrack.clusters,r.cluster.elementStartPos,o=>o.elementStartPos);return m(s!==-1),this.performClusterLookup(()=>{let o=a.blocks.findIndex((c,u)=>c.isKeyFrame&&u>r.blockIndex);if(o!==-1)return{clusterIndex:s,blockIndex:o,correctBlockFound:!0};{let c=r.cluster;for(;c.nextCluster;){c=c.nextCluster;let u=c.trackData.get(this.internalTrack.id);if(u&&u.firstKeyFrameTimestamp!==null){let d=W(this.internalTrack.clusters,c.elementStartPos,p=>p.elementStartPos);m(d!==-1);let l=u.blocks.findIndex(p=>p.isKeyFrame);return m(l!==-1),{clusterIndex:d,blockIndex:l,correctBlockFound:!0}}}return{clusterIndex:s,blockIndex:-1,correctBlockFound:!1}}},n.timestamp,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];m(n);let s=r.metadataOnly?ee:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,u=new D(s,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}findBlockInClustersForTimestamp(e){let t=F(this.internalTrack.clusters,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.clusters[t].trackData.get(this.internalTrack.id),o=F(s.presentationTimestamps,e,c=>c.timestamp);m(o!==-1),r=s.presentationTimestamps[o].blockIndex,a=e<s.endTimestamp}return{clusterIndex:t,blockIndex:r,correctBlockFound:a}}findKeyBlockInClustersForTimestamp(e){let t=F(this.internalTrack.clustersWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).firstKeyFrameTimestamp),r=-1,a=-1,n=!1;if(t!==-1){let s=this.internalTrack.clustersWithKeyFrame[t];r=W(this.internalTrack.clusters,s.elementStartPos,d=>d.elementStartPos),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=Jt(o.presentationTimestamps,d=>o.blocks[d.blockIndex].isKeyFrame&&d.timestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].blockIndex,n=e<o.endTimestamp}return{clusterIndex:r,blockIndex:a,correctBlockFound:n}}async performClusterLookup(e,t,r,a){let{demuxer:n,segment:s}=this.internalTrack,o=await s.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:u,correctBlockFound:d}=e();if(d){let w=this.internalTrack.clusters[c];return this.fetchPacketInCluster(w,u,a)}let l=n.metadataReader,p=n.clusterReader,h=null,f=c,b=u,g=F(this.internalTrack.cuePoints,t,w=>w.time),k=g!==-1?this.internalTrack.cuePoints[g]:null,y=!1;if(c===-1)l.pos=k?.clusterPosition??s.clusterSeekStartPos,y=l.pos===s.clusterSeekStartPos;else{let w=this.internalTrack.clusters[c];!k||w.elementStartPos>=k.clusterPosition?(l.pos=w.elementEndPos,h=w):l.pos=k.clusterPosition}for(;l.pos<s.elementEndPos;){if(h){let A=h.trackData.get(this.internalTrack.id);if(A&&A.startTimestamp>r)break;if(h.nextCluster){l.pos=h.nextCluster.elementEndPos,h=h.nextCluster;continue}}await l.reader.loadRange(l.pos,l.pos+Ne);let w=l.pos,T=l.readElementHeader(),x=T.id,E=T.size,I=l.pos;if(x===524531317){let A=W(s.clusters,w,ui=>ui.elementStartPos),_;A===-1?(l.pos=w,_=await n.readCluster(s)):_=s.clusters[A],h&&(h.nextCluster=_),h=_,y&&(_.isKnownToBeFirstCluster=!0,y=!1);let{clusterIndex:te,blockIndex:ke,correctBlockFound:Fa}=e();if(Fa){let ui=this.internalTrack.clusters[te];return this.fetchPacketInCluster(ui,ke,a)}te!==-1&&(f=te,b=ke)}if(E===null){x===524531317?(m(h),E=h.elementEndPos-I):(p.pos=I,E=(await p.searchForNextElementId(_i,s.elementEndPos)??s.elementEndPos)-I);let A=I+E;if(A>s.elementEndPos-Mr)break;if(p.pos=A,p.readElementId()===408125543){s.elementEndPos=A;break}}l.pos=I+E}let C=null,S=f!==-1?this.internalTrack.clusters[f]:null;if(S&&(C=await this.fetchPacketInCluster(S,b,a)),!C&&k&&(!S||S.elementStartPos<k.clusterPosition)){let T=this.internalTrack.cuePoints[g-1]?.time??-1/0;return this.performClusterLookup(e,T,r,a)}return C}finally{o()}}},an=class extends ti{constructor(t){super(t);this.decoderConfigPromise=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let t=null;return(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(t=await this.getFirstPacket({})),{codec:ur({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcCodecInfo:this.internalTrack.info.codec==="avc"&&t?Sr(t.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&t?Cr(t.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&t?xr(t.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&t?vr(t.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},sn=class extends ti{constructor(t){super(t);this.decoderConfig=null;this.internalTrack=t}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:lr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},So=i=>{let e=new Map;for(let n=0;n<i.length;n++){let s=i[n];e.set(s.timestamp,s)}let t=new Set,r=[],a=n=>{if(!t.has(n)){t.add(n);for(let s=0;s<n.referencedTimestamps.length;s++){let o=n.referencedTimestamps[s],c=e.get(o);c&&a(c)}r.push(n)}};for(let n=0;n<i.length;n++)a(i[n]);return r};var kt=class{constructor(e){this.reader=e;this.pos=0;this.fileSize=null}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readId3(){return this.readAscii(3)!=="ID3"?(this.pos-=3,null):(this.pos+=3,{size:Co(this.readU32())})}readNextFrameHeader(e){for(m(this.fileSize),e??=this.fileSize;this.pos<=e-4;){let t=this.readU32();this.pos-=4;let r=zr(t,this);if(r)return r}return null}},Co=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var ri=class extends oe{constructor(t){super(t);this.metadataPromise=null;this.firstFrameHeader=null;this.allSamples=[];this.tracks=[];this.reader=new kt(t._mainReader)}async readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.input.source.getSize();this.reader.fileSize=t,await this.reader.reader.loadRange(0,t);let r=this.reader.readId3();r&&(this.reader.pos+=r.size);let a=0;for(;;){let n=this.reader.readNextFrameHeader();if(!n)break;let s=ct(n.mpegVersionId,n.channel);this.reader.pos=n.startPos+s;let o=this.reader.readU32(),c=o===ot||o===Vr;if(this.reader.pos=n.startPos+n.totalSize-1,c)continue;this.firstFrameHeader||(this.firstFrameHeader=n);let u=n.audioSamplesInFrame/n.sampleRate,d={timestamp:a/n.sampleRate,duration:u,dataStart:n.startPos,dataSize:n.totalSize};this.allSamples.push(d),a+=n.audioSamplesInFrame}if(!this.firstFrameHeader)throw new Error("No MP3 frames found.");this.tracks=[new X(new cn(this))]})()}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let t=V(this.allSamples);return m(t),t.timestamp+t.duration}},cn=class{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}computeDuration(){return this.demuxer.computeDuration()}getLanguageCode(){return Z}getCodec(){return"mp3"}getNumberOfChannels(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}getPacketAtIndex(e,t){if(e===-1)return null;let r=this.demuxer.allSamples[e];if(!r)return null;let a;return t.metadataOnly?a=ee:(this.demuxer.reader.pos=r.dataStart,a=this.demuxer.reader.readBytes(r.dataSize)),new D(a,"key",r.timestamp,r.duration,e,r.dataSize)}async getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=W(this.demuxer.allSamples,e.timestamp,a=>a.timestamp);if(r===-1)throw new Error("Packet was not created from this track.");return this.getPacketAtIndex(r+1,t)}async getPacket(e,t){let r=F(this.demuxer.allSamples,e,a=>a.timestamp);return this.getPacketAtIndex(r,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ii=class extends oe{constructor(t){super(t);this.readingMutex=new ne;this.metadataPromise=null;this.fileSize=null;this.bitstreams=[];this.tracks=[];this.reader=new dt(new de(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{for(this.fileSize=await this.input.source.getSize();this.reader.pos<this.fileSize-ut;){await this.reader.reader.loadRange(this.reader.pos,this.reader.pos+He);let t=this.reader.readPageHeader();if(!t||!!!(t.headerType&2))break;this.bitstreams.push({serialNumber:t.serialNumber,bosPage:t,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),this.reader.pos=t.headerStartPos+t.totalSize}for(let t of this.bitstreams){let r=await this.readPacket(this.reader,t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.tracks.push(new X(new dn(t,this))))}})()}async readVorbisMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n||(a=await this.findNextPacketStart(this.reader,n),!a))return;let s=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;let o=[],c=p=>{for(;o.push(Math.min(255,p)),!(p<255);)p-=255};c(t.data.length),c(n.data.length);let u=new Uint8Array(1+o.length+t.data.length+n.data.length+s.data.length);u[0]=o.length,u.set(o,1),u.set(t.data,1+o.length),u.set(n.data,1+o.length+t.data.length),u.set(s.data,1+o.length+t.data.length+n.data.length),r.codecInfo.codec="vorbis",r.description=u,r.lastMetadataPacket=s;let d=Y(t.data);r.numberOfChannels=d.getUint8(11),r.sampleRate=d.getUint32(12,!0);let l=d.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:Pr(s.data).modeBlockflags}}async readOpusMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n)return;r.codecInfo.codec="opus",r.description=t.data,r.lastMetadataPacket=n;let s=Oe(t.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=s.inputSampleRate,r.codecInfo.opusInfo={preSkip:s.preSkip}}async readPacket(t,r,a){m(a<r.lacingValues.length),m(this.fileSize);let n=0;for(let h=0;h<a;h++)n+=r.lacingValues[h];let s=r,o=n,c=a,u=[];e:for(;;){await t.reader.loadRange(s.dataStartPos,s.dataStartPos+s.dataSize),t.pos=s.dataStartPos;let h=t.readBytes(s.dataSize);for(;;){if(c===s.lacingValues.length){u.push(h.subarray(n,o));break}let f=s.lacingValues[c];if(o+=f,f<255){u.push(h.subarray(n,o));break e}c++}for(;;){if(t.pos=s.headerStartPos+s.totalSize,t.pos>=this.fileSize-ut)return null;await t.reader.loadRange(t.pos,t.pos+He);let f=t.readPageHeader();if(!f)return null;if(s=f,s.serialNumber===r.serialNumber)break}n=0,o=0,c=0}let d=u.reduce((h,f)=>h+f.length,0),l=new Uint8Array(d),p=0;for(let h=0;h<u.length;h++){let f=u[h];l.set(f,p),p+=f.length}return{data:l,endPage:s,endSegmentIndex:c}}async findNextPacketStart(t,r){if(m(this.fileSize!==null),r.endSegmentIndex<r.endPage.lacingValues.length-1)return{startPage:r.endPage,startSegmentIndex:r.endSegmentIndex+1};if(!!(r.endPage.headerType&4))return null;for(t.pos=r.endPage.headerStartPos+r.endPage.totalSize;;){if(t.pos>=this.fileSize-ut)return null;await t.reader.loadRange(t.pos,t.pos+He);let n=t.readPageHeader();if(!n)return null;if(n.serialNumber===r.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};t.pos=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return Kr({codecStrings:t.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let t=await this.getTracks(),r=await Promise.all(t.map(a=>a.computeDuration()));return Math.max(0,...r)}},dn=class{constructor(e,t){this.bitstream=e;this.demuxer=t;this.encodedPacketToMetadata=new WeakMap;this.internalSampleRate=e.codecInfo.codec==="opus"?et:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}async getDecoderConfig(){return m(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getLanguageCode(){return Z}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(m(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:a,vorbisBlockSize:n}=Hr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new D(r.metadataOnly?ee:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisBlockSize:n}),s}async getFirstPacket(e,t=!0){let r=t?await this.demuxer.readingMutex.acquire():null;try{m(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.demuxer.reader,this.bitstream.lastMetadataPacket);if(!a)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(this.demuxer.reader,a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:null},e)}finally{r?.()}}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let a=this.encodedPacketToMetadata.get(e);if(!a)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(this.demuxer.reader,a.packet);if(!n)return null;let s=a.timestampInSamples+a.durationInSamples,o=await this.demuxer.readPacket(this.demuxer.reader,n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:s,vorbisLastBlocksize:a.vorbisBlockSize},t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{m(this.demuxer.fileSize!==null);let a=Xe(e*this.internalSampleRate,14);if(a===0)return this.getFirstPacket(t,!1);if(a<0)return null;let n=this.demuxer.reader;m(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(n,this.bitstream.lastMetadataPacket);if(!s)return null;let o=s.startPage,c=this.demuxer.fileSize,u=[o];e:for(;o.headerStartPos+o.totalSize<c;){let S=o.headerStartPos,w=Math.floor((S+c)/2),T=w;for(;;){let x=Math.min(T+Qr,c-ut);if(await n.reader.loadRange(T,x),n.pos=T,!n.findNextPageHeader(x)){c=w+ut;continue e}await n.reader.loadRange(n.pos,n.pos+He);let I=n.readPageHeader();m(I);let A=!1;if(I.serialNumber===this.bitstream.serialNumber)A=!0;else{await n.reader.loadRange(I.headerStartPos,I.headerStartPos+I.totalSize),n.pos=I.headerStartPos;let te=n.readBytes(I.totalSize);A=Lr(te)===I.checksum}if(!A){T=I.headerStartPos+4;continue}if(A&&I.serialNumber!==this.bitstream.serialNumber){T=I.headerStartPos+I.totalSize;continue}if(I.granulePosition===-1){T=I.headerStartPos+I.totalSize;continue}this.granulePositionToTimestampInSamples(I.granulePosition)>a?c=I.headerStartPos:(o=I,u.push(I));continue e}}let d=s.startPage;for(let S of u){if(S.granulePosition===o.granulePosition)break;(!d||S.headerStartPos>d.headerStartPos)&&(d=S)}let l=d,p=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===o.granulePosition);){n.pos=l.headerStartPos+l.totalSize,await n.reader.loadRange(n.pos,n.pos+He);let S=n.readPageHeader();m(S),l=S,l.serialNumber===this.bitstream.serialNumber&&p.push(l)}m(l.granulePosition!==-1);let h=null,f,b,g=l,k=0;if(l.headerStartPos===s.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),b=!0,h=0;else{f=0,b=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){h=T+1;break}if(h===null)throw new Error("Invalid page with granule position: no packets end on this page.");k=h-1;let S={data:ee,endPage:g,endSegmentIndex:k};if(await this.demuxer.findNextPacketStart(n,S)){let T=Ca(p,l,h);m(T);let x=Sa(p,T.page,T.segmentIndex);x&&(l=x.page,h=x.segmentIndex)}else for(;;){let T=Ca(p,l,h);if(!T)break;let x=Sa(p,T.page,T.segmentIndex);if(!x)break;if(l=x.page,h=x.segmentIndex,T.page.headerStartPos!==g.headerStartPos){g=T.page,k=T.segmentIndex;break}}}let y=null,C=null;for(;l!==null;){m(h!==null);let S=await this.demuxer.readPacket(n,l,h);if(!S)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&h<s.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:f,vorbisLastBlocksize:C?.vorbisBlockSize??null},t);m(x);let E=this.encodedPacketToMetadata.get(x);if(m(E),!b&&S.endPage.headerStartPos===g.headerStartPos&&S.endSegmentIndex===k?(f=this.granulePositionToTimestampInSamples(l.granulePosition),b=!0,x=this.createEncodedPacketFromOggPacket(S,{timestampInSamples:f-E.durationInSamples,vorbisLastBlocksize:C?.vorbisBlockSize??null},t),m(x),E=this.encodedPacketToMetadata.get(x),m(E)):f+=E.durationInSamples,y=x,C=E,b&&(Math.max(f,0)>a||Math.max(E.timestampInSamples,0)===a))break}let T=await this.demuxer.findNextPacketStart(n,S);if(!T)break;l=T.startPage,h=T.startSegmentIndex}return y}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Sa=(i,e,t)=>{let r=e,a=t;e:for(;;){for(a--,a;a>=0;a--)if(r.lacingValues[a]<255){a++;break e}if(m(a===-1),!(r.headerType&1)){a=0;break}let s=pi(i,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,a=r.lacingValues.length}if(m(a!==-1),a===r.lacingValues.length){let n=i[i.indexOf(r)+1];m(n),r=n,a=0}return{page:r,segmentIndex:a}},Ca=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=pi(i,a=>a.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var be=class{},$t=class extends be{async _getMajorBrand(e){if(await e._mainReader.source.getSize()<12)return null;let r=new qe(e._mainReader);return r.pos=4,r.readAscii(4)!=="ftyp"?null:r.readAscii(4)}_createDemuxer(e){return new Zr(e)}},ni=class extends $t{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},ai=class extends $t{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},qt=class extends be{async isSupportedEBMLOfDocType(e,t){if(await e._mainReader.source.getSize()<8)return!1;let a=new We(e._mainReader),n=a.readVarIntSize();if(n<1||n>8||a.readUnsignedInt(n)!==440786851)return!1;let o=a.readElementSize();if(o===null)return!1;let c=a.pos;for(;a.pos<c+o;){let{id:u,size:d}=a.readElementHeader(),l=a.pos;if(d===null)return!1;switch(u){case 17030:if(a.readUnsignedInt(d)!==1)return!1;break;case 17143:if(a.readUnsignedInt(d)!==1)return!1;break;case 17026:if(a.readString(d)!==t)return!1;break;case 17031:if(a.readUnsignedInt(d)>4)return!1;break}a.pos=l+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new ei(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},si=class extends qt{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},oi=class extends be{async _canReadInput(e){let t=await e._mainReader.source.getSize();if(t<4)return!1;let r=new kt(e._mainReader);r.fileSize=t;let a=r.readId3();a&&(r.pos+=a.size);let n=r.pos;await r.reader.loadRange(r.pos,r.pos+4096);let s=r.readNextFrameHeader(Math.min(n+4096,t));if(!s)return!1;if(a)return!0;r.pos=s.startPos+s.totalSize,await r.reader.loadRange(r.pos,r.pos+4);let o=r.readNextFrameHeader(r.pos+4);return!(!o||s.channel!==o.channel||s.sampleRate!==o.sampleRate)}_createDemuxer(e){return new ri(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},ci=class extends be{async _canReadInput(e){if(await e._mainReader.source.getSize()<12)return!1;let r=new $e(e._mainReader),a=r.readAscii(4);return a!=="RIFF"&&a!=="RIFX"&&a!=="RF64"?!1:(r.pos=8,r.readAscii(4)==="WAVE")}_createDemuxer(e){return new jr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},di=class extends be{async _canReadInput(e){return await e._mainReader.source.getSize()<4?!1:new dt(e._mainReader).readAscii(4)==="OggS"}_createDemuxer(e){return new ii(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},xa=new ni,va=new ai,Pa=new qt,Ea=new si,Ia=new oi,_a=new ci,Aa=new di,xo=[xa,va,Pa,Ea,_a,Aa,Ia];var jt=class{constructor(e){this._demuxerPromise=null;this._format=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof be)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ie))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._mainReader=new de(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{await this._mainReader.loadRange(0,4096);for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(t=>t.isVideoTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(t=>t.isVideoTrack())??null}async getAudioTracks(){return(await this.getTracks()).filter(t=>t.isAudioTrack())}async getPrimaryAudioTrack(){return(await this.getTracks()).find(t=>t.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}};var un=2,ln=48e3,mn=class i{constructor(e){this._addedCounts={video:0,audio:0,subtitle:0};this._totalTrackCount=0;this._trackPromises=[];this._executed=!1;this._synchronizer=new fn;this._totalDuration=null;this._maxTimestamps=new Map;this._canceled=!1;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this.utilizedTracks=[];this.discardedTracks=[];if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof jt))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Kt))throw new TypeError("options.output must be an Output.");if(e.output._tracks.length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks added and not started.");if(e.video!==void 0&&(!e.video||typeof e.video!="object"))throw new TypeError("options.video, when provided, must be an object.");if(e.video?.discard!==void 0&&typeof e.video.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(e.video?.forceTranscode!==void 0&&typeof e.video.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(e.video?.codec!==void 0&&!q.includes(e.video.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${q.join(", ")}.`);if(e.video?.bitrate!==void 0&&!(e.video.bitrate instanceof H)&&(!Number.isInteger(e.video.bitrate)||e.video.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(e.video?.width!==void 0&&(!Number.isInteger(e.video.width)||e.video.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(e.video?.height!==void 0&&(!Number.isInteger(e.video.height)||e.video.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(e.video?.fit!==void 0&&!["fill","contain","cover"].includes(e.video.fit))throw new TypeError('options.video.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.video?.width!==void 0&&e.video.height!==void 0&&e.video.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(e.video?.rotate!==void 0&&![0,90,180,270].includes(e.video.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(e.audio!==void 0&&(!e.audio||typeof e.audio!="object"))throw new TypeError("options.video, when provided, must be an object.");if(e.audio?.discard!==void 0&&typeof e.audio.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(e.audio?.forceTranscode!==void 0&&typeof e.audio.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(e.audio?.codec!==void 0&&!j.includes(e.audio.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${j.join(", ")}.`);if(e.audio?.bitrate!==void 0&&!(e.audio.bitrate instanceof H)&&(!Number.isInteger(e.audio.bitrate)||e.audio.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(e.audio?.numberOfChannels!==void 0&&(!Number.isInteger(e.audio.numberOfChannels)||e.audio.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(e.audio?.sampleRate!==void 0&&(!Number.isInteger(e.audio.sampleRate)||e.audio.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&(!Number.isFinite(e.trim.start)||e.trim.start<0))throw new TypeError("options.trim.start, when provided, must be a non-negative number.");if(e.trim?.end!==void 0&&(!Number.isFinite(e.trim.end)||e.trim.end<0))throw new TypeError("options.trim.end, when provided, must be a non-negative number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");this._options=e,this.input=e.input,this.output=e.output,this._startTimestamp=e.trim?.start??0,this._endTimestamp=e.trim?.end??1/0;let{promise:t,resolve:r}=z();this._started=t,this._start=r}static async init(e){let t=new i(e);return await t._init(),t}async _init(){let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts();for(let a of e){if(a.isVideoTrack()&&this._options.video?.discard){this.discardedTracks.push({track:a,reason:"discarded_by_user"});continue}if(a.isAudioTrack()&&this._options.audio?.discard){this.discardedTracks.push({track:a,reason:"discarded_by_user"});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:a,reason:"max_track_count_reached"});continue}if(this._addedCounts[a.type]===t[a.type].max){this.discardedTracks.push({track:a,reason:"max_track_count_of_type_reached"});continue}a.isVideoTrack()?await this._processVideoTrack(a):a.isAudioTrack()&&await this._processAudioTrack(a)}let r=this.discardedTracks.filter(a=>a.reason!=="discarded_by_user");r.length>0&&console.warn("Some tracks had to be discarded from the conversion:",r)}async execute(){if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0,this.onProgress&&(this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp),this.onProgress?.(0)),await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||await this.cancel(),e}this._canceled&&await new Promise(()=>{}),await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e){let t=e.codec;if(!t){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let r,a=Ae(e.rotation+(this._options.video?.rotate??0)),n=this.output.format.supportsVideoRotationMetadata,[s,o]=a%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],c=s,u=o,d=c/u,l=g=>Math.ceil(g/2)*2;this._options.video?.width!==void 0&&this._options.video.height===void 0?(c=l(this._options.video.width),u=l(Math.round(c/d))):this._options.video?.width===void 0&&this._options.video?.height!==void 0?(u=l(this._options.video.height),c=l(Math.round(u*d))):this._options.video?.width!==void 0&&this._options.video.height!==void 0&&(c=l(this._options.video.width),u=l(this._options.video.height));let p=await e.getFirstTimestamp(),h=!!this._options.video?.forceTranscode||this._startTimestamp>0||p<0,f=c!==s||u!==o||a!==0&&!n,b=this.output.format.getSupportedVideoCodecs();if(!h&&!this._options.video?.bitrate&&!f&&b.includes(t)&&(!this._options.video?.codec||this._options.video?.codec===t)){let g=new Nt(t);r=g,this._trackPromises.push((async()=>{await this._started;let k=new he(e),C={decoderConfig:await e.getDecoderConfig()??void 0},S=Number.isFinite(this._endTimestamp)?await k.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let w of k.packets(void 0,S,{verifyKeyPackets:!0})){if(this._synchronizer.shouldWait(e.id,w.timestamp)&&await this._synchronizer.wait(w.timestamp),this._canceled)return;await g.add(w,C),this._reportProgress(e.id,w.timestamp+w.duration)}g.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}this._options.video?.codec&&(b=b.filter(S=>S===this._options.video?.codec));let k=this._options.video?.bitrate??mr,y=await wi(b,{width:c,height:u,bitrate:k});if(!y){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}let C={codec:y,bitrate:k,onEncodedPacket:S=>this._reportProgress(e.id,S.timestamp+S.duration)};if(f){let S=new ht(C);r=S,this._trackPromises.push((async()=>{await this._started;let T=new Vt(e,{width:c,height:u,fit:this._options.video?.fit??"fill",rotation:a,poolSize:1}).canvases(this._startTimestamp,this._endTimestamp);for await(let{canvas:x,timestamp:E,duration:I}of T){if(this._synchronizer.shouldWait(e.id,E)&&await this._synchronizer.wait(E),this._canceled)return;let A=new ce(x,{timestamp:Math.max(E-this._startTimestamp,0),duration:I});await S.add(A),A.close()}})())}else{let S=new ht(C);r=S,this._trackPromises.push((async()=>{await this._started;let w=new mt(e);for await(let T of w.samples(this._startTimestamp,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,T.timestamp)&&await this._synchronizer.wait(T.timestamp),T.setTimestamp(Math.max(T.timestamp-this._startTimestamp,0)),this._canceled)return;await S.add(T),T.close()}S.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addVideoTrack(r,{languageCode:e.languageCode,rotation:f?0:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _processAudioTrack(e){let t=e.codec;if(!t){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let r,a=e.numberOfChannels,n=e.sampleRate,s=await e.getFirstTimestamp(),o=this._options.audio?.numberOfChannels??a,c=this._options.audio?.sampleRate??n,u=o!==a||c!==n||this._startTimestamp>0||s<0,d=this.output.format.getSupportedAudioCodecs();if(!this._options.audio?.forceTranscode&&!this._options.audio?.bitrate&&!u&&d.includes(t)&&(!this._options.audio?.codec||this._options.audio.codec===t)){let l=new Lt(t);r=l,this._trackPromises.push((async()=>{await this._started;let p=new he(e),f={decoderConfig:await e.getDecoderConfig()??void 0},b=Number.isFinite(this._endTimestamp)?await p.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let g of p.packets(void 0,b)){if(this._synchronizer.shouldWait(e.id,g.timestamp)&&await this._synchronizer.wait(g.timestamp),this._canceled)return;await l.add(g,f),this._reportProgress(e.id,g.timestamp+g.duration)}l.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}let p=null;this._options.audio?.codec&&(d=d.filter(b=>b===this._options.audio.codec));let h=this._options.audio?.bitrate??mr,f=await xt(d,{numberOfChannels:o,sampleRate:c,bitrate:h});if(!f.some(b=>Ce.includes(b))&&d.some(b=>Ce.includes(b))&&(o!==un||c!==ln)){let g=(await xt(d,{numberOfChannels:un,sampleRate:ln,bitrate:h})).find(k=>Ce.includes(k));g&&(u=!0,p=g,o=un,c=ln)}else p=f[0]??null;if(p===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}if(u)r=this._resampleAudio(e,p,o,c,h);else{let b=new gt({codec:p,bitrate:h,onEncodedPacket:g=>this._reportProgress(e.id,g.timestamp+g.duration)});r=b,this._trackPromises.push((async()=>{await this._started;let g=new Ke(e);for await(let k of g.samples(void 0,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,k.timestamp)&&await this._synchronizer.wait(k.timestamp),this._canceled)return;await b.add(k),k.close()}b.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:e.languageCode}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}_resampleAudio(e,t,r,a,n){let s=new gt({codec:t,bitrate:n,onEncodedPacket:o=>this._reportProgress(e.id,o.timestamp+o.duration)});return this._trackPromises.push((async()=>{await this._started;let o=new pn({sourceNumberOfChannels:e.numberOfChannels,sourceSampleRate:e.sampleRate,targetNumberOfChannels:r,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:d=>s.add(d)}),u=new Ke(e).samples(this._startTimestamp,this._endTimestamp);for await(let d of u){if(this._synchronizer.shouldWait(e.id,d.timestamp)&&await this._synchronizer.wait(d.timestamp),this._canceled)return;await o.add(d)}await o.finalize(),s.close(),this._synchronizer.closeTrack(e.id)})()),s}_reportProgress(e,t){if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)??-1/0));let r=0;for(let[,s]of this._maxTimestamps)r+=s;let a=r/this._totalTrackCount,n=$(a/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},Ra=5,fn=class{constructor(){this.maxTimestamps=new Map;this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let r=this.resolvers[t];r.timestamp-e<Ra&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0));let r=this.computeMinAndMaybeResolve();return t-r>=Ra}wait(e){let{promise:t,resolve:r}=z();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},pn=class{constructor(e){this.sourceSampleRate=e.sourceSampleRate,this.targetSampleRate=e.targetSampleRate,this.sourceNumberOfChannels=e.sourceNumberOfChannels,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1,this.setupChannelMixer(),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels)}setupChannelMixer(){let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(r,a)=>r[a*e]:e===1&&t===4?this.channelMixer=(r,a,n)=>r[a*e]*+(n<2):e===1&&t===6?this.channelMixer=(r,a,n)=>r[a*e]*+(n===2):e===2&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .5*(r[n]+r[n+1])}:e===2&&t===4?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .25*(r[n]+r[n+1]+r[n+2]+r[n+3])}:e===4&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return .5*(r[s+n]+r[s+n+2])}:e===4&&t===6?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]:n===2||n===3?0:r[s+n-2]}:e===6&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return Math.SQRT1_2*(r[n]+r[n+1])+r[n+2]+.5*(r[n+4]+r[n+5])}:e===6&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return r[s+n]+Math.SQRT1_2*(r[s+2]+r[s+n+4])}:e===6&&t===4?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]+Math.SQRT1_2*r[s+2]:r[s+n+2]}:this.channelMixer=(r,a,n)=>n<e?r[a*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let r=new Float32Array(t);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(e){if(!e||e._closed)return;let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(a,{planeIndex:0,format:"f32"});let n=e.timestamp-this.startTime,s=e.numberOfFrames/this.sourceSampleRate,o=Math.min(n+s,this.endTime-this.startTime),c=Math.floor(n*this.targetSampleRate),u=Math.ceil(o*this.targetSampleRate);for(let d=c;d<u;d++){if(d<this.bufferStartFrame)continue;for(;d>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=d-this.bufferStartFrame;m(l<this.bufferSizeInFrames);let f=(d/this.targetSampleRate-n)*this.sourceSampleRate,b=Math.floor(f),g=Math.ceil(f),k=f-b;for(let y=0;y<this.targetNumberOfChannels;y++){let C=0,S=0;b>=0&&b<e.numberOfFrames&&(C=this.channelMixer(a,b,y)),g>=0&&g<e.numberOfFrames&&(S=this.channelMixer(a,g,y));let w=C+k*(S-C),T=l*this.targetNumberOfChannels+y;this.outputBuffer[T]+=w}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let r=this.bufferStartFrame/this.targetSampleRate,a=new ie({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:t});await this.onSample(a),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};export{xo as ALL_FORMATS,ka as ALL_TRACK_TYPES,j as AUDIO_CODECS,Ui as AudioBufferSink,Qi as AudioBufferSource,ie as AudioSample,Ke as AudioSampleSink,gt as AudioSampleSource,Ee as AudioSource,Dt as BaseMediaSampleSink,Ji as BlobSource,Yi as BufferSource,_t as BufferTarget,Vt as CanvasSink,Hi as CanvasSource,mn as Conversion,rr as CustomAudioDecoder,nr as CustomAudioEncoder,tr as CustomVideoDecoder,ir as CustomVideoEncoder,Lt as EncodedAudioPacketSource,D as EncodedPacket,he as EncodedPacketSink,Nt as EncodedVideoPacketSource,jt as Input,X as InputAudioTrack,be as InputFormat,Qe as InputTrack,le as InputVideoTrack,$t as IsobmffInputFormat,Ut as IsobmffOutputFormat,Pa as MATROSKA,Ia as MP3,xa as MP4,qt as MatroskaInputFormat,pt as MediaSource,$i as MediaStreamAudioTrackSource,Ki as MediaStreamVideoTrackSource,zt as MkvOutputFormat,it as MovOutputFormat,oi as Mp3InputFormat,Ni as Mp3OutputFormat,ni as Mp4InputFormat,Yr as Mp4OutputFormat,Ce as NON_PCM_AUDIO_CODECS,Aa as OGG,di as OggInputFormat,Li as OggOutputFormat,Kt as Output,ge as OutputFormat,U as PCM_AUDIO_CODECS,va as QTFF,mr as QUALITY_HIGH,Va as QUALITY_LOW,Ua as QUALITY_MEDIUM,za as QUALITY_VERY_HIGH,Da as QUALITY_VERY_LOW,H as Quality,ai as QuickTimeInputFormat,ae as SUBTITLE_CODECS,Ie as Source,Zi as StreamSource,Ii as StreamTarget,bt as SubtitleSource,ze as Target,qi as TextSubtitleSource,en as UrlSource,q as VIDEO_CODECS,ce as VideoSample,mt as VideoSampleSink,ht as VideoSampleSource,Pe as VideoSource,_a as WAVE,Ea as WEBM,Wi as WavOutputFormat,ci as WaveInputFormat,si as WebMInputFormat,st as WebMOutputFormat,$a as canEncode,gr as canEncodeAudio,br as canEncodeSubtitles,hr as canEncodeVideo,xt as getEncodableAudioCodecs,qa as getEncodableCodecs,Fn as getEncodableSubtitleCodecs,Rn as getEncodableVideoCodecs,ja as getFirstEncodableAudioCodec,Ga as getFirstEncodableSubtitleCodec,wi as getFirstEncodableVideoCodec,Ma as registerDecoder,Ba as registerEncoder};
|