UNPKG

mediabunny

Version:

Pure TypeScript media toolkit for reading, writing, and converting media files, directly in the browser.

17 lines 305 kB
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
function m(n){if(!n)throw new Error("Assertion failed.")}var De=n=>{let e=(n%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${n}.`)},U=n=>n&&n[n.length-1],Le=n=>n>=0&&n<2**32,q=class n{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 n(this.bytes);return e.pos=this.pos,e}},I=n=>{let e=0;for(;n.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+n.readBits(e)},rt=n=>{let e=I(n);return(e&1)===0?-(e>>1):e+1>>1},In=(n,e,t,r)=>{for(let a=e;a<t;a++){let i=Math.floor(a/8),s=n[i],o=7-(a&7);s&=~(1<<o),s|=(r&1<<t-a-1)>>t-a-1<<o,n[i]=s}},K=n=>n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),ee=n=>n instanceof DataView?n:n instanceof ArrayBuffer?new DataView(n):new DataView(n.buffer,n.byteOffset,n.byteLength),fe=new TextEncoder,Ti=n=>Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e])),Ce={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ir=Ti(Ce),xe={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},nr=Ti(xe),ve={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ar=Ti(ve),sr=n=>!!n&&!!n.primaries&&!!n.transfer&&!!n.matrix&&n.fullRange!==void 0,it=n=>n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer||ArrayBuffer.isView(n),ie=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}},yi=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),Si=n=>(n=n>>1&1431655765|(n&1431655765)<<1,n=n>>2&858993459|(n&858993459)<<2,n=n>>4&252645135|(n&252645135)<<4,n=n>>8&16711935|(n&16711935)<<8,n=n>>16&65535|(n&65535)<<16,n>>>0),H=(n,e,t)=>{let r=0,a=n.length-1,i=-1;for(;r<=a;){let s=r+a>>1,o=t(n[s]);o===e?(i=s,a=s-1):o<e?r=s+1:a=s-1}return i},V=(n,e,t)=>{let r=0,a=n.length-1,i=-1;for(;r<=a;){let s=r+(a-r+1)/2|0;t(n[s])<=e?(i=s,r=s+1):a=s-1}return i},pe=(n,e,t)=>{let r=V(n,t(e),t);n.splice(r+1,0,e)},W=()=>{let n,e;return{promise:new Promise((r,a)=>{n=r,e=a}),resolve:n,reject:e}},En=(n,e)=>{let t=n.indexOf(e);t!==-1&&n.splice(t,1)},Ci=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return n[t]},or=(n,e)=>{for(let t=n.length-1;t>=0;t--)if(e(n[t]))return t;return-1},_n=async function*(n){Symbol.iterator in n?yield*n[Symbol.iterator]():yield*n[Symbol.asyncIterator]()},An=n=>{if(!(Symbol.iterator in n)&&!(Symbol.asyncIterator in n))throw new TypeError("Argument must be an iterable or async iterable.")},Pe=n=>{throw new Error(`Unexpected value: ${n}`)},xi=(n,e,t)=>{let r=n.getUint8(e),a=n.getUint8(e+1),i=n.getUint8(e+2);return t?r|a<<8|i<<16:r<<16|a<<8|i},Rn=(n,e,t)=>xi(n,e,t)<<8>>8,vi=(n,e,t,r)=>{t=t>>>0,t=t&16777215,r?(n.setUint8(e,t&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t>>>16&255)):(n.setUint8(e,t>>>16&255),n.setUint8(e+1,t>>>8&255),n.setUint8(e+2,t&255))},Fn=(n,e,t,r)=>{t=j(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),vi(n,e,t,r)},On=(n,e,t,r)=>{r?(n.setUint32(e+0,t,!0),n.setInt32(e+4,Math.floor(t/2**32),!0)):(n.setInt32(e+0,Math.floor(t/2**32),!0),n.setUint32(e+4,t,!0))},Et=(n,e)=>({async next(){let t=await n.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return n.return()},throw(t){return n.throw(t)},[Symbol.asyncIterator](){return this}}),j=(n,e,t)=>Math.max(e,Math.min(t,n)),te="und",nt=(n,e)=>{let t=10**e;return Math.round(n*t)/t},_t=(n,e)=>Math.round(n/e)*e,Mn=n=>{let e=0;for(;n;)e++,n>>=1;return e},Ka=/^[a-z]{3}$/,at=n=>Ka.test(n),be=1e6*(1+Number.EPSILON),At=(n,e)=>{let t={...n};for(let r in e)typeof n[r]=="object"&&n[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=At(n[r],e[r]):t[r]=e[r];return t},cr=async(n,e,t)=>{let r=0;for(;;)try{return await fetch(n,e)}catch(a){r++;let i=t(r);if(i===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(i)||i<0)throw new TypeError("Retry delay must be a non-negative finite number.");i>0&&await new Promise(s=>setTimeout(s,1e3*i))}},Bn=(n,e)=>{let t=n<0?-1:1;n=Math.abs(n);let r=0,a=1,i=1,s=0,o=n;for(;;){let c=Math.floor(o),u=c*i+r,d=c*s+a;if(d>e)return{numerator:t*i,denominator:s};if(r=i,a=s,i=u,s=d,o=1/(o-c),!isFinite(o))break}return{numerator:t*i,denominator:s}},Be=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},wi=null,dr=()=>{if(wi!==null)return wi;let n=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i)&&!navigator.userAgent?.match(/crios/i)&&!navigator.userAgent?.match(/fxios/i)&&!navigator.userAgent?.match(/Opera|OPT\//));return wi=n,n};var ur=class{static supports(e,t){return!1}},lr=class{static supports(e,t){return!1}},mr=class{static supports(e,t){return!1}},fr=class{static supports(e,t){return!1}},st=[],ot=[],He=[],Ke=[],Qa=n=>{if(n.prototype instanceof ur){let e=n;if(st.includes(e)){console.warn("Video decoder already registered.");return}st.push(e)}else if(n.prototype instanceof lr){let e=n;if(ot.includes(e)){console.warn("Audio decoder already registered.");return}ot.push(e)}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},qa=n=>{if(n.prototype instanceof mr){let e=n;if(He.includes(e)){console.warn("Video encoder already registered.");return}He.push(e)}else if(n.prototype instanceof fr){let e=n;if(Ke.includes(e)){console.warn("Audio encoder already registered.");return}Ke.push(e)}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var G=["avc","hevc","vp9","av1","vp8"],z=["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"],Ee=["aac","opus","mp3","vorbis","flac"],Y=[...Ee,...z],ce=["webvtt"],Dn=[{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}],Ie=[{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}],Un=[{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}],zn=".01.01.01.01.00",Wn=".0.110.01.01.01.0",pr=(n,e,t,r)=>{if(n==="avc"){let i=Math.ceil(e/16)*Math.ceil(t/16),s=Dn.find(l=>i<=l.maxMacroblocks&&r<=l.maxBitrate)??U(Dn),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(n==="hevc"){let a="",s="6",o=e*t,c=Vn.find(d=>o<=d.maxPictureSize&&r<=d.maxBitrate)??U(Vn);return`hev1.${a}1.${s}.${c.tier}${c.level}.B0`}else{if(n==="vp8")return"vp8";if(n==="vp9"){let a="00",i=e*t,s=Ie.find(c=>i<=c.maxPictureSize&&r<=c.maxBitrate)??U(Ie);return`vp09.${a}.${s.level.toString().padStart(2,"0")}.08`}else if(n==="av1"){let i=e*t,s=Un.find(u=>i<=u.maxPictureSize&&r<=u.maxBitrate)??U(Un);return`av01.0.${s.level.toString().padStart(2,"0")}${s.tier}.08`}}throw new TypeError(`Unhandled codec '${n}'.`)},Nn=n=>{let e=n.split("."),t=Number(e[1]),r=Number(e[2]),a=Number(e[3]),i=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,a,4,1,i]},kr=n=>{let e=n.split("."),a=(1<<7)+1,i=Number(e[1]),s=e[2],o=Number(s.slice(0,-1)),c=(i<<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,k=e[5]?Number(e[5][1]):1,g=e[5]?Number(e[5][2]):0,b=(u<<7)+(l<<6)+(p<<5)+(h<<4)+(f<<3)+(k<<2)+g;return[a,c,b,0]},wr=n=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:i,vp9CodecInfo:s,av1CodecInfo:o}=n;if(e==="avc"){if(a){let c=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc1.${yi(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.${yi(t.subarray(1,4))}`}else if(e==="hevc"){let c,u,d,l,p,h;if(i)c=i.generalProfileSpace,u=i.generalProfileIdc,d=Si(i.generalProfileCompatibilityFlags),l=i.generalTierFlag,p=i.generalLevelIdc,h=[...i.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 k=ee(t),g=k.getUint8(1);c=g>>6&3,u=g&31,d=Si(k.getUint32(2)),l=g>>5&1,p=k.getUint8(12),h=[];for(let b=0;b<6;b++)h.push(k.getUint8(6+b))}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(k=>k.toString(16).toUpperCase()).join(".")),f}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!s){let b=n.width*n.height,w=U(Ie).level;for(let C of Ie)if(b<=C.maxPictureSize){w=C.level;break}return`vp09.00.${w.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"),k=s.videoFullRangeFlag.toString().padStart(2,"0"),g=`vp09.${c}.${u}.${d}.${l}`;return g+=`.${p}.${h}.${f}.${k}`,g.endsWith(zn)&&(g=g.slice(0,-zn.length)),g}else if(e==="av1"){if(!o){let C=n.width*n.height,x=U(Ie).level;for(let y of Ie)if(C<=y.maxPictureSize){x=y.level;break}return`av01.0.${x.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?Ce[r.primaries]:1,k=r?.transfer?xe[r.transfer]:1,g=r?.matrix?ve[r.matrix]:1,b=r?.fullRange?1:0,w=`av01.${c}.${u}${d}.${l}`;return w+=`.${p}.${h.toString().padStart(3,"0")}`,w+=`.${f.toString().padStart(2,"0")}`,w+=`.${k.toString().padStart(2,"0")}`,w+=`.${g.toString().padStart(2,"0")}`,w+=`.${b}`,w.endsWith(Wn)&&(w=w.slice(0,-Wn.length)),w}}throw new TypeError(`Unhandled codec '${e}'.`)},hr=(n,e,t)=>{if(n==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(n==="mp3")return"mp3";if(n==="opus")return"opus";if(n==="vorbis")return"vorbis";if(n==="flac")return"flac";if(z.includes(n))return n;throw new TypeError(`Unhandled codec '${n}'.`)},Tr=n=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=n;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${Pi(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&&z.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Pi=n=>{if(!n||n.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new q(n),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 i=e.readBits(4),s=null;return i>=1&&i<=7&&(s={1:1,2:2,3:3,4:4,5:5,6:6,7:8}[i]),{objectType:t,frequencyIndex:r,sampleRate:a,channelConfiguration:i,numberOfChannels:s}},ct=48e3,Ln=/^pcm-([usf])(\d+)+(be)?$/,Z=n=>{if(m(z.includes(n)),n==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(n==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Ln.exec(n);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",i=n==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:a,silentValue:i}},Ii=n=>n.startsWith("avc1")||n.startsWith("avc3")?"avc":n.startsWith("hev1")||n.startsWith("hvc1")?"hevc":n==="vp8"?"vp8":n.startsWith("vp09")?"vp9":n.startsWith("av01")?"av1":n.startsWith("mp4a.40")||n==="mp4a.67"?"aac":n==="mp3"||n==="mp4a.69"||n==="mp4a.6B"||n==="mp4a.6b"?"mp3":n==="opus"?"opus":n==="vorbis"?"vorbis":n==="flac"?"flac":n==="ulaw"?"ulaw":n==="alaw"?"alaw":Ln.test(n)?n:n==="webvtt"?"webvtt":null,gr=n=>n==="avc"?{avc:{format:"avc"}}:n==="hevc"?{hevc:{format:"hevc"}}:{},br=n=>n==="aac"?{aac:{format:"aac"}}:n==="opus"?{opus:{format:"opus"}}:{},Q=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){let a=t*r,i={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*i[e]*this._factor;return Math.ceil(l/1e3)*1e3}_toAudioBitrate(e){if(z.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}},$a=new Q(.3),ja=new Q(.6),Ga=new Q(1),yr=new Q(2),Xa=new Q(4),Ya=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Za=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ja=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,es=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ts=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Sr=n=>{if(!n)throw new TypeError("Video chunk metadata must be provided.");if(typeof n!="object")throw new TypeError("Video chunk metadata must be an object.");if(!n.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof n.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof n.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Ya.some(e=>n.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(n.decoderConfig.codedWidth)||n.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(n.decoderConfig.codedHeight)||n.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(n.decoderConfig.description!==void 0&&!it(n.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(n.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=n.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(Ce);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(xe);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(ve);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(n.decoderConfig.codec.startsWith("avc1")||n.decoderConfig.codec.startsWith("avc3")){if(!Za.test(n.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(n.decoderConfig.codec.startsWith("hev1")||n.decoderConfig.codec.startsWith("hvc1")){if(!Ja.test(n.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(n.decoderConfig.codec.startsWith("vp8")){if(n.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(n.decoderConfig.codec.startsWith("vp09")){if(!es.test(n.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(n.decoderConfig.codec.startsWith("av01")&&!ts.test(n.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/.')},rs=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Ve=n=>{if(!n)throw new TypeError("Audio chunk metadata must be provided.");if(typeof n!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!n.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof n.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof n.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!rs.some(e=>n.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(n.decoderConfig.sampleRate)||n.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(n.decoderConfig.numberOfChannels)||n.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(n.decoderConfig.description!==void 0&&!it(n.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(n.decoderConfig.codec.startsWith("mp4a")&&n.decoderConfig.codec!=="mp4a.69"&&n.decoderConfig.codec!=="mp4a.6B"&&n.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(n.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(!n.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(n.decoderConfig.codec.startsWith("mp3")||n.decoderConfig.codec.startsWith("mp4a")){if(n.decoderConfig.codec!=="mp3"&&n.decoderConfig.codec!=="mp4a.69"&&n.decoderConfig.codec!=="mp4a.6B"&&n.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(n.decoderConfig.codec.startsWith("opus")){if(n.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(n.decoderConfig.description&&n.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(n.decoderConfig.codec.startsWith("vorbis")){if(n.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!n.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(n.decoderConfig.codec.startsWith("flac")){if(n.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!n.decoderConfig.description||n.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((n.decoderConfig.codec.startsWith("pcm")||n.decoderConfig.codec.startsWith("ulaw")||n.decoderConfig.codec.startsWith("alaw"))&&!z.includes(n.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${z.join(", ")}).`)},Cr=n=>{if(!n)throw new TypeError("Subtitle metadata must be provided.");if(typeof n!="object")throw new TypeError("Subtitle metadata must be an object.");if(!n.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof n.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof n.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},is=n=>{if(G.includes(n))return xr(n);if(Y.includes(n))return vr(n);if(ce.includes(n))return Pr(n);throw new TypeError(`Unknown codec '${n}'.`)},xr=async(n,{width:e=1280,height:t=720,bitrate:r=1e6}={})=>{if(!G.includes(n))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 Q)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");let a=r instanceof Q?r._toVideoBitrate(n,e,t):r;if(He.length>0){let s={codec:pr(n,e,t,a),width:e,height:t,bitrate:a,...gr(n)};if(He.some(o=>o.supports(n,s)))return!0}return typeof VideoEncoder>"u"?!1:(await VideoEncoder.isConfigSupported({codec:pr(n,e,t,a),width:e,height:t,bitrate:a,...gr(n)})).supported===!0},vr=async(n,{numberOfChannels:e=2,sampleRate:t=48e3,bitrate:r=128e3}={})=>{if(!Y.includes(n))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 Q)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");let a=r instanceof Q?r._toAudioBitrate(n):r;if(Ke.length>0){let s={codec:hr(n,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...br(n)};if(Ke.some(o=>o.supports(n,s)))return!0}return z.includes(n)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported({codec:hr(n,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...br(n)})).supported===!0},Pr=async n=>!!ce.includes(n),ns=async()=>{let[n,e,t]=await Promise.all([Hn(),Rt(),Kn()]);return[...n,...e,...t]},Hn=async(n=G,e)=>{let t=await Promise.all(n.map(r=>xr(r,e)));return n.filter((r,a)=>t[a])},Rt=async(n=Y,e)=>{let t=await Promise.all(n.map(r=>vr(r,e)));return n.filter((r,a)=>t[a])},Kn=async(n=ce)=>{let e=await Promise.all(n.map(Pr));return n.filter((t,r)=>e[r])},Ei=async(n,e)=>{for(let t of n)if(await xr(t,e))return t;return null},as=async(n,e)=>{for(let t of n)if(await vr(t,e))return t;return null},ss=async n=>{for(let e of n)if(await Pr(e))return e;return null};var Ft=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,os=/^WEBVTT(.|\n)*?\n{2}/,dt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ir=class{constructor(e){this.preambleText=null;this.preambleEmitted=!1;this.options=e}parse(e){e=e.replaceAll(`\r
`,`
`).replaceAll("\r",`
`),Ft.lastIndex=0;let t;if(!this.preambleText){if(!os.test(e))throw new Error("WebVTT preamble incorrect.");t=Ft.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),Ft.lastIndex=0)}for(;t=Ft.exec(e);){let r=e.slice(0,t.index),a=t[1],i=t.index+t[0].length,s=e.indexOf(`
`,i)+1,o=e.slice(i,s).trim(),c=e.indexOf(`

`,i);c===-1&&(c=e.length);let u=Er(t[2]),l=Er(t[3])-u,p=e.slice(s,c).trim();e=e.slice(c).trimStart(),Ft.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)}}},cs=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Er=n=>{let e=cs.exec(n);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])},_r=n=>{let e=Math.floor(n/36e5),t=Math.floor(n%(60*60*1e3)/(60*1e3)),r=Math.floor(n%(60*1e3)/1e3),a=n%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var Ot=n=>{let e=[],t=0;for(;t<n.length;){let r=-1,a=0;for(let i=t;i<n.length-3;i++){if(n[i]===0&&n[i+1]===0&&n[i+2]===1){r=i,a=3;break}if(i<n.length-4&&n[i]===0&&n[i+1]===0&&n[i+2]===0&&n[i+3]===1){r=i,a=4;break}}if(r===-1)break;if(t>0&&r>t){let i=n.subarray(t,r);i.length>0&&e.push(i)}t=r+a}if(t<n.length){let r=n.subarray(t);r.length>0&&e.push(r)}return e},Qn=(n,e)=>{let t=[],r=0,a=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;r+e<=n.length;){let i;e===1?i=a.getUint8(r):e===2?i=a.getUint16(r,!1):e===3?i=(a.getUint16(r,!1)<<8)+a.getUint8(r+2):e===4?i=a.getUint32(r,!1):(Pe(e),m(!1)),r+=e;let s=n.subarray(r,r+i);t.push(s),r+=i}return t},_i=n=>{let e=[],t=n.length;for(let r=0;r<t;r++)r+2<t&&n[r]===0&&n[r+1]===0&&n[r+2]===3?(e.push(0,0),r+=2):e.push(n[r]);return new Uint8Array(e)},Xn=n=>{let t=Ot(n);if(t.length===0)return null;let r=0;for(let o of t)r+=4+o.byteLength;let a=new Uint8Array(r),i=new DataView(a.buffer),s=0;for(let o of t){let c=o.byteLength;i.setUint32(s,c,!1),s+=4,a.set(o,s),s+=o.byteLength}return a},Ar=n=>n[0]&31,Rr=n=>{try{let e=Ot(n),t=e.filter(p=>Ar(p)===7),r=e.filter(p=>Ar(p)===8),a=e.filter(p=>Ar(p)===13);if(t.length===0||r.length===0)return null;let i=t[0],s=new q(_i(i));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){I(s);let p=I(s);p===3&&s.skipBits(1);let h=I(s),f=I(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}},Yn=n=>{let e=[];e.push(n.configurationVersion),e.push(n.avcProfileIndication),e.push(n.profileCompatibility),e.push(n.avcLevelIndication),e.push(252|n.lengthSizeMinusOne&3),e.push(224|n.sequenceParameterSets.length&31);for(let t of n.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(n.pictureParameterSets.length);for(let t of n.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(n.avcProfileIndication===100||n.avcProfileIndication===110||n.avcProfileIndication===122||n.avcProfileIndication===144){m(n.chromaFormat!==null),m(n.bitDepthLumaMinus8!==null),m(n.bitDepthChromaMinus8!==null),m(n.sequenceParameterSetExt!==null),e.push(252|n.chromaFormat&3),e.push(248|n.bitDepthLumaMinus8&7),e.push(248|n.bitDepthChromaMinus8&7),e.push(n.sequenceParameterSetExt.length);for(let t of n.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)},qn=32,$n=33,jn=34,ds=39,us=40,Qe=n=>n[0]>>1&63,Fr=n=>{try{let e=Ot(n),t=e.filter(A=>Qe(A)===qn),r=e.filter(A=>Qe(A)===$n),a=e.filter(A=>Qe(A)===jn),i=e.filter(A=>Qe(A)===ds||Qe(A)===us);if(r.length===0||a.length===0)return null;let s=r[0],o=new q(_i(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:k}=ls(o,c);I(o);let g=I(o);g===3&&o.skipBits(1),I(o),I(o),o.readBits(1)&&(I(o),I(o),I(o),I(o));let b=I(o),w=I(o);I(o);let x=o.readBits(1)?0:c;for(let A=x;A<=c;A++)I(o),I(o),I(o);I(o),I(o),I(o),I(o),I(o),I(o),o.readBits(1)&&o.readBits(1)&&ms(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),I(o),I(o),o.skipBits(1));let y=I(o);if(fs(o,y),o.readBits(1)){let A=I(o);for(let _=0;_<A;_++)I(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let T=0;o.readBits(1)&&(T=hs(o,c));let S=0;if(a.length>0){let A=a[0],_=new q(_i(A));_.skipBits(16),I(_),I(_),_.skipBits(1),_.skipBits(1),_.skipBits(3),_.skipBits(1),_.skipBits(1),I(_),I(_),rt(_),_.skipBits(1),_.skipBits(1),_.readBits(1)&&I(_),rt(_),rt(_),_.skipBits(1),_.skipBits(1),_.skipBits(1),_.skipBits(1);let M=_.readBits(1),N=_.readBits(1);!M&&!N?S=0:M&&!N?S=2:!M&&N?S=3:S=0}let v=[...t.length?[{arrayCompleteness:1,nalUnitType:qn,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:$n,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:jn,nalUnits:a}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Qe(i[0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:l,generalProfileIdc:p,generalProfileCompatibilityFlags:h,generalConstraintIndicatorFlags:f,generalLevelIdc:k,minSpatialSegmentationIdc:T,parallelismType:S,chromaFormatIdc:g,bitDepthLumaMinus8:b,bitDepthChromaMinus8:w,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:c+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:v}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},ls=(n,e)=>{let t=n.readBits(2),r=n.readBits(1),a=n.readBits(5),i=0;for(let d=0;d<32;d++)i=i<<1|n.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=n.readBits(8);let o=n.readBits(8),c=[],u=[];for(let d=0;d<e;d++)c.push(n.readBits(1)),u.push(n.readBits(1));if(e>0)for(let d=e;d<8;d++)n.skipBits(2);for(let d=0;d<e;d++)c[d]&&n.skipBits(88),u[d]&&n.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:i,general_constraint_indicator_flags:s,general_level_idc:o}},ms=n=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!n.readBits(1))I(n);else{let a=Math.min(64,1<<4+(e<<1));e>1&&rt(n);for(let i=0;i<a;i++)rt(n)}},fs=(n,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=ps(n,r,e,t)},ps=(n,e,t,r)=>{let a=0,i=0,s=0;if(e!==0&&(i=n.readBits(1)),i){if(e===t){let c=I(n);s=e-(c+1)}else s=e-1;n.readBits(1),I(n);let o=r[s]??0;for(let c=0;c<=o;c++)n.readBits(1)||n.readBits(1);a=r[s]}else{let o=I(n),c=I(n);for(let u=0;u<o;u++)I(n),n.readBits(1);for(let u=0;u<c;u++)I(n),n.readBits(1);a=o+c}return a},hs=(n,e)=>{if(n.readBits(1)&&n.readBits(8)===255&&(n.readBits(16),n.readBits(16)),n.readBits(1)&&n.readBits(1),n.readBits(1)&&(n.readBits(3),n.readBits(1),n.readBits(1)&&(n.readBits(8),n.readBits(8),n.readBits(8))),n.readBits(1)&&(I(n),I(n)),n.readBits(1),n.readBits(1),n.readBits(1),n.readBits(1)&&(I(n),I(n),I(n),I(n)),n.readBits(1)&&(n.readBits(32),n.readBits(32),n.readBits(1)&&I(n),n.readBits(1)&&gs(n,!0,e)),n.readBits(1)){n.readBits(1),n.readBits(1),n.readBits(1);let t=I(n);return I(n),I(n),I(n),I(n),t}return 0},gs=(n,e,t)=>{let r=!1,a=!1,i=!1;e&&(r=n.readBits(1)===1,a=n.readBits(1)===1,(r||a)&&(i=n.readBits(1)===1,i&&(n.readBits(8),n.readBits(5),n.readBits(1),n.readBits(5)),n.readBits(4),n.readBits(4),i&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5)));for(let s=0;s<=t;s++){let o=n.readBits(1)===1,c=!0;o||(c=n.readBits(1)===1);let u=!1;c?I(n):u=n.readBits(1)===1;let d=1;u||(d=I(n)+1),r&&Gn(n,d,i),a&&Gn(n,d,i)}},Gn=(n,e,t)=>{for(let r=0;r<e;r++)I(n),I(n),t&&(I(n),I(n)),n.readBits(1)},Zn=n=>{let e=[];e.push(n.configurationVersion),e.push((n.generalProfileSpace&3)<<6|(n.generalTierFlag&1)<<5|n.generalProfileIdc&31),e.push(n.generalProfileCompatibilityFlags>>>24&255),e.push(n.generalProfileCompatibilityFlags>>>16&255),e.push(n.generalProfileCompatibilityFlags>>>8&255),e.push(n.generalProfileCompatibilityFlags&255),e.push(...n.generalConstraintIndicatorFlags),e.push(n.generalLevelIdc&255),e.push(240|n.minSpatialSegmentationIdc>>8&15),e.push(n.minSpatialSegmentationIdc&255),e.push(252|n.parallelismType&3),e.push(252|n.chromaFormatIdc&3),e.push(248|n.bitDepthLumaMinus8&7),e.push(248|n.bitDepthChromaMinus8&7),e.push(n.avgFrameRate>>8&255),e.push(n.avgFrameRate&255),e.push((n.constantFrameRate&3)<<6|(n.numTemporalLayers&7)<<3|(n.temporalIdNested&1)<<2|n.lengthSizeMinusOne&3),e.push(n.arrays.length&255);for(let t of n.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)},Or=n=>{let e=new q(n);if(e.readBits(2)!==2)return null;let r=e.readBits(1),i=(e.readBits(1)<<1)+r;if(i===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;i>=2&&(u=e.readBits(1)?12:10);let d=e.readBits(3),l=0,p=0;if(d!==7)if(p=e.readBits(1),i===1||i===3){let S=e.readBits(1),v=e.readBits(1);l=!S&&!v?3:S&&!v?2:1,e.skipBits(1)}else l=1;else l=3,p=1;let h=e.readBits(16),f=e.readBits(16),k=h+1,g=f+1,b=k*g,w=U(Ie).level;for(let T of Ie)if(b<=T.maxPictureSize){w=T.level;break}return{profile:i,level:w,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*Jn(n){let e=new q(n),t=()=>{let r=0;for(let a=0;a<8;a++){let i=e.readAlignedByte();if(r|=(i&127)<<a*7,!(i&128))break;if(a===7&&i&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),i=e.readBits(1);e.skipBits(1),a&&e.skipBits(8);let s;if(i){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:n.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}}var Mr=n=>{for(let{type:e,data:t}of Jn(n)){if(e!==1)continue;let r=new q(t),a=r.readBits(3),i=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 b=r.readBits(1);b&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));let w=r.readBits(5);for(let C=0;C<=w;C++){r.skipBits(12);let x=r.readBits(5);if(C===0&&(o=x),x>7){let T=r.readBits(1);C===0&&(c=T)}if(b&&r.readBits(1)){let S=u+1;r.skipBits(S),r.skipBits(S),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,k=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&&(k=r.readBits(2))),{profile:a,level:o,tier:c,bitDepth:l,monochrome:p,chromaSubsamplingX:h,chromaSubsamplingY:f,chromaSamplePosition:k}}return null},Ue=n=>{let e=ee(n),t=e.getUint8(9),r=e.getUint16(10,!0),a=e.getUint32(12,!0),i=e.getInt16(16,!0),s=e.getUint8(18),o=null;return s&&(o=n.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:a,outputGain:i,channelMappingFamily:s,channelMappingTable:o}},bs=[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],ea=n=>{let e=n[0]>>3;return{durationInSamples:bs[e]}},Br=n=>{if(n.length<7)throw new Error("Setup header is too short.");if(n[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...n.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=n.length,r=new Uint8Array(t);for(let l=0;l<t;l++)r[l]=n[t-1-l];let a=new q(r),i=0;for(;a.getBitsLeft()>97;)if(a.readBits(1)===1){i=a.pos;break}if(i===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(i);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}},ta=async(n,e)=>{switch(m(n.codec),n.codec){case"avc":{let t=await n.getDecoderConfig();m(t);let r;if(t.description){let o=(K(t.description)[4]&3)+1;r=Qn(e.data,o)}else r=Ot(e.data);return r.some(i=>Ar(i)===5)?"key":"delta"}case"hevc":{let t=await n.getDecoderConfig();m(t);let r;if(t.description){let o=(K(t.description)[21]&3)+1;r=Qn(e.data,o)}else r=Ot(e.data);return r.some(i=>{let s=Qe(i);return 16<=s&&s<=23})?"key":"delta"}case"vp8":return(e.data[0]&1)===0?"key":"delta";case"vp9":{let t=new q(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 Jn(e.data))if(r===1){let i=new q(a);i.skipBits(4),t=!!i.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let i=new q(a);return i.readBits(1)?null:i.readBits(2)===0?"key":"delta"}return null}default:Pe(n.codec),m(!1)}};var Mt=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 i of e.children)i&&this.writeBox(i);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}}},O=new Uint8Array(8),we=new DataView(O.buffer),L=n=>[(n%256+256)%256],R=n=>(we.setUint16(0,n,!1),[O[0],O[1]]),ia=n=>(we.setInt16(0,n,!1),[O[0],O[1]]),na=n=>(we.setUint32(0,n,!1),[O[1],O[2],O[3]]),P=n=>(we.setUint32(0,n,!1),[O[0],O[1],O[2],O[3]]),We=n=>(we.setInt32(0,n,!1),[O[0],O[1],O[2],O[3]]),qe=n=>(we.setUint32(0,Math.floor(n/2**32),!1),we.setUint32(4,n,!1),[O[0],O[1],O[2],O[3],O[4],O[5],O[6],O[7]]),aa=n=>(we.setInt16(0,2**8*n,!1),[O[0],O[1]]),_e=n=>(we.setInt32(0,2**16*n,!1),[O[0],O[1],O[2],O[3]]),Ai=n=>(we.setInt32(0,2**30*n,!1),[O[0],O[1],O[2],O[3]]),Ri=(n,e)=>{let t=[],r=n;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()},re=(n,e=!1)=>{let t=Array(n.length).fill(null).map((r,a)=>n.charCodeAt(a));return e&&t.push(0),t},Oi=n=>{let e=null;for(let t of n)(!e||t.timestamp>e.timestamp)&&(e=t);return e},sa=n=>{let e=n*(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]},oa=sa(0),ca=n=>[_e(n[0]),_e(n[1]),Ai(n[2]),_e(n[3]),_e(n[4]),Ai(n[5]),_e(n[6]),_e(n[7]),Ai(n[8])],F=(n,e,t)=>({type:n,contents:e&&new Uint8Array(e.flat(10)),children:t}),B=(n,e,t,r,a)=>F(n,[L(e),na(t),r??[]],a),da=n=>n.isQuickTime?F("ftyp",[re("qt  "),P(512),re("qt  ")]):n.fragmented?F("ftyp",[re("iso5"),P(512),re("iso5"),re("iso6"),re("mp41")]):F("ftyp",[re("isom"),P(512),re("isom"),n.holdsAvc?re("avc1"):[],re("mp41")]),Vr=n=>({type:"mdat",largeSize:n}),Bt=(n,e,t=!1)=>F("moov",void 0,[ks(e,n),...n.map(r=>ws(r,e)),t?to(n):null]),ks=(n,e)=>{let t=$(Math.max(0,...e.filter(s=>s.samples.length>0).map(s=>{let o=Oi(s.samples);return o.timestamp+o.duration})),Dr),r=Math.max(0,...e.map(s=>s.track.id))+1,a=!Le(n)||!Le(t),i=a?qe:P;return B("mvhd",+a,0,[i(n),i(n),P(Dr),i(t),_e(1),aa(1),Array(10).fill(0),ca(oa),Array(24).fill(0),P(r)])},ws=(n,e)=>F("trak",void 0,[Ts(n,e),ys(n,e)]),Ts=(n,e)=>{let t=Oi(n.samples),r=$(t?t.timestamp+t.duration:0,Dr),a=!Le(e)||!Le(r),i=a?qe:P,s;if(n.type==="video"){let o=n.track.metadata.rotation;s=sa(o??0)}else s=oa;return B("tkhd",+a,3,[i(e),i(e),P(n.track.id),P(0),i(r),Array(8).fill(0),R(0),R(n.track.id),aa(n.type==="audio"?1:0),R(0),ca(s),_e(n.type==="video"?n.info.width:0),_e(n.type==="video"?n.info.height:0)])},ys=(n,e)=>F("mdia",void 0,[Ss(n,e),vs(n),Ps(n)]),Ss=(n,e)=>{let t=Oi(n.samples),r=$(t?t.timestamp+t.duration:0,n.timescale),a=!Le(e)||!Le(r),i=a?qe:P,s=0;for(let o of n.track.metadata.languageCode??te)s<<=5,s+=o.charCodeAt(0)-96;return B("mdhd",+a,0,[i(e),i(e),P(n.timescale),i(r),R(s),R(0)])},Cs={video:"vide",audio:"soun",subtitle:"text"},xs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},vs=n=>B("hdlr",0,0,[re("mhlr"),re(Cs[n.type]),P(0),P(0),P(0),re(xs[n.type],!0)]),Ps=n=>F("minf",void 0,[As[n.type](),Rs(),Ms(n)]),Is=()=>B("vmhd",0,1,[R(0),R(0),R(0),R(0)]),Es=()=>B("smhd",0,0,[R(0),R(0)]),_s=()=>B("nmhd",0,0),As={video:Is,audio:Es,subtitle:_s},Rs=()=>F("dinf",void 0,[Fs()]),Fs=()=>B("dref",0,0,[P(1)],[Os()]),Os=()=>B("url ",0,1),Ms=n=>{let e=n.compositionTimeOffsetTable.length>1||n.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return F("stbl",void 0,[Bs(n),js(n),e?Js(n):null,e?eo(n):null,Xs(n),Ys(n),Zs(n),Gs(n)])},Bs=n=>{let e;if(n.type==="video")e=Ds(lo[n.track.source._codec],n);else if(n.type==="audio"){let t=ha(n.track.source._codec,n.muxer.isQuickTime);m(t),e=Ns(t,n)}else n.type==="subtitle"&&(e=qs(po[n.track.source._codec],n));return m(e),B("stsd",0,0,[P(1)],[e])},Ds=(n,e)=>F(n,[Array(6).fill(0),R(1),R(0),R(0),Array(12).fill(0),R(e.info.width),R(e.info.height),P(4718592),P(4718592),P(0),R(1),Array(32).fill(0),R(24),ia(65535)],[mo[e.track.source._codec](e),sr(e.info.decoderConfig.colorSpace)?Vs(e):null]),Vs=n=>F("colr",[re("nclx"),R(Ce[n.info.decoderConfig.colorSpace.primaries]),R(xe[n.info.decoderConfig.colorSpace.transfer]),R(ve[n.info.decoderConfig.colorSpace.matrix]),L((n.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Us=n=>n.info.decoderConfig&&F("avcC",[...K(n.info.decoderConfig.description)]),zs=n=>n.info.decoderConfig&&F("hvcC",[...K(n.info.decoderConfig.description)]),ra=n=>{if(!n.info.decoderConfig)return null;let e=n.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),a=Number(t[2]),i=Number(t[3]),s=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(i<<4)+(s<<1)+o,u=t[5]?Number(t[5]):e.colorSpace?.primaries?Ce[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?xe[e.colorSpace.transfer]:2,l=t[7]?Number(t[7]):e.colorSpace?.matrix?ve[e.colorSpace.matrix]:2;return B("vpcC",1,0,[L(r),L(a),L(c),L(u),L(d),L(l),R(0)])},Ws=n=>F("av1C",kr(n.info.decoderConfig.codec)),Ns=(n,e)=>{let t=0,r,a=16;if(z.includes(e.track.source._codec)){let i=e.track.source._codec,{sampleSize:s}=Z(i);a=8*s,a>16&&(t=1)}return t===0?r=[Array(6).fill(0),R(1),R(t),R(0),P(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),P(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),P(1),P(a/8),P(e.info.numberOfChannels*a/8),P(2)],F(n,r,[fo(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Fi=n=>{let e;switch(n.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: ${n.track.source._codec}`)}let t=[...L(e),...L(21),...na(0),...P(0),...P(0)];if(n.info.decoderConfig.description){let r=K(n.info.decoderConfig.description);t=[...t,...L(5),...Ri(r.byteLength),...r]}return t=[...R(1),...L(0),...L(4),...Ri(t.length),...t,...L(6),...L(1),...L(2)],t=[...L(3),...Ri(t.length),...t],B("esds",0,0,t)},ze=n=>F("wave",void 0,[Ls(n),Hs(n),F("\0\0\0\0")]),Ls=n=>F("frma",[re(ha(n.track.source._codec,n.muxer.isQuickTime))]),Hs=n=>{let{littleEndian:e}=Z(n.track.source._codec);return F("enda",[R(+e)])},Ks=n=>{let e=n.info.numberOfChannels,t=3840,r=n.info.sampleRate,a=0,i=0,s=new Uint8Array(0),o=n.info.decoderConfig?.description;if(o){m(o.byteLength>=18);let c=K(o),u=Ue(c);e=u.outputChannelCount,t=u.preSkip,r=u.inputSampleRate,a=u.outputGain,i=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return F("dOps",[L(0),L(e),R(t),P(r),ia(a),L(i),...s])},Qs=n=>{let e=n.info.decoderConfig?.description;m(e);let t=K(e);return B("dfLa",0,0,[...t.subarray(4)])},ke=n=>{let{littleEndian:e,sampleSize:t}=Z(n.track.source._codec),r=+e;return B("pcmC",0,0,[L(r),L(8*t)])},qs=(n,e)=>F(n,[Array(6).fill(0),R(1)],[ho[e.track.source._codec](e)]),$s=n=>F("vttC",[...fe.encode(n.info.config.description)]);var js=n=>B("stts",0,0,[P(n.timeToSampleTable.length),n.timeToSampleTable.map(e=>[P(e.sampleCount),P(e.sampleDelta)])]),Gs=n=>{if(n.samples.every(t=>t.type==="key"))return null;let e=[...n.samples.entries()].filter(([,t])=>t.type==="key");return B("stss",0,0,[P(e.length),e.map(([t])=>P(t+1))])},Xs=n=>B("stsc",0,0,[P(n.compactlyCodedChunkTable.length),n.compactlyCodedChunkTable.map(e=>[P(e.firstChunk),P(e.samplesPerChunk),P(1)])]),Ys=n=>{if(n.type==="audio"&&n.info.requiresPcmTransformation){let{sampleSize:e}=Z(n.track.source._codec);return B("stsz",0,0,[P(e*n.info.numberOfChannels),P(n.samples.reduce((t,r)=>t+$(r.duration,n.timescale),0))])}return B("stsz",0,0,[P(0),P(n.samples.length),n.samples.map(e=>P(e.size))])},Zs=n=>n.finalizedChunks.length>0&&U(n.finalizedChunks).offset>=2**32?B("co64",0,0,[P(n.finalizedChunks.length),n.finalizedChunks.map(e=>qe(e.offset))]):B("stco",0,0,[P(n.finalizedChunks.length),n.finalizedChunks.map(e=>P(e.offset))]),Js=n=>B("ctts",1,0,[P(n.compositionTimeOffsetTable.length),n.compositionTimeOffsetTable.map(e=>[P(e.sampleCount),We(e.sampleCompositionTimeOffset)])]),eo=n=>{let e=1/0,t=-1/0,r=1/0,a=-1/0;m(n.compositionTimeOffsetTable.length>0),m(n.samples.length>0);for(let s=0;s<n.compositionTimeOffsetTable.length;s++){let o=n.compositionTimeOffsetTable[s];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let s=0;s<n.samples.length;s++){let o=n.samples[s];r=Math.min(r,$(o.timestamp,n.timescale)),a=Math.max(a,$(o.timestamp+o.duration,n.timescale))}let i=Math.max(-e,0);return a>=2**31?null:B("cslg",0,0,[We(i),We(e),We(t),We(r),We(a)])},to=n=>F("mvex",void 0,n.map(ro)),ro=n=>B("trex",0,0,[P(n.track.id),P(1),P(0),P(0),P(0)]),Mi=(n,e)=>F("moof",void 0,[io(n),...e.map(no)]),io=n=>B("mfhd",0,0,[P(n)]),ua=n=>{let e=0,t=0,r=0,a=0,i=n.type==="delta";return t|=+i,i?e|=1:e|=2,e<<24|t<<16|r<<8|a},no=n=>F("traf",void 0,[ao(n),so(n),oo(n)]),ao=n=>{m(n.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=n.currentChunk.samples[1]??n.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:ua(t)};return B("tfhd",0,e,[P(n.track.id),P(r.duration),P(r.size),P(r.flags)])},so=n=>(m(n.currentChunk),B("tfdt",1,0,[qe($(n.currentChunk.startTimestamp,n.timescale))])),oo=n=>{m(n.currentChunk);let e=n.currentChunk.samples.map(k=>k.timescaleUnitsToNextSample),t=n.currentChunk.samples.map(k=>k.size),r=n.currentChunk.samples.map(ua),a=n.currentChunk.samples.map(k=>$(k.timestamp-k.decodeTimestamp,n.timescale)),i=new Set(e),s=new Set(t),o=new Set(r),c=new Set(a),u=o.size===2&&r[0]!==r[1],d=i.size>1,l=s.size>1,p=!u&&o.size>1,h=c.size>1||[...c].some(k=>k!==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,[P(n.currentChunk.samples.length),P(n.currentChunk.offset-n.currentChunk.moofOffset||0),u?P(r[0]):[],n.currentChunk.samples.map((k,g)=>[d?P(e[g]):[],l?P(t[g]):[],p?P(r[g]):[],h?We(a[g]):[]])])},la=n=>F("mfra",void 0,[...n.map(co),uo()]),co=(n,e)=>B("tfra",1,0,[P(n.track.id),P(63),P(n.finalizedChunks.length),n.finalizedChunks.map(r=>[qe($(r.samples[0].timestamp,n.timescale)),qe(r.moofOffset),P(e+1),P(1),P(1)])]),uo=()=>B("mfro",0,0,[P(0)]),ma=()=>F("vtte"),fa=(n,e,t,r,a)=>F("vttc",void 0,[a!==null?F("vsid",[We(a)]):null,t!==null?F("iden",[...fe.encode(t)]):null,e!==null?F("ctim",[...fe.encode(_r(e))]):null,r!==null?F("sttg",[...fe.encode(r)]):null,F("payl",[...fe.encode(n)])]),pa=n=>F("vtta",[...fe.encode(n)]),lo={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},mo={avc:Us,hevc:zs,vp8:ra,vp9:ra,av1:Ws},ha=(n,e)=>{switch(n){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(n){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(n){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"}},fo=(n,e)=>{switch(n){case"aac":return Fi;case"mp3":return Fi;case"opus":return Ks;case"vorbis":return Fi;case"flac":return Qs}if(e)switch(n){case"pcm-s24":return ze;case"pcm-s24be":return ze;case"pcm-s32":return ze;case"pcm-s32be":return ze;case"pcm-f32":return ze;case"pcm-f32be":return ze;case"pcm-f64":return ze;case"pcm-f64be":return ze}else switch(n){case"pcm-s16":return ke;case"pcm-s16be":return ke;case"pcm-s24":return ke;case"pcm-s24be":return ke;case"pcm-s32":return ke;case"pcm-s32be":return ke;case"pcm-f32":return ke;case"pcm-f32be":return ke;case"pcm-f64":return ke;case"pcm-f64be":return ke}return null},po={webvtt:"wvtt"},ho={webvtt:$s};var de=class{constructor(e){this.mutex=new ie;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 Ur=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 i=new Uint8Array(a);i.set(this.trackedWrites,0),this.trackedWrites=i}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}},Bi=2**16,Di=2**32,ut=class extends Ur{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(Bi,{maxByteLength:Di})}catch{this.buffer=new ArrayBuffer(Bi),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Bi);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>Di)throw new Error(`ArrayBuffer exceeded maximum size of ${Di} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let a=new ArrayBuffer(r),i=new Uint8Array(a);i.set(this.bytes,0),this.buffer=a,this.bytes=i}}}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)}},go=2**24,bo=2,zr=class extends Ur{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??go}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,i)=>a.start-i.start);t.push({start:r[0].start,size:r[0].data.byteLength});for(let a=1;a<r.length;a++){let i=t[t.length-1],s=r[a];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):t.push({start:s.start,size:s.data.byteLength})}for(let a of t){a.data=new Uint8Array(a.size);for(let i of this.sections)a.start<=i.start&&i.start<a.start+a.size&&a.data.set(i.data,i.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 i=this.chunks[a],s=r-i.start,o=t.subarray(0,Math.min(this.chunkSize-s,t.byteLength));i.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this.insertSectionIntoChunk(i,c),i.written[0].start===0&&i.written[0].end===this.chunkSize&&(i.shouldFlush=!0),this.chunks.length>bo){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,i=t.written.length-1,s=-1;for(;a<=i;){let o=Math.floor(a+(i-a+1)/2);t.written[o].start<=r.start?(a=o+1,s=o):i=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((i,s)=>i.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 i of a.written){let s=a.start+i.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data.subarray(i.start,i.end),position:s}),this.lastFlushEnd=a.start+i.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 $e=class{constructor(){this._output=null}},Dt=class extends $e{constructor(){super(...arguments);this.buffer=null}_createWriter(){return new ut(this)}},Vi=class extends $e{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 zr(this)}};var Wr=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isQuickTime?"quicktime":"mp4");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var lt=8,Ne=16,je=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 i=0;i<e;i++)a+=String.fromCharCode(t.getUint8(r+i));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 Dr=1e3,ko=2082844800,$=(n,e,t=!0)=>{let r=n*e;return t?Math.round(r):r},Nr=class extends de{constructor(t,r){super(t);this.auxTarget=new Dt;this.auxWriter=this.auxTarget._createWriter();this.auxBoxWriter=new Mt(this.auxWriter);this.mdat=null;this.trackDatas=[];this.allTracksKnown=W();this.creationTime=Math.floor(Date.now()/1e3)+ko;this.finalizedChunks=[];this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.format=r,this.writer=t._writer,this.boxWriter=new Mt(this.writer),this.isQuickTime=r instanceof mt;let a=this.writer instanceof ut?"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(da({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:a,start:i}=this.writer.stopTrackingWrites();this.format._options.onFtyp(a,i)}this.fastStart==="in-memory"?this.mdat=Vr(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Vr(!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 Wr({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 i=this.trackDatas.find(d=>d.track===t);if(i)return i;Sr(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=Rr(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=Yn(d),o=!0}else if(t.source._codec==="hevc"&&!s.description){let d=Fr(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=Zn(d),o=!0}let c=Bn(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;Ve(r),m(r),m(r.decoderConfig);let i={muxer:this,track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&z.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(i),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Cr(r),m(r),m(r.config);let i={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(i),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(t,r,a){let i=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,r,a),o=r.data;if(s.info.requiresAnnexBTransformation){let d=Xn(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{i()}}async addEncodedAudioPacket(t,r,a){let i=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{i()}}async maybePadWithSilence(t,r){let a=U(t.samples),i=a?a.timestamp+a.duration:0,s=r-i,o=$(s,t.timescale);if(o>0){let{sampleSize:c,silentValue:u}=Z(t.info.decoderConfig.codec),d=o*t.info.numberOfChannels,l=new Uint8Array(c*d).fill(u),p=this.createSampleForTrack(t,new Uint8Array(l.buffer),i,s,"key");await this.registerSample(t,p)}}async addSubtitleCue(t,r,a){let i=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{i()}}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 i=[...a].sort((d,l)=>d-l),s=i[0],o=i[1]??s;if(r<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);let d=ma();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;dt.lastIndex=0;let p=dt.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=pa(l.notes);this.auxBoxWriter.writeBox(g)}let k=fa(l.text,p?s:null,l.identifier??null,l.settings??null,f??null);this.auxBoxWriter.writeBox(k),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,i,s){return{timestamp:a,decodeTimestamp:a,duration:i,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:$(i,t.timescale)}}processTimestamps(t,r){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){let i=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){let o=t.timestampProcessingQueue[s],c=$(o.duration,t.timescale);i+=c}if(t.timeToSampleTable.length===0)t.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{let s=U(t.timeToSampleTable);s.sampleCount+=i}t.timestampProcessingQueue.length=0;return}let a=t.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);for(let i=0;i<t.timestampProcessingQueue.length;i++){let s=t.timestampProcessingQueue[i];s.decodeTimestamp=a[i],!this.isFragmented&&t.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=$(s.timestamp-s.decodeTimestamp,t.timescale),c=$(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){m(t.lastSample);let u=$(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=U(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=U(t.compositionTimeOffsetTable);m(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=$(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 i=$(r.timestamp,t.timescale,!1),s=Math.round(i-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 i=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});i>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(a=!0,await this.finalizeFragment())}else a=i>=.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,i)=>a+$(i.duration,t.timescale),0)),(t.compactlyCodedChunkTable.length===0||U(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 i=r.sampleQueue.shift();await this.addSampleToTrack(r,i)}}async finalizeFragment(t=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let f=Bt(this.trackDatas,this.creationTime,!0);if(this.boxWriter.writeBox(f),this.format._options.onMoov){let{data:k,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoov(k,g)}}let a=this.trackDatas.filter(f=>f.currentChunk),i=Mi(r,a),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(i),c=o+lt,u=1/0;for(let f of a){f.currentChunk.offset=c,f.currentChunk.moofOffset=s;for(let k of f.currentChunk.samples)c+=k.size;u=Math.min(u,f.currentChunk.startTimestamp)}let d=c-o,l=d>=2**32;if(l)for(let f of a)f.currentChunk.offset+=Ne-lt;this.format._options.onMoof&&this.writer.startTrackingWrites();let p=Mi(r,a);if(this.boxWriter.writeBox(p),this.format._options.onMoof){let{data:f,start:k}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,k,u)}m(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let h=Vr(l);h.size=d,this.boxWriter.writeBox(h),this.writer.seek(o+(l?Ne:lt));for(let f of a)for(let k of f.currentChunk.samples)this.writer.write(k.data),k.data=null;if(this.format._options.onMdat){let{data:f,start:k}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,k)}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(i=>i.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 i=0;i<2;i++){let s=Bt(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=Bt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(a),this.format._options.onMoov){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let i of this.finalizedChunks)for(let s of i.samples)m(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented){let r=this.writer.getPos(),a=la(this.trackDatas);this.boxWriter.writeBox(a);let i=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}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 i=Bt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}t()}};var ft=class{constructor(e){this.value=e}},pt=class{constructor(e){this.value=e}},Vt=class{constructor(e){this.value=e}};var wo=[440786851,408125543],To=[17138,17139,290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],Hr=[...wo,...To],ga=n=>n<256?1:n<65536?2:n<1<<24?3:n<2**32?4:n<2**40?5:6,ba=n=>n>=-64&&n<64?1:n>=-8192&&n<8192?2:n>=-(1<<20)&&n<1<<20?3:n>=-(1<<27)&&n<1<<27?4:n>=-(2**34)&&n<2**34?5:6,yo=n=>{if(n<127)return 1;if(n<16383)return 2;if(n<(1<<21)-1)return 3;if(n<(1<<28)-1)return 4;if(n<2**35-1)return 5;if(n<2**42-1)return 6;throw new Error("EBML varint size not supported "+n)},Lr=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=ga(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=ba(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=yo(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))}writeAsciiString(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 i=this.writer.getPos()-a,s=this.writer.getPos();this.writer.seek(t),this.writeVarInt(i,r),this.writer.seek(s)}}else if(typeof e.data=="number"){let t=e.size??ga(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(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 ft)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof pt)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Vt){let t=e.size??ba(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}}}},So=8,Ae=2,ht=2*So,Ge=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);if(r===0)return null;let a=1,i=128;for(;(r&i)===0;)a++,i>>=1;return a}readVarInt(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1),r=e.getUint8(t);if(r===0)return null;let a=1,i=128;for(;(r&i)===0;)a++,i>>=1;let{view:s,offset:o}=this.reader.getViewAndOffset(this.pos,this.pos+a),c=r&i-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 i=0;i<e;i++)a*=256,a+=t.getUint8(r+i);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}readAsciiString(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a=0;for(;a<e&&t.getUint8(r+a)!==0;)a+=1;return String.fromCharCode(...new Uint8Array(t.buffer,r,a))}readElementId(){let e=this.readVarIntSize();return e===null?null: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();if(e===null)return null;let t=this.readElementSize();return{id:e,size:t}}async searchForNextElementId(e,t){let a=new Set(e);for(;this.pos<=t-Ae;){this.reader.rangeIsLoaded(this.pos,Math.min(this.pos+ht,t))||await this.reader.loadRange(this.pos,Math.min(this.pos+1048576,t));let i=this.pos,s=this.readElementHeader();if(!s)break;if(a.has(s.id))return i;Xe(s.size),this.pos+=s.size}return null}},se={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"},Ui=(n,e)=>{if(e>=n.length)throw new Error("Offset out of bounds.");let t=n[e],r=1,a=128;for(;(t&a)===0&&r<8;)r++,a>>=1;if(e+r>n.length)throw new Error("VarInt extends beyond data bounds.");let i=t&a-1;for(let s=1;s<r;s++)i*=256,i+=n[e+s];return{value:i,width:r}};function Xe(n){if(n===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Kr=n=>{let t=(n.hasVideo?"video/":n.hasAudio?"audio/":"application/")+(n.isWebM?"webm":"x-matroska");if(n.codecStrings.length>0){let r=[...new Set(n.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var Co=-(2**15),xo=2**15-1,ka="https://github.com/Vanilagy/mediabunny",wa=6,Ta=5,vo={video:1,audio:2,subtitle:17},Qr=class extends de{constructor(t,r){super(t);this.trackDatas=[];this.allTracksKnown=W();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 Lr(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 gt?"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]),i={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=i}createSegmentInfo(){let t={id:17545,data:new pt(0)};this.segmentDuration=t;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:ka},{id:22337,data:ka},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=se[r.track.source._codec];m(a);let i=0;if(r.type==="audio"&&r.track.source._codec==="opus"){i=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=K(s),c=Ue(o);i=Math.round(1e9*(c.preSkip/ct))}}t.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:vo[r.type]},{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??te},{id:134,data:a},{id:22186,data:0},{id:22203,data:i},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,i=[t.info.decoderConfig.description?{id:25506,data:K(t.info.decoderConfig.description)}:null,r?{id:2352003,data:1e9/r}:null],s=a?De(-a):0,o=t.info.decoderConfig.colorSpace,c={id:224,data:[{id:176,data:t.info.width},{id:186,data:t.info.height},sr(o)?{id:21936,data:[{id:21937,data:ve[o.matrix]},{id:21946,data:xe[o.transfer]},{id:21947,data:Ce[o.primaries]},{id:21945,data:o.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new ft((s+180)%360-180)}]}:null]};return i.push(c),i}audioSpecificTrackInfo(t){let r=z.includes(t.track.source._codec)?Z(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:25506,data:K(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new ft(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:25506,data:fe.encode(t.info.config.description)}]}createSegment(){let t={id:408125543,size:this.format._options.appendOnly?-1:wa,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 Kr({isWebM:this.format instanceof gt,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;Sr(r),m(r),m(r.decoderConfig),m(r.decoderConfig.codedWidth!==void 0),m(r.decoderConfig.codedHeight!==void 0);let i={track:t,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return t.source._codec==="vp9"?i.info.decoderConfig={...i.info.decoderConfig,description:new Uint8Array(Nn(i.info.decoderConfig.codec))}:t.source._codec==="av1"&&(i.info.decoderConfig={...i.info.decoderConfig,description:new Uint8Array(kr(i.info.decoderConfig.codec))}),this.trackDatas.push(i),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Ve(r),m(r),m(r.decoderConfig);let i={track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Cr(r),m(r),m(r.config);let i={track:t,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(i),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(t,r,a){let i=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=_t(c,1/t.metadata.frameRate),u=_t(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{i()}}async addEncodedAudioPacket(t,r,a){let i=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{i()}}async addSubtitleCue(t,r,a){let i=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);dt.lastIndex=0,c=c.replace(dt,h=>{let k=Er(h.slice(1,-1))-u;return`<${_r(k)}>`});let d=fe.encode(c),l=`${r.settings??""}
${r.identifier??""}
${r.notes??""}`,p=this.createInternalChunk(d,o,r.duration,"key",l.trim()?fe.encode(l):null);s.chunkQueue.push(p),await this.interleaveChunks()}finally{i()}}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 i=r.chunkQueue.shift();this.writeBlock(r,i)}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 q(r.data);a.skipBits(2);let i=a.readBits(1),o=(a.readBits(1)<<1)+i;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];In(r.data,a.pos,a.pos+3,l)}createInternalChunk(t,r,a,i,s=null){return{data:t,type:i,timestamp:r,duration:a,additions:s}}writeBlock(t,r){this.segment||(this.createTracks(),this.createSegment());let a=Math.round(1e3*r.timestamp),i=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=i&&a>this.currentClusterMaxMsTimestamp&&l>=1e3*(this.format._options.minimumClusterDuration??1)||l>xo}s&&this.createNewCluster(a);let o=a-this.currentClusterStartMsTimestamp;if(o<Co)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 Vt(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:Ta,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 i=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(i,Ta),this.writer.seek(s)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);let{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(i,s,this.currentClusterStartMsTimestamp/1e3)}let t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[i,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(i);let a=[...r.entries()].sort((i,s)=>i[0]-s[0]);for(let[i,s]of a)m(this.cues),this.cues.data.push({id:187,data:[{id:179,data:i},...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,wa),this.segmentDuration.data=new pt(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 zi={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]},Wi={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]},Ni={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},bt=1483304551,qr=1231971951,$r=(n,e,t,r)=>Math.floor(n===3?(12*e/t+r)*4:144*e/t+r),kt=(n,e)=>n===3?e===3?21:36:e===3?13:21,jr=(n,e)=>{let t=e.pos,r=n>>>24,a=n>>>16&255,i=n>>>8&255,s=n&255;if(r!==255&&a!==255&&i!==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=i>>4&15,d=i>>2&3,l=i>>1&1,p=s>>6&3,h=s>>4&3,f=s>>3&1,k=s>>2&1,g=s&3,b=o===3?zi[c]?.[u]:Wi[c]?.[u];if(!b||b===-1)return null;let w=b*1e3,C=Ni[o]?.[d];if(!C||C===-1)return null;let x=$r(c,w,C,l);if(e.fileSize!==null&&e.fileSize-t<x)return null;let y;return o===3?y=c===3?384:1152:c===3?y=384:c===2?y=1152:y=576,{startPos:t,totalSize:x,mpegVersionId:o,layer:c,bitrate:w,frequencyIndex:d,sampleRate:C,channel:p,modeExtension:h,copyright:f,original:k,emphasis:g,audioSamplesInFrame:y}};var Gr=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?zi:Wi)?.[e.layer];if(!s)throw new Error("Invalid MPEG version and layer combination.");let o=Ni[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=>$r(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=kt(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(bt);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 k=$r(e.layer,1e3*s[d],o,c);this.writer.seek(t+k)}};var Xr=class extends de{constructor(t,r){super(t);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.format=r,this.writer=t._writer,this.mp3Writer=new Gr(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{let i=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&i){let s=ee(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=jr(o,{pos:0,fileSize:null});if(!c)throw new Error("Invalid MP3 header in sample.");let u=kt(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let d=s.getUint32(u,!1);if(d===bt||d===qr)return}this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null},this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(t,r.timestamp,r.type==="key"),this.writer.write(r.data),this.frameCount++,await this.writer.flush(),i&&this.framePositions.push(this.writer.getPos())}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 i=0;i<100;i++){let s=Math.floor(this.framePositions.length*(i/100));m(s!==-1&&s<this.framePositions.length);let o=this.framePositions[s];a[i]=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:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(i,s)}this.writer.seek(r),t()}};var Ut=1399285583,Po=79764919,Sa=new Uint32Array(256);for(let n=0;n<256;n++){let e=n<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Po:e<<1;Sa[n]=e>>>0&4294967295}var Yr=n=>{let e=ee(n),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let a=0;a<n.length;a++){let i=n[a];r=(r<<8^Sa[r>>>24^i])>>>0}return e.setUint32(22,t,!0),r},Zr=(n,e,t)=>{let r=0,a=null;if(n.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);let i=e.vorbisInfo.modeBlockflags.length,o=(1<<Mn(i-1))-1<<1,c=(n[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=n[0]&l?1:0;u=e.vorbisInfo.blocksizes[p]}r=u!==null?u+a>>2:0}else e.codec==="opus"&&(r=ea(n).durationInSamples);return{durationInSamples:r,vorbisBlockSize:a}},Jr=n=>{let e="audio/ogg";if(n.codecStrings){let t=[...new Set(n.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var Tt=27,Ye=282,ei=Ye+255*255,wt=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 i=0;i<e;i++)a+=String.fromCharCode(t.getUint8(r+i));return a}readPageHeader(){let e=this.pos;if(this.readU32()!==Ut)return null;this.pos+=1;let r=this.readU8(),a=this.readI64(),i=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:i,sequenceNumber:s,checksum:o,lacingValues:u}}findNextPageHeader(e){for(;this.pos<e-3;){let t=this.readU32(),r=t&255,a=t>>>8&255,i=t>>>16&255,s=t>>>24&255,o=79;if(!(r!==o&&a!==o&&i!==o&&s!==o)){if(this.pos-=4,t===Ut)return!0;this.pos+=1}}return!1}};var Io=8192,ti=class extends de{constructor(t,r){super(t);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=W();this.pageBytes=new Uint8Array(ei);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,Jr({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 i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===i));m(t.source._codec==="vorbis"||t.source._codec==="opus"),Ve(r),m(r),m(r.decoderConfig);let s={track:t,serialNumber:i,internalSampleRate:t.source._codec==="opus"?ct: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=K(r.decoderConfig.description);if(a[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let i=1,s=()=>{let k=0;for(;;){let g=a[i++];if(g===void 0)throw new TypeError("Vorbis decoder description is too short.");if(k+=g,g<255)return k}},o=s(),c=s();if(a.length-i<=0)throw new TypeError("Vorbis decoder description is too short.");let d=a.subarray(i,i+=o),l=a.subarray(i,i+=c),p=a.subarray(i);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=ee(d).getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Br(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=K(r.decoderConfig.description),i=new Uint8Array(16),s=new DataView(i.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:i,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),t.codecInfo.opusInfo={preSkip:Ue(a).preSkip}}}async addEncodedAudioPacket(t,r,a){let i=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}=Zr(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{i()}}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 i=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,i,s)}t||await this.writer.flush()}writePacket(t,r,a){let i=r.data.length,s=0,o=0;for(;;){t.currentLacingValues.length===0&&s>0&&(t.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,i);t.currentLacingValues.push(u),t.currentPageSize++,o+=u;let d=i<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;i-=255}let c=r.data.subarray(s);t.currentPageData.push(c),t.currentPageSize+=c.length,t.currentGranulePosition=r.endGranulePosition,(t.currentPageSize>=Io||r.forcePageFlush)&&this.writePage(t,a)}writePage(t,r){this.pageView.setUint32(0,Ut,!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 i=t.currentLacingValues.every(u=>u===255)?-1:t.currentGranulePosition;On(this.pageView,6,i,!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=Yr(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 ue=class{constructor(e){this.input=e}};var ne=new Uint8Array(0),D=class n{constructor(e,t,r,a,i=-1,s){this.data=e;this.type=t;this.timestamp=r;this.duration=a;this.sequenceNumber=i;if(e===ne&&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(i))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===ne}get microsecondTimestamp(){return Math.trunc(be*this.timestamp)}get microsecondDuration(){return Math.trunc(be*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 n(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 n(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var Ca=n=>{let r=n,a=4096,i=0,s=12,o=0;for(r<0&&(r=-r,i=128),r+=33,r>8191&&(r=8191);(r&a)!==a&&s>=5;)a>>=1,s--;return o=r>>s-4&15,~(i|s-5<<4|o)&255},xa=n=>{let t=0,r=0,a=~n;a&128&&(a&=-129,t=-1),r=((a&240)>>4)+5;let i=(1<<r|(a&15)<<r-4|1<<r-5)-33;return t===0?i:-i},va=n=>{let t=2048,r=0,a=11,i=0,s=n;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&a>=5;)t>>=1,a--;return i=s>>(a===4?1:a-4)&15,(r|a-4<<4|i)^85},Pa=n=>{let e=0,t=0,r=n^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 oe=class n{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=K(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 n(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*be),duration:Math.trunc((t.duration??0)*be)}),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 i=new OffscreenCanvas(r,a),s=i.getContext("2d",{alpha:!1,willReadFrequently:!0});m(s),s.drawImage(e,0,0),this._data=i,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(be*this.timestamp)}get microsecondDuration(){return Math.trunc(be*this.duration)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),zt(this._data)?new n(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new n(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new n(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(zt(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),zt(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!it(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),zt(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)K(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);K(e).set(a.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),zt(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,i,s,o,c,u){let d=0,l=0,p=this.displayWidth,h=this.displayHeight,f=0,k=0,g=this.displayWidth,b=this.displayHeight;if(s!==void 0?(d=t,l=r,p=a,h=i,f=s,k=o,c!==void 0?(g=c,b=u):(g=p,b=h)):(f=t,k=r,a!==void 0&&(g=a,b=i)),!(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(k))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(b)||b<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 w=this.toCanvasImageSource();e.save();let C=f+g/2,x=k+b/2;e.translate(C,x),e.rotate(this.rotation*Math.PI/180);let y=this.rotation%180===0?1:g/b;e.scale(1/y,y),e.drawImage(w,d,l,p,h,-g/2,-b/2,g,b),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}},zt=n=>typeof VideoFrame<"u"&&n instanceof VideoFrame,Li=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),ae=class n{constructor(e){this._closed=!1;if(Nt(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(!Li.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/(Wt(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*Wt(this.format);if(r.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}get microsecondTimestamp(){return Math.trunc(be*this.timestamp)}get microsecondDuration(){return Math.trunc(be*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&&!Li.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 i=Wt(t),s=ri(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)*i}copyTo(e,t){if(!it(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&&!Li.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:i,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=i!==void 0?i:c-d;if(l>c-d)throw new RangeError("frameCount out of range");let p=Wt(o),h=ri(o);if(h&&r>=u)throw new RangeError("planeIndex out of range");if(!h&&r!==0)throw new RangeError("planeIndex out of range");let k=(h?l:l*u)*p;if(e.byteLength<k)throw new RangeError("Destination buffer is too small");let g=ee(e),b=_o(o);if(Nt(this._data))if(h)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});else{let w=new ArrayBuffer(l*4),C=new Float32Array(w);this._data.copyTo(C,{planeIndex:r,frameOffset:d,frameCount:l,format:"f32-planar"});let x=new DataView(w);for(let y=0;y<l;y++){let T=y*p,S=x.getFloat32(y*4,!0);b(g,T,S)}}else{let w=u,C=new Float32Array(l);for(let x=0;x<w;x++){this._data.copyTo(C,{planeIndex:x,frameOffset:d,frameCount:l,format:"f32-planar"});for(let y=0;y<l;y++){let S=(y*w+x)*p;b(g,S,C[y])}}}else{let w=this._data,C=new DataView(w.buffer,w.byteOffset,w.byteLength),x=this.format,y=Eo(x),T=Wt(x),S=ri(x);for(let v=0;v<l;v++)if(h){let E=v*p,A;S?A=(r*c+(v+d))*T:A=((v+d)*u+r)*T;let _=y(C,A);b(g,E,_)}else for(let E=0;E<u;E++){let _=(v*u+E)*p,M;S?M=(E*c+(v+d))*T:M=((v+d)*u+E)*T;let N=y(C,M);b(g,_,N)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Nt(this._data)){let e=new n(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new n({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Nt(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Nt(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ri(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}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=64*1024*1024,a=e.numberOfChannels,i=e.sampleRate,s=e.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++)e.copyFromChannel(p.subarray(f*l,f*l+l),f,c);let h=new n({format:"f32-planar",sampleRate:i,numberOfFrames:l,numberOfChannels:a,timestamp:t+c/i,data:p});d.push(h),c+=l,u-=l}return d}},Wt=n=>{switch(n){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")}},ri=n=>{switch(n){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Eo=n=>{switch(n){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)}},_o=n=>{switch(n){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,j((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,j(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,j(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},Nt=n=>typeof AudioData<"u"&&n instanceof AudioData;var yt=n=>{if(!n||typeof n!="object")throw new TypeError("options must be an object.");if(n.metadataOnly!==void 0&&typeof n.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(n.verifyKeyPackets!==void 0&&typeof n.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(n.verifyKeyPackets&&n.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Re=n=>{if(typeof n!="number"||Number.isNaN(n))throw new TypeError("timestamp must be a number.")},Hi=(n,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let a=await n.determinePacketType(r);return a&&(r.type=a),r}):e,Te=class{constructor(e){if(!(e instanceof Je))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return yt(e),Hi(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return Re(e),yt(t),Hi(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 yt(t),Hi(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Re(e),yt(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(yt(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.");yt(r);let a=[],{promise:i,resolve:s}=W(),{promise:o,resolve:c}=W(),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}=W()),await o;continue}a.push(f),s(),{promise:i,resolve:s}=W(),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(),k=performance.now();for(p.push(k);p.length>0&&k-p[0]>=1e3;)p.shift();return c(),{value:f,done:!1}}else{if(u)return{value:void 0,done:!0};await i}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},Lt=class{constructor(e,t){this.onSample=e;this.onError=t}},Ht=class{mediaSamplesInRange(e=0,t=1/0){Re(e),Re(t);let r=[],a=!1,i=null,{promise:s,resolve:o}=W(),{promise:c,resolve:u}=W(),d=!1,l=!1,p=!1,h=null;return(async()=>{let f=new Error,k=await this._createDecoder(y=>{if(u(),y.timestamp>=t&&(l=!0),l){y.close();return}i&&(y.timestamp>e?(r.push(i),a=!0):i.close()),y.timestamp>=e&&(r.push(y),a=!0),i=a?null:y,r.length>0&&(o(),{promise:s,resolve:o}=W())},y=>{h||(y.stack=f.stack,h=y,o())}),g=this._createPacketSink(),b=await g.getKeyPacket(e,{verifyKeyPackets:!0})??await g.getFirstPacket();if(!b)return;let w=b,C;if(t<1/0){let y=await g.getPacket(t),T=y?y.type==="key"&&y.timestamp===t?y:await g.getNextKeyPacket(y,{verifyKeyPackets:!0}):null;T&&(C=T)}let x=g.packets(b,C);for(await x.next();w&&!l;){let y=Ia(r.length);if(r.length+k.getDecodeQueueSize()>y){({promise:c,resolve:u}=W()),await c;continue}k.decode(w);let T=await x.next();if(T.done)break;w=T.value}await x.return(),p||await k.flush(),k.close(),!a&&i&&r.push(i),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(),i?.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){An(e);let t=_n(e),r=[],a=[],{promise:i,resolve:s}=W(),{promise:o,resolve:c}=W(),u=!1,d=!1,l=null,p=h=>{a.push(h),s(),{promise:i,resolve:s}=W()};return(async()=>{let h=new Error,f=await this._createDecoder(y=>{if(c(),d){y.close();return}let T=0;for(;r.length>0&&y.timestamp-r[0]>-1e-10;)T++,r.shift();if(T>0)for(let S=0;S<T;S++)p(S<T-1?y.clone():y);else y.close()},y=>{l||(y.stack=h.stack,l=y,s())}),k=this._createPacketSink(),g=null,b=null,w=-1,C=async()=>{m(b);let y=b;for(f.decode(y);y.sequenceNumber<w;){let T=Ia(a.length);for(;a.length+f.getDecodeQueueSize()>T&&!d;)({promise:o,resolve:c}=W()),await o;if(d)break;let S=await k.getNextPacket(y);m(S),y=S,f.decode(S)}w=-1},x=async()=>{await f.flush();for(let y=0;y<r.length;y++)p(null);r.length=0};for await(let y of t){if(Re(y),d)break;let T=await k.getPacket(y),S=T&&await k.getKeyPacket(y,{verifyKeyPackets:!0});if(!S){w!==-1&&(await C(),await x()),p(null),g=null;continue}g&&(S.sequenceNumber!==b.sequenceNumber||T.timestamp<g.timestamp)&&(await C(),await x()),r.push(T.timestamp),w=Math.max(T.sequenceNumber,w),g=T,b=S}d||(w!==-1&&await C(),await x()),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 i;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}}}},Ia=n=>n===0?40:8,Ki=class extends Lt{constructor(t,r,a,i,s,o){super(t,r);this.rotation=s;this.timeResolution=o;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Be;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];let c=st.find(u=>u.supports(a,i));if(c)this.customDecoder=new c,this.customDecoder.codec=a,this.customDecoder.config=i,this.customDecoder.onSample=u=>{if(!(u instanceof oe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(u)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let u=d=>{if(dr()){if(this.sampleQueue.length>0&&d.timestamp>=U(this.sampleQueue).timestamp){for(let l of this.sampleQueue)this.finalizeAndEmitSample(l);this.sampleQueue.length=0}pe(this.sampleQueue,d,l=>l.timestamp)}else{let l=this.inputTimestamps.shift();m(l!==void 0),d.setTimestamp(l),this.finalizeAndEmitSample(d)}};this.decoder=new VideoDecoder({output:d=>u(new oe(d)),error:r}),this.decoder.configure(i)}}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),dr()||pe(this.inputTimestamps,t.timestamp,r=>r),this.decoder.decode(t.toEncodedVideoChunk()))}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await this.decoder.flush()),dr()){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}},St=class extends Ht{constructor(e){if(!(e instanceof he))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,i=await this._videoTrack.getDecoderConfig(),s=this._videoTrack.timeResolution;return m(r&&i),new Ki(e,t,r,i,a,s)}_createPacketSink(){return new Te(this._videoTrack)}async getSample(e){Re(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)}},Kt=class{constructor(e,t={}){this._nextCanvasIndex=0;if(!(e instanceof he))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,i]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=a/i;t.width!==void 0&&t.height===void 0?(a=t.width,i=Math.round(a/s)):t.width===void 0&&t.height!==void 0?(i=t.height,a=Math.round(i*s)):t.width!==void 0&&t.height!==void 0&&(a=t.width,i=t.height),this._videoTrack=e,this._width=a,this._height=i,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new St(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,i,s,o;if(this._fit==="fill")a=0,i=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,i=(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,i,s,o);let u={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),u}async getCanvas(e){Re(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return Et(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return Et(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},Qi=class extends Lt{constructor(t,r,a,i){super(t,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Be;this.customDecoderQueueSize=0;let s=c=>{if(c.numberOfFrames===0){c.close();return}let u=i.sampleRate;c.setTimestamp(Math.round(c.timestamp*u)/u),t(c)},o=ot.find(c=>c.supports(a,i));o?(this.customDecoder=new o,this.customDecoder.codec=a,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof ae))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 ae(c)),error:r}),this.decoder.configure(i))}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())}},qi=class extends Lt{constructor(t,r,a){super(t,r);this.decoderConfig=a;this.currentTimestamp=null;m(z.includes(a.codec)),this.codec=a.codec;let{dataType:i,sampleSize:s,littleEndian:o}=Z(this.codec);switch(this.inputSampleSize=s,s){case 1:i==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:i==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):i==="ulaw"?this.readInputValue=(c,u)=>xa(c.getUint8(u)):i==="alaw"?this.readInputValue=(c,u)=>Pa(c.getUint8(u)):m(!1);break;case 2:i==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:i==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):m(!1);break;case 3:i==="unsigned"?this.readInputValue=(c,u)=>xi(c,u,o)-2**23:i==="signed"?this.readInputValue=(c,u)=>Rn(c,u,o):m(!1);break;case 4:i==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:i==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):i==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):m(!1);break;case 8:i==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):m(!1);break;default:Pe(s),m(!1)}switch(s){case 1:i==="ulaw"||i==="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,i==="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:Pe(s),m(!1)}}getDecodeQueueSize(){return 0}decode(t){let r=ee(t.data),a=t.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=a*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(i),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 ae({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:a,timestamp:u});this.onSample(d)}async flush(){}close(){}},Ze=class extends Ht{constructor(e){if(!(e instanceof J))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),z.includes(a.codec)?new qi(e,t,a):new Qi(e,t,r,a)}_createPacketSink(){return new Te(this._audioTrack)}async getSample(e){Re(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)}},$i=class{constructor(e){if(!(e instanceof J))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Ze(e)}_audioSampleToWrappedArrayBuffer(e){return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}async getBuffer(e){Re(e);let t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return Et(this._audioSampleSink.samples(e,t),r=>this._audioSampleToWrappedArrayBuffer(r))}buffersAtTimestamps(e){return Et(this._audioSampleSink.samplesAtTimestamps(e),t=>t&&this._audioSampleToWrappedArrayBuffer(t))}};var Je=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof he}isAudioTrack(){return this instanceof J}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 Te(this),r=1/0,a=-1/0,i=0,s=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),i++,s+=o.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(a-r)).toPrecision(16)):0,averageBitrate:i?Number((8*s/(a-r)).toPrecision(16)):0}}},he=class extends Je{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:ta(this,e)}},J=class extends Je{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),ot.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 le=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=V(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 i=this.source._read(e,t),s={start:e,end:t,promise:i};this.loadingSegments.push(s);let o=await i;En(this.loadingSegments,s),this.insertIntoLoadedSegments(e,o)}rangeIsLoaded(e,t){if(t<=e)return!0;let r=V(this.loadedSegments,e,a=>a.start);if(r===-1)return!1;for(let a=r;a<this.loadedSegments.length;a++){let i=this.loadedSegments[a];if(i.start>e)break;if(i.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=V(this.loadedSegments,e,i=>i.start);(a===-1||this.loadedSegments[a].start<r.start)&&a++,this.loadedSegments.splice(a,0,r),this.totalStoredBytes+=t.byteLength;for(let i=a+1;i<this.loadedSegments.length;i++){let s=this.loadedSegments[i];if(s.start>=r.end)break;r.start<=s.start&&s.end<=r.end&&(this.loadedSegments.splice(i,1),i--)}for(;this.totalStoredBytes>this.maxStorableBytes&&this.loadedSegments.length>1;){let i=null,s=-1;for(let o=0;o<this.loadedSegments.length;o++){let c=this.loadedSegments[o];(!i||c.age<i.age)&&(i=c,s=o)}m(i),this.totalStoredBytes-=i.bytes.byteLength,this.loadedSegments.splice(s,1)}}getViewAndOffset(e,t){let r=V(this.loadedSegments,e,i=>i.start),a=null;if(r!==-1)for(let i=r;i<this.loadedSegments.length;i++){let s=this.loadedSegments[i];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=V(this.loadedSegments,e,i=>i.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 et=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 i=0;i<e;i++)a+=String.fromCharCode(t.getUint8(r+i));return a}};var ii=class extends ue{constructor(t){super(t);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.tracks=[];this.metadataReader=new et(t._mainReader),this.chunkReader=new et(new le(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",i=this.metadataReader.readU32(),s=a?t:Math.min(i+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 J(new ji(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(),i=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:i,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}},Ct=2048,ji=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 te}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){m(this.demuxer.audioInfo);let r=e*Ct*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let a=Math.min(Ct*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r),i;if(t.metadataOnly)i=ne;else{let c=Ct*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,i=this.demuxer.chunkReader.readBytes(a)}let s=e*Ct/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return new D(i,"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/Ct);return this.getPacketAtIndex(r,t)}getNextPacket(e,t){m(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ct);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var ni=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 ai=class extends de{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 ni(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 i=await this.mutex.acquire();try{if(this.headerWritten||(Ve(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{i()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(t,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let a,i=t.source._codec,s=Z(i);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 ye=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>G.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Y.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ce.includes(e))}_codecUnsupportedHint(e){return""}},Qt=class extends ye{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 Nr(e,this)}},si=class extends Qt{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...G,...Ee,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ce]}_codecUnsupportedHint(e){return new mt().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},mt=class extends Qt{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...G,...Y]}_codecUnsupportedHint(e){return new si().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},qt=class extends ye{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 Qr(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[...G,...Ee,...z.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...ce]}get supportsVideoRotationMetadata(){return!1}},gt=class extends qt{getSupportedCodecs(){return[...G.filter(e=>["vp8","vp9","av1"].includes(e)),...Y.filter(e=>["opus","vorbis"].includes(e)),...ce]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new qt().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Gi=class extends ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");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 Xr(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}},Xi=class extends ye{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 ai(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[...z.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}},Yi=class extends ye{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 ti(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[...Y.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}};var xt=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.")}async _start(){}async _flushAndClose(e){}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(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}},Fe=class extends xt{constructor(t){super();this._connectedTrack=null;if(!G.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${G.join(", ")}.`);this._codec=t}},$t=class extends Fe{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)}},sn=n=>{if(!n||typeof n!="object")throw new TypeError("Encoding config must be an object.");if(!G.includes(n.codec))throw new TypeError(`Invalid video codec '${n.codec}'. Must be one of: ${G.join(", ")}.`);if(!(n.bitrate instanceof Q)&&(!Number.isInteger(n.bitrate)||n.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(n.latencyMode!==void 0&&!["quality","realtime"].includes(n.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.");if(n.keyFrameInterval!==void 0&&(!Number.isFinite(n.keyFrameInterval)||n.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(n.fullCodecString!==void 0&&typeof n.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(n.fullCodecString!==void 0&&Ii(n.fullCodecString)!==n.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${n.codec}).`);if(n.onEncodedPacket!==void 0&&typeof n.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(n.onEncoderConfig!==void 0&&typeof n.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},jt=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 Be;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t,r){try{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,i=Math.floor(e.timestamp/a),s={...r,keyFrame:r?.keyFrame||a===0||i!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=i,this.customEncoder){this.customEncoderQueueSize++;let o=e.clone(),c=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,s)).then(()=>this.customEncoderQueueSize--).catch(u=>this.encoderError??=u).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await c}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}finally{t&&e.close()}}async ensureEncoder(e){if(!this.encoder)return this.ensureEncoderPromise=(async()=>{let t=e.codedWidth,r=e.codedHeight,a=this.encodingConfig.bitrate instanceof Q?this.encodingConfig.bitrate._toVideoBitrate(this.encodingConfig.codec,t,r):this.encodingConfig.bitrate,i={codec:this.encodingConfig.fullCodecString??pr(this.encodingConfig.codec,t,r,a),width:t,height:r,bitrate:a,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.encodingConfig.latencyMode,...gr(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(i);let s=He.find(o=>o.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,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(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.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=>{c.stack=new Error().stack,this.encoderError??=c}}),this.encoder.configure(i)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError}},Gt=class extends Fe{constructor(e){sn(e),super(e.codec),this._encoder=new jt(this,e)}add(e,t){if(!(e instanceof oe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},en=class extends Fe{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.");sn(t),super(t.codec),this._encoder=new jt(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 oe(this._canvas,{timestamp:e,duration:t});return this._encoder.add(a,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},tn=class extends Fe{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");sn(r),r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=W();this._errorPromiseAccessed=!1;this._encoder=new jt(this,r),this._track=t}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let t=null,r=!1,a=i=>{if(r){i.close();return}if(t===null){t=i.timestamp/1e6;let s=this._connectedTrack.output._muxer;s.firstMediaStreamTimestamp===null?(s.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-t):this._timestampOffset=performance.now()/1e3-s.firstMediaStreamTimestamp-t}if(this._encoder.getQueueSize()>=4){i.close();return}this._encoder.add(new oe(i),!0).catch(s=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(s),this._workerTrackId!==null&&Ji({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let i=new MediaStreamTrackProcessor({track:this._track}),s=new WritableStream({write:a});i.readable.pipeTo(s,{signal:this._abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||this._promiseWithResolvers.reject(o)})}else if(await Oo())this._workerTrackId=Ro++,Ji({type:"videoTrack",trackId:this._workerTrackId,track:this._track},[this._track]),this._workerListener=s=>{let o=s.data;o.type==="videoFrame"&&o.trackId===this._workerTrackId?a(o.videoFrame):o.type==="error"&&o.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(o.error)},me.addEventListener("message",this._workerListener);else throw new Error("MediaStreamTrackProcessor is required but not supported by this browser.")}async _flushAndClose(t){this._abortController&&(this._abortController.abort(),this._abortController=null),this._workerTrackId!==null&&(m(this._workerListener),Ji({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let a=i=>{let s=i.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(m(this._workerListener),me.removeEventListener("message",this._workerListener),me.removeEventListener("message",a),r())};me.addEventListener("message",a)})),await this._encoder.flushAndClose(t)}},Oe=class extends xt{constructor(t){super();this._connectedTrack=null;if(!Y.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Y.join(", ")}.`);this._codec=t}},Xt=class extends Oe{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)}},on=n=>{if(!n||typeof n!="object")throw new TypeError("Encoding config must be an object.");if(!Y.includes(n.codec))throw new TypeError(`Invalid audio codec '${n.codec}'. Must be one of: ${Y.join(", ")}.`);if(n.bitrate===void 0&&(!z.includes(n.codec)||n.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(n.bitrate!==void 0&&!(n.bitrate instanceof Q)&&(!Number.isInteger(n.bitrate)||n.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(n.fullCodecString!==void 0&&typeof n.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(n.fullCodecString!==void 0&&Ii(n.fullCodecString)!==n.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${n.codec}).`);if(n.onEncodedPacket!==void 0&&typeof n.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(n.onEncoderConfig!==void 0&&typeof n.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},Yt=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 Be;this.customEncoderQueueSize=0;this.encoderError=null}async add(e,t){try{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=e.clone(),a=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).then(()=>this.customEncoderQueueSize--).catch(i=>this.encoderError??=i).finally(()=>{r.close()});this.customEncoderQueueSize>=4&&await a,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}}finally{t&&e.close()}}async doPcmEncoding(e,t){m(this.outputSampleSize),m(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:a,sampleRate:i,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,k=new ArrayBuffer(f),g=new DataView(k);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:k}=c[h];for(let g=0;g<f;g++)this.writeOutputValue(k,(g*r+p)*this.outputSampleSize,d[h*o+g])}}t&&e.close();let l={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:i}};for(let p=0;p<c.length;p++){let{frameCount:h,view:f}=c[p],k=f.buffer,g=p*o,b=new D(new Uint8Array(k),"key",s+g/i,h/i);this.encodingConfig.onEncodedPacket?.(b,l),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,b,l)}}ensureEncoder(e){if(!this.encoderInitialized)return this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,a=this.encodingConfig.bitrate instanceof Q?this.encodingConfig.bitrate._toAudioBitrate(this.encodingConfig.codec):this.encodingConfig.bitrate,i={codec:this.encodingConfig.fullCodecString??hr(this.encodingConfig.codec,t,r),numberOfChannels:t,sampleRate:r,bitrate:a,...br(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(i);let s=Ke.find(o=>o.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,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(z.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(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.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=>{c.stack=new Error().stack,this.encoderError??=c}}),this.encoder.configure(i)}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}=Z(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(i,s,o)=>i.setUint8(s,j((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(i,s,o)=>{i.setInt8(s,j(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(i,s,o)=>{let c=j(Math.floor(o*32767),-32768,32767);i.setUint8(s,Ca(c))}:t==="alaw"?this.writeOutputValue=(i,s,o)=>{let c=j(Math.floor(o*32767),-32768,32767);i.setUint8(s,va(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(i,s,o)=>i.setUint16(s,j((o+1)*32767.5,0,65535),a):t==="signed"?this.writeOutputValue=(i,s,o)=>i.setInt16(s,j(Math.round(o*32767),-32768,32767),a):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(i,s,o)=>vi(i,s,j((o+1)*83886075e-1,0,16777215),a):t==="signed"?this.writeOutputValue=(i,s,o)=>Fn(i,s,j(Math.round(o*8388607),-8388608,8388607),a):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(i,s,o)=>i.setUint32(s,j((o+1)*21474836475e-1,0,4294967295),a):t==="signed"?this.writeOutputValue=(i,s,o)=>i.setInt32(s,j(Math.round(o*2147483647),-2147483648,2147483647),a):t==="float"?this.writeOutputValue=(i,s,o)=>i.setFloat32(s,o,a):m(!1);break;case 8:t==="float"?this.writeOutputValue=(i,s,o)=>i.setFloat64(s,o,a):m(!1);break;default:Pe(r),m(!1)}}async flushAndClose(e){this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),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}},vt=class extends Oe{constructor(e){on(e),super(e.codec),this._encoder=new Yt(this,e)}add(e){if(!(e instanceof ae))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},rn=class extends Oe{constructor(t){on(t);super(t.codec);this._accumulatedTime=0;this._encoder=new Yt(this,t)}add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let a=ae.fromAudioBuffer(t,this._accumulatedTime).map(i=>this._encoder.add(i,!0));return this._accumulatedTime+=t.duration,Promise.all(a)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},nn=class extends Oe{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");on(r);super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=W();this._errorPromiseAccessed=!1;this._encoder=new Yt(this,r),this._track=t}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}async _start(){if(this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController,typeof MediaStreamTrackProcessor<"u"){let t=null,r=new MediaStreamTrackProcessor({track:this._track}),a=new WritableStream({write:i=>{if(t===null){t=i.timestamp/1e6;let s=this._connectedTrack.output._muxer;s.firstMediaStreamTimestamp===null?(s.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-t):this._timestampOffset=performance.now()/1e3-s.firstMediaStreamTimestamp-t}if(this._encoder.getQueueSize()>=4){i.close();return}this._encoder.add(new ae(i),!0).catch(s=>{this._abortController?.abort(),this._promiseWithResolvers.reject(s)})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(i=>{i instanceof DOMException&&i.name==="AbortError"||this._promiseWithResolvers.reject(i)})}else{let t=window.AudioContext||window.webkitAudioContext;this._audioContext=new t({sampleRate:this._track.getSettings().sampleRate});let r=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),r.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let a=!1,i=0;this._scriptProcessorNode.onaudioprocess=s=>{let o=ae.fromAudioBuffer(s.inputBuffer,i);i+=s.inputBuffer.duration;for(let c of o){if(!a){a=!0;let u=this._connectedTrack.output._muxer;u.firstMediaStreamTimestamp===null?u.firstMediaStreamTimestamp=performance.now()/1e3:this._timestampOffset=performance.now()/1e3-u.firstMediaStreamTimestamp}if(this._encoder.getQueueSize()>=4){c.close();continue}this._encoder.add(c,!0).catch(u=>{this._audioContext.suspend(),this._promiseWithResolvers.reject(u)})}}}}async _flushAndClose(t){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(m(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(t)}},Ao=()=>{let n=(r,a)=>{a?self.postMessage(r,{transfer:a}):self.postMessage(r)};n({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let e=new Map,t=new Set;self.addEventListener("message",r=>{let a=r.data;switch(a.type){case"videoTrack":{let i=new MediaStreamTrackProcessor({track:a.track}),s=new WritableStream({write:c=>{if(t.has(a.trackId)){c.close();return}n({type:"videoFrame",trackId:a.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(a.trackId,o),i.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||n({type:"error",trackId:a.trackId,error:c})})}break;case"stopTrack":{let i=e.get(a.trackId);i&&(i.abort(),e.delete(a.trackId)),t.add(a.trackId),n({type:"trackStopped",trackId:a.trackId})}break;default:Pe(a)}})},Ro=0,me=null,Fo=()=>{let n=new Blob([`(${Ao.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(n);me=new Worker(e)},Zi=null,Oo=async()=>Zi!==null?Zi:(me||Fo(),new Promise(n=>{m(me);let e=t=>{let r=t.data;r.type==="support"&&(Zi=r.supported,me.removeEventListener("message",e),n(r.supported))};me.addEventListener("message",e)})),Ji=(n,e)=>{m(me),e?me.postMessage(n,e):me.postMessage(n)},Pt=class extends xt{constructor(t){super();this._connectedTrack=null;if(!ce.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${ce.join(", ")}.`);this._codec=t}},an=class extends Pt{constructor(e){super(e),this._parser=new Ir({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 Ea=["video","audio","subtitle"],cn=n=>{if(!n||typeof n!="object")throw new TypeError("metadata must be an object.");if(n.languageCode!==void 0&&!at(n.languageCode))throw new TypeError("metadata.languageCode must be a three-letter, ISO 639-2/T language code.")},Zt=class{constructor(e){this.state="pending";this._tracks=[];this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new ie;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof ye))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof $e))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 Fe))throw new TypeError("source must be a VideoSource.");if(cn(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 Oe))throw new TypeError("source must be an AudioSource.");cn(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Pt))throw new TypeError("source must be a SubtitleSource.");cn(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(),i=this._tracks.reduce((u,d)=>u+(d.type===e?1:0),0),s=a[e].max;if(i===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 Ea){let a=this._tracks.reduce((s,o)=>s+(o.type===r?1:0),0),i=e[r].min;if(a<i)throw new Error(i===e[r].max?`${this.format._name} requires exactly ${i} ${r} track${i===1?"":"s"}.`:`${this.format._name} requires at least ${i} ${r} track${i===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();let a=this._tracks.map(i=>i.source._start());await Promise.all(a),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._flushOrWaitForOngoingClose(!0));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._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}};var Me=class{constructor(){this._sizePromise=null;this.onread=null}getSize(){return this._sizePromise??=this._retrieveSize()}},dn=class extends Me{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}},un=class extends Me{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()}},ln=class extends Me{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}},mn=class extends Me{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._nextUrlVersion=null;this._url=t instanceof URL?t:new URL(t),this._options=r}async _makeRequest(t){let r={};t&&(r.Range=`bytes=${t.start}-${t.end-1}`),this._nextUrlVersion!==null&&(this._url.searchParams.set("mediabunny_version",this._nextUrlVersion.toString()),this._nextUrlVersion++);let a=await cr(this._url,At(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 i=await a.arrayBuffer();return a.status===206&&t&&i.byteLength!==t.end-t.start&&this._nextUrlVersion===null?(this._nextUrlVersion=1,this._makeRequest(t)):(a.status===200&&(this._fullData=i),{response:i,statusCode:a.status})}async _read(t,r){if(this._fullData)return new Uint8Array(this._fullData,t,r-t);let{response:a,statusCode:i}=await this._makeRequest({start:t,end:r});return i===200?new Uint8Array(a).subarray(t,r):new Uint8Array(a)}async _retrieveSize(){if(this._fullData)return this._fullData.byteLength;try{let a=await cr(this._url,At(this._options.requestInit??{},{method:"HEAD"}),this._options.getRetryDelay??(()=>null));if(a.ok){let i=a.headers.get("Content-Length");if(i)return parseInt(i)}}catch{}let t=await cr(this._url,At(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 i=a.match(/bytes \d+-\d+\/(\d+)/);if(i&&i[1])return parseInt(i[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 oi=class extends ue{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 ie;this.metadataReader=new je(t._mainReader),this.chunkReader=new je(new le(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 Wr({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+Ne);let r=this.metadataReader.pos,a=this.metadataReader.readBoxHeader();if(a.name==="ftyp"){let i=this.metadataReader.readAscii(4);this.isQuickTime=i==="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 i of this.tracks){let s=i.editListPreviousSegmentDurations/this.movieTimescale;i.editListOffset-=Math.round(s*i.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 i=this.metadataReader.readBoxHeader();i.name==="mfra"&&this.readContiguousBoxes(i.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&&z.includes(t.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(t.info?.type==="audio");let i=Z(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,k=V(r.sampleTimingEntries,h,v=>v.startIndex),g=r.sampleTimingEntries[k],b=V(r.sampleTimingEntries,f,v=>v.startIndex),w=r.sampleTimingEntries[b],C=g.startDecodeTimestamp+(h-g.startIndex)*g.delta,y=w.startDecodeTimestamp+(f-w.startIndex)*w.delta-C,T=U(s);T&&T.delta===y?T.count++:s.push({startIndex:u.startChunkIndex+p,startDecodeTimestamp:C,count:1,delta:y});let S=u.samplesPerChunk*i.sampleSize*t.info.numberOfChannels;o.push(S)}u.startSampleIndex=u.startChunkIndex,u.samplesPerChunk=1}r.sampleTimingEntries=s,r.sampleSizes=o}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let i of r.sampleTimingEntries)for(let s=0;s<i.count;s++)r.presentationTimestamps.push({presentationTimestamp:i.startDecodeTimestamp+s*i.delta,sampleIndex:i.startIndex+s});for(let i of r.sampleCompositionTimeOffsets)for(let s=0;s<i.count;s++){let o=i.startIndex+s,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=i.offset)}r.presentationTimestamps.sort((i,s)=>i.presentationTimestamp-s.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let i=0;i<r.presentationTimestamps.length;i++)r.presentationTimestampIndexMap[r.presentationTimestamps[i].sampleIndex]=i}return r}async readFragment(){let t=this.metadataReader.pos;await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Ne);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 i=H(this.fragments,t,o=>o.moofOffset);m(i!==-1);let s=this.fragments[i];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=V(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+Ne);let f=this.metadataReader.pos,k=this.metadataReader.readBoxHeader();if(k.name==="moof"){let g=H(this.fragments,f,w=>w.moofOffset),b;g===-1?(this.metadataReader.pos=f,b=await this.readFragment()):b=this.fragments[g],d&&(d.nextFragment=b),d=b,h&&(b.isKnownToBeFirstFragment=!0,h=!1)}this.metadataReader.pos=f+k.totalSize}d&&d.trackData.has(o)&&(l=d)}if(l){let f=l.trackData.get(o);m(f.startTimestampIsFinal),Aa(c,f.endTimestamp)}c.startTimestampIsFinal=!0}return s}readContiguousBoxes(t){let r=this.metadataReader.pos;for(;this.metadataReader.pos-r<=t-lt;)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 i=this.metadataReader.readU8();this.metadataReader.pos+=3,i===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 i={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,languageCode:te,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=i,this.readContiguousBoxes(r.contentSize),i.id!==-1&&i.timescale!==-1&&i.info!==null){if(i.info.type==="video"&&i.info.width!==-1){let s=i;i.inputTrack=new he(new fn(s)),this.tracks.push(i)}else if(i.info.type==="audio"&&i.info.numberOfChannels!==-1){let s=i;i.inputTrack=new J(new pn(s)),this.tracks.push(i)}}this.currentTrack=null}break;case"tkhd":{let i=this.currentTrack;m(i);let s=this.metadataReader.readU8();if(!((this.metadataReader.readU24()&1)!==0))break;if(s===0)this.metadataReader.pos+=8,i.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,i.durationInMovieTimescale=this.metadataReader.readU32();else if(s===1)this.metadataReader.pos+=16,i.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,i.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=De(_t(Vo(u),90));m(d===0||d===90||d===180||d===270),i.rotation=d}break;case"elst":{let i=this.currentTrack;m(i);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}i.editListPreviousSegmentDurations=c,i.editListOffset=p,o=!0}}}break;case"mdhd":{let i=this.currentTrack;m(i);let s=this.metadataReader.readU8();this.metadataReader.pos+=3,s===0?(this.metadataReader.pos+=8,i.timescale=this.metadataReader.readU32(),i.durationInMediaTimescale=this.metadataReader.readU32()):s===1&&(this.metadataReader.pos+=16,i.timescale=this.metadataReader.readU32(),i.durationInMediaTimescale=this.metadataReader.readU64());let o=this.metadataReader.readU16();if(o>0){i.languageCode="";for(let c=0;c<3;c++)i.languageCode=String.fromCharCode(96+(o&31))+i.languageCode,o>>=5;at(i.languageCode)||(i.languageCode=te)}}break;case"hdlr":{let i=this.currentTrack;m(i),this.metadataReader.pos+=8;let s=this.metadataReader.readAscii(4);s==="vide"?i.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:s==="soun"&&(i.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let i=this.currentTrack;m(i),i.sampleTableByteOffset=t,this.readContiguousBoxes(r.contentSize)}break;case"stsd":{let i=this.currentTrack;if(m(i),i.info===null||i.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(i.info.type==="video")l==="avc1"?i.info.codec="avc":l==="hvc1"||l==="hev1"?i.info.codec="hevc":l==="vp08"?i.info.codec="vp8":l==="vp09"?i.info.codec="vp9":l==="av01"?i.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),this.metadataReader.pos+=6*1+2+2+2+3*4,i.info.width=this.metadataReader.readU16(),i.info.height=this.metadataReader.readU16(),this.metadataReader.pos+=50,this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos);else{l==="mp4a"||(l==="opus"?i.info.codec="opus":l==="flac"?i.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"?i.info.codec="ulaw":l==="alaw"?i.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 k=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,k=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 b=f+7>>3,w=!!(g&1),C=!!(g&2),x=g&4?-1:0;f>0&&f<=64&&(w?f===32&&(i.info.codec=C?"pcm-f32be":"pcm-f32"):x&1<<b-1?b===1?i.info.codec="pcm-s8":b===2?i.info.codec=C?"pcm-s16be":"pcm-s16":b===3?i.info.codec=C?"pcm-s24be":"pcm-s24":b===4&&(i.info.codec=C?"pcm-s32be":"pcm-s32"):b===1&&(i.info.codec="pcm-u8")),i.info.codec===null&&console.warn("Unsupported PCM format.")}}}i.info.numberOfChannels=h,i.info.sampleRate=k,l==="twos"?f===8?i.info.codec="pcm-s8":f===16?i.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${f} for codec 'twos'.`),i.info.codec=null):l==="sowt"?f===8?i.info.codec="pcm-s8":f===16?i.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${f} for codec 'sowt'.`),i.info.codec=null):l==="raw "?i.info.codec="pcm-u8":l==="in24"?i.info.codec="pcm-s24be":l==="in32"?i.info.codec="pcm-s32be":l==="fl32"?i.info.codec="pcm-f32be":l==="fl64"?i.info.codec="pcm-f64be":l==="ipcm"?i.info.codec="pcm-s16be":l==="fpcm"&&(i.info.codec="pcm-f32be"),this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos)}}}break;case"avcC":{let i=this.currentTrack;m(i&&i.info),i.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"hvcC":{let i=this.currentTrack;m(i&&i.info),i.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"vpcC":{let i=this.currentTrack;m(i&&i.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();i.info.vp9CodecInfo={profile:s,level:o,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:l,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:f}}break;case"av1C":{let i=this.currentTrack;m(i&&i.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,k=u>>2&1,g=u&3,b=o==2&&l?p?12:10:l?10:8;i.info.av1CodecInfo={profile:o,level:c,tier:d,bitDepth:b,monochrome:h,chromaSubsamplingX:f,chromaSubsamplingY:k,chromaSamplePosition:g}}break;case"colr":{let i=this.currentTrack;if(m(i&&i.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);i.info.colorSpace={primaries:ir[o],transfer:nr[c],matrix:ar[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(r.contentSize);break;case"esds":{let i=this.currentTrack;m(i&&i.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 k=this.metadataReader.readU8();this.metadataReader.pos+=k}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?(i.info.codec="aac",i.info.aacCodecInfo={isMpeg2:f===103}):f===105||f===107?i.info.codec="mp3":f===221?i.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${f}) - discarding track.`),this.metadataReader.pos+=12,p>this.metadataReader.pos-h){let k=this.metadataReader.readU8();m(k===5);let g=this.metadataReader.readIsomVariableInteger();if(i.info.codecDescription=this.metadataReader.readBytes(g),i.info.codec==="aac"){let b=Pi(i.info.codecDescription);b.numberOfChannels!==null&&(i.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(i.info.sampleRate=b.sampleRate)}}}break;case"enda":{let i=this.currentTrack;m(i&&i.info?.type==="audio"),this.metadataReader.readU16()&255&&(i.info.codec==="pcm-s16be"?i.info.codec="pcm-s16":i.info.codec==="pcm-s24be"?i.info.codec="pcm-s24":i.info.codec==="pcm-s32be"?i.info.codec="pcm-s32":i.info.codec==="pcm-f32be"?i.info.codec="pcm-f32":i.info.codec==="pcm-f64be"&&(i.info.codec="pcm-f64"))}break;case"pcmC":{let i=this.currentTrack;m(i&&i.info?.type==="audio"),this.metadataReader.pos+=4;let o=!!(this.metadataReader.readU8()&1),c=this.metadataReader.readU8();i.info.codec==="pcm-s16be"?o?c===16?i.info.codec="pcm-s16":c===24?i.info.codec="pcm-s24":c===32?i.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${c}.`),i.info.codec=null):c===16?i.info.codec="pcm-s16be":c===24?i.info.codec="pcm-s24be":c===32?i.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${c}.`),i.info.codec=null):i.info.codec==="pcm-f32be"&&(o?c===32?i.info.codec="pcm-f32":c===64?i.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${c}.`),i.info.codec=null):c===32?i.info.codec="pcm-f32be":c===64?i.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${c}.`),i.info.codec=null));break}case"dOps":{let i=this.currentTrack;m(i&&i.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),i.info.codecDescription=p,i.info.numberOfChannels=s,i.info.sampleRate=c}break;case"dfLa":{let i=this.currentTrack;m(i&&i.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(),b=g>>>12,w=(g>>9&7)+1;i.info.sampleRate=b,i.info.numberOfChannels=w,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),i.info.codecDescription=l}break;case"stts":{let i=this.currentTrack;if(m(i),!i.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();i.sampleTable.sampleTimingEntries.push({startIndex:o,startDecodeTimestamp:c,count:d,delta:l}),o+=d,c+=d*l}}break;case"ctts":{let i=this.currentTrack;if(m(i),!i.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();i.sampleTable.sampleCompositionTimeOffsets.push({startIndex:o,count:u,offset:d}),o+=u}}break;case"stsz":{let i=this.currentTrack;if(m(i),!i.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();i.sampleTable.sampleSizes.push(u)}else i.sampleTable.sampleSizes.push(s)}break;case"stz2":{let i=this.currentTrack;if(m(i),!i.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 q(c);for(let d=0;d<o;d++){let l=u.readBits(s);i.sampleTable.sampleSizes.push(l)}}break;case"stss":{let i=this.currentTrack;if(m(i),!i.sampleTable)break;this.metadataReader.pos+=4,i.sampleTable.keySampleIndices=[];let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32()-1;i.sampleTable.keySampleIndices.push(c)}i.sampleTable.keySampleIndices[0]!==0&&i.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let i=this.currentTrack;if(m(i),!i.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();i.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:l})}let o=0;for(let c=0;c<i.sampleTable.sampleToChunk.length;c++)if(i.sampleTable.sampleToChunk[c].startSampleIndex=o,c<i.sampleTable.sampleToChunk.length-1){let d=i.sampleTable.sampleToChunk[c+1].startChunkIndex-i.sampleTable.sampleToChunk[c].startChunkIndex;o+=d*i.sampleTable.sampleToChunk[c].samplesPerChunk}}break;case"stco":{let i=this.currentTrack;if(m(i),!i.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32();i.sampleTable.chunkOffsets.push(c)}}break;case"co64":{let i=this.currentTrack;if(m(i),!i.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU64();i.sampleTable.chunkOffsets.push(c)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(r.contentSize);break;case"mehd":{let i=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=i===1?this.metadataReader.readU64():this.metadataReader.readU32();this.movieDurationInTimescale=s}break;case"trex":{this.metadataReader.pos+=4;let i=this.metadataReader.readU32(),s=this.metadataReader.readU32(),o=this.metadataReader.readU32(),c=this.metadataReader.readU32(),u=this.metadataReader.readU32();this.fragmentTrackDefaults.push({trackId:i,defaultSampleDescriptionIndex:s,defaultSampleDuration:o,defaultSampleSize:c,defaultSampleFlags:u})}break;case"tfra":{let i=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=this.metadataReader.readU32(),o=this.tracks.find(w=>w.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],k=h[d],g=h[l],b=this.metadataReader.readU32();for(let w=0;w<b;w++){let C=i===1?this.metadataReader.readU64():this.metadataReader.readU32(),x=i===1?this.metadataReader.readU64():this.metadataReader.readU32(),y=f(),T=k(),S=g();o.fragmentLookupTable.push({timestamp:C,moofOffset:x})}}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),pe(this.fragments,this.currentFragment,i=>i.moofOffset);for(let[,i]of this.currentFragment.trackData){let s=i.samples[0],o=U(i.samples);this.currentFragment.dataStart=Math.min(this.currentFragment.dataStart,s.byteOffset),this.currentFragment.dataEnd=Math.max(this.currentFragment.dataEnd,o.byteOffset+o.byteSize)}this.currentFragment=null}break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(r.contentSize),this.currentTrack){let i=this.currentFragment.trackData.get(this.currentTrack.id);if(i){pe(this.currentTrack.fragments,this.currentFragment,c=>c.moofOffset),i.firstKeyFrameTimestamp!==null&&pe(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment,c=>c.moofOffset);let{currentFragmentState:o}=this.currentTrack;m(o),o.startTimestamp!==null&&(Aa(i,o.startTimestamp),i.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),this.metadataReader.pos+=1;let i=this.metadataReader.readU24(),s=!!(i&1),o=!!(i&2),c=!!(i&8),u=!!(i&16),d=!!(i&32),l=!!(i&65536),p=!!(i&131072),h=this.metadataReader.readU32(),f=this.tracks.find(g=>g.id===h);if(!f)break;let k=this.fragmentTrackDefaults.find(g=>g.trackId===h);this.currentTrack=f,f.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:k?.defaultSampleDescriptionIndex??null,defaultSampleDuration:k?.defaultSampleDuration??null,defaultSampleSize:k?.defaultSampleSize??null,defaultSampleFlags:k?.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 i=this.currentTrack;if(!i)break;m(i.currentFragmentState);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=s===0?this.metadataReader.readU32():this.metadataReader.readU64();i.currentFragmentState.startTimestamp=o}break;case"trun":{let i=this.currentTrack;if(!i)break;if(m(this.currentFragment),m(i.currentFragmentState),this.currentFragment.trackData.has(i.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(),k=i.currentFragmentState.baseDataOffset;c&&(k+=this.metadataReader.readI32());let g=null;u&&(g=this.metadataReader.readU32());let b=k;if(f===0){this.currentFragment.implicitBaseDataOffset=b;break}let w=0,C={startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(i.id,C);for(let T=0;T<f;T++){let S;d?S=this.metadataReader.readU32():(m(i.currentFragmentState.defaultSampleDuration!==null),S=i.currentFragmentState.defaultSampleDuration);let v;l?v=this.metadataReader.readU32():(m(i.currentFragmentState.defaultSampleSize!==null),v=i.currentFragmentState.defaultSampleSize);let E;p?E=this.metadataReader.readU32():(m(i.currentFragmentState.defaultSampleFlags!==null),E=i.currentFragmentState.defaultSampleFlags),T===0&&g!==null&&(E=g);let A=0;h&&(s===0?A=this.metadataReader.readU32():A=this.metadataReader.readI32());let _=!(E&65536);C.samples.push({presentationTimestamp:w+A,duration:S,byteOffset:b,byteSize:v,isKeyFrame:_}),b+=v,w+=S}C.presentationTimestamps=C.samples.map((T,S)=>({presentationTimestamp:T.presentationTimestamp,sampleIndex:S})).sort((T,S)=>T.presentationTimestamp-S.presentationTimestamp);for(let T=0;T<C.presentationTimestamps.length;T++){let S=C.presentationTimestamps[T],v=C.samples[S.sampleIndex];if(C.firstKeyFrameTimestamp===null&&v.isKeyFrame&&(C.firstKeyFrameTimestamp=v.presentationTimestamp),T<C.presentationTimestamps.length-1){let E=C.presentationTimestamps[T+1];v.duration=E.presentationTimestamp-S.presentationTimestamp}}let x=C.samples[C.presentationTimestamps[0].sampleIndex],y=C.samples[U(C.presentationTimestamps).sampleIndex];C.startTimestamp=x.presentationTimestamp,C.endTimestamp=y.presentationTimestamp+y.duration,this.currentFragment.implicitBaseDataOffset=b}break}this.metadataReader.pos=a}},ci=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){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(()=>{let r=this.internalTrack.demuxer.fragments[0]??null;if(r?.isKnownToBeFirstFragment){let a=r;for(;a;){if(a.trackData.get(this.internalTrack.id))return{fragmentIndex:H(this.internalTrack.fragments,a.moofOffset,s=>s.moofOffset),sampleIndex:0,correctSampleFound:!0};a=a.nextFragment}}return{fragmentIndex:-1,sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return nt(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=_a(a,r),s=await this.fetchPacketForSampleIndex(i,t);return!Ra(a)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(()=>this.findSampleInFragmentsForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,t);let a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");let i=a.fragment.trackData.get(this.internalTrack.id),s=H(this.internalTrack.fragments,a.fragment.moofOffset,o=>o.moofOffset);return m(s!==-1),this.performFragmentedLookup(()=>{if(a.sampleIndex+1<i.samples.length)return{fragmentIndex:s,sampleIndex:a.sampleIndex+1,correctSampleFound:!0};{let o=a.fragment;for(;o.nextFragment;)if(o=o.nextFragment,o.trackData.get(this.internalTrack.id)){let u=H(this.internalTrack.fragments,o.moofOffset,d=>d.moofOffset);return m(u!==-1),{fragmentIndex:u,sampleIndex:0,correctSampleFound:!0}}return{fragmentIndex:s,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=_a(a,r),s=i===-1?-1:Bo(a,i),o=await this.fetchPacketForSampleIndex(s,t);return!Ra(a)||!this.internalTrack.demuxer.isFragmented?o:this.performFragmentedLookup(()=>this.findKeySampleInFragmentsForTimestamp(r),r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),c=Do(o,r);return this.fetchPacketForSampleIndex(c,t)}let a=this.packetToFragmentLocation.get(e);if(a===void 0)throw new Error("Packet was not created from this track.");let i=a.fragment.trackData.get(this.internalTrack.id),s=H(this.internalTrack.fragments,a.fragment.moofOffset,o=>o.moofOffset);return m(s!==-1),this.performFragmentedLookup(()=>{let o=i.samples.findIndex((c,u)=>c.isKeyFrame&&u>a.sampleIndex);if(o!==-1)return{fragmentIndex:s,sampleIndex:o,correctSampleFound:!0};{let c=a.fragment;for(;c.nextFragment;){c=c.nextFragment;let u=c.trackData.get(this.internalTrack.id);if(u&&u.firstKeyFrameTimestamp!==null){let d=H(this.internalTrack.fragments,c.moofOffset,p=>p.moofOffset);m(d!==-1);let l=u.samples.findIndex(p=>p.isKeyFrame);return m(l!==-1),{fragmentIndex:d,sampleIndex:l,correctSampleFound:!0}}}return{fragmentIndex:s,sampleIndex:-1,correctSampleFound:!1}}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Mo(r,e);if(!a)return null;let i;t.metadataOnly?i=ne:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(a.chunkOffset,a.chunkOffset+a.chunkSize),this.internalTrack.demuxer.chunkReader.pos=a.sampleOffset,i=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(i,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 i=e.trackData.get(this.internalTrack.id).samples[t];m(i);let s;r.metadataOnly?s=ne:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(e.dataStart,e.dataEnd),this.internalTrack.demuxer.chunkReader.pos=i.byteOffset,s=this.internalTrack.demuxer.chunkReader.readBytes(i.byteSize));let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=i.duration/this.internalTrack.timescale,u=new D(s,i.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}findSampleInFragmentsForTimestamp(e){let t=V(this.internalTrack.fragments,e,i=>i.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=V(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=V(this.internalTrack.fragmentsWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=-1,i=!1;if(t!==-1){let s=this.internalTrack.fragmentsWithKeyFrame[t];r=H(this.internalTrack.fragments,s.moofOffset,d=>d.moofOffset),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=or(o.presentationTimestamps,d=>o.samples[d.sampleIndex].isKeyFrame&&d.presentationTimestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].sampleIndex,i=e<o.endTimestamp}return{fragmentIndex:r,sampleIndex:a,correctSampleFound:i}}async performFragmentedLookup(e,t,r,a){let i=this.internalTrack.demuxer,s=await i.fragmentLookupMutex.acquire();try{let{fragmentIndex:o,sampleIndex:c,correctSampleFound:u}=e();if(u){let x=this.internalTrack.fragments[o];return this.fetchPacketInFragment(x,c,a)}let d=i.metadataReader,l=await d.reader.source.getSize(),p=null,h=o,f=c,k=this.internalTrack.fragmentLookupTable?V(this.internalTrack.fragmentLookupTable,t,x=>x.timestamp):-1,g=k!==-1?this.internalTrack.fragmentLookupTable[k]:null,b=!1;if(o===-1)d.pos=g?.moofOffset??0,b=d.pos===0;else{let x=this.internalTrack.fragments[o];!g||x.moofOffset>=g.moofOffset?(d.pos=x.moofOffset+x.moofSize,p=x):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+Ne);let x=d.pos,y=d.readBoxHeader();if(y.name==="moof"){let T=H(i.fragments,x,_=>_.moofOffset),S;T===-1?(d.pos=x,S=await i.readFragment()):S=i.fragments[T],p&&(p.nextFragment=S),p=S,b&&(S.isKnownToBeFirstFragment=!0,b=!1);let{fragmentIndex:v,sampleIndex:E,correctSampleFound:A}=e();if(A){let _=this.internalTrack.fragments[v];return this.fetchPacketInFragment(_,E,a)}v!==-1&&(h=v,f=E)}d.pos=x+y.totalSize}let w=null,C=h!==-1?this.internalTrack.fragments[h]:null;if(C&&(w=await this.fetchPacketInFragment(C,f,a)),!w&&g&&(!C||C.moofOffset<g.moofOffset)){let y=this.internalTrack.fragmentLookupTable[k-1]?.timestamp??-1/0;return this.performFragmentedLookup(e,y,r,a)}return w}finally{s()}}},fn=class extends ci{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&&Or(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Mr(t.data)}return{codec:wr(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}},pn=class extends ci{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:Tr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},_a=(n,e)=>{if(n.presentationTimestamps){let t=V(n.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:n.presentationTimestamps[t].sampleIndex}else{let t=V(n.sampleTimingEntries,e,a=>a.startDecodeTimestamp);if(t===-1)return-1;let r=n.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},Mo=(n,e)=>{let t=V(n.sampleTimingEntries,e,b=>b.startIndex),r=n.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let i=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=V(n.sampleCompositionTimeOffsets,e,b=>b.startIndex),o=n.sampleCompositionTimeOffsets[s];o&&e-o.startIndex<o.count&&(i+=o.offset);let c=n.sampleSizes[Math.min(e,n.sampleSizes.length-1)],u=V(n.sampleToChunk,e,b=>b.startSampleIndex),d=n.sampleToChunk[u];m(d);let l=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),p=n.chunkOffsets[l],h=d.startSampleIndex+(l-d.startChunkIndex)*d.samplesPerChunk,f=0,k=p;if(n.sampleSizes.length===1)k+=c*(e-h),f+=c*d.samplesPerChunk;else for(let b=h;b<h+d.samplesPerChunk;b++){let w=n.sampleSizes[b];b<e&&(k+=w),f+=w}let g=r.delta;if(n.presentationTimestamps){let b=n.presentationTimestampIndexMap[e];m(b!==void 0),b<n.presentationTimestamps.length-1&&(g=n.presentationTimestamps[b+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:g,sampleOffset:k,sampleSize:c,chunkOffset:p,chunkSize:f,isKeyFrame:n.keySampleIndices?H(n.keySampleIndices,e,b=>b)!==-1:!0}},Bo=(n,e)=>{if(!n.keySampleIndices)return e;let t=V(n.keySampleIndices,e,r=>r);return n.keySampleIndices[t]??-1},Do=(n,e)=>{if(!n.keySampleIndices)return e+1;let t=V(n.keySampleIndices,e,r=>r);return n.keySampleIndices[t+1]??-1},Aa=(n,e)=>{n.startTimestamp+=e,n.endTimestamp+=e;for(let t of n.samples)t.presentationTimestamp+=e;for(let t of n.presentationTimestamps)t.presentationTimestamp+=e},Vo=n=>{let[e,,,t]=n,r=Math.hypot(e,t),a=e/r,i=t/r;return-Math.atan2(i,a)*(180/Math.PI)},Ra=n=>n.sampleSizes.length===0;var hn=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],di=class extends ue{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 Ge(t._mainReader),this.clusterReader=new Ge(new le(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 Kr({isWebM:this.isWebM,hasVideo:this.segments.some(a=>a.tracks.some(i=>i.info?.type==="video")),hasAudio:this.segments.some(a=>a.tracks.some(i=>i.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-Ae;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+ht);let r=this.metadataReader.readElementHeader();if(!r)break;let a=r.id,i=r.size,s=this.metadataReader.pos;if(a===440786851)Xe(i),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+i),this.readContiguousElements(this.metadataReader,i);else if(a===408125543){if(await this.readSegment(i),i===null)break}else if(a===524531317){i===null&&(i=(await this.clusterReader.searchForNextElementId(Hr,t)??t)-s);let o=U(this.segments);o&&(o.elementEndPos=s+i)}Xe(i),this.metadataReader.pos=s+i}})()}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 ie},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-Ae;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+ht);let u=this.metadataReader.pos,d=this.metadataReader.readElementHeader();if(!d)break;let{id:l,size:p}=d,h=this.metadataReader.pos,f=hn.findIndex(k=>k.id===l);if(f!==-1){let k=hn[f].flag;this.currentSegment[k]=!0,Xe(p),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+p),this.readContiguousElements(this.metadataReader,p)}else l===524531317&&(a||(a=!0,this.currentSegment.clusterSeekStartPos=u));if(this.currentSegment.infoSeen&&this.currentSegment.tracksSeen&&this.currentSegment.cuesSeen)break;if(this.currentSegment.seekHeadSeen){let k=this.currentSegment.infoSeen,g=this.currentSegment.tracksSeen,b=this.currentSegment.cuesSeen;for(let w of this.currentSegment.seekEntries)w.id===357149030?k=!0:w.id===374648427?g=!0:w.id===475249515&&(b=!0);if(k&&g&&b)break}if(p===null)break;this.metadataReader.pos=h+p,a||(this.currentSegment.clusterSeekStartPos=this.metadataReader.pos)}for(let u of hn){if(this.currentSegment[u.flag])continue;let d=this.currentSegment.seekEntries.find(f=>f.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 l=this.metadataReader.readElementHeader();if(!l)continue;let{id:p,size:h}=l;p===u.id&&(Xe(h),this.currentSegment[u.flag]=!0,await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+h),this.readContiguousElements(this.metadataReader,h))}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6),this.currentSegment.tracks.sort((u,d)=>Number(d.isDefault)-Number(u.isDefault)),this.currentSegment.cuePoints.sort((u,d)=>u.clusterPosition-d.clusterPosition);let i=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 i)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+ht);let r=this.metadataReader.pos,a=this.metadataReader.readElementHeader();m(a);let i=a.id,s=a.size,o=this.metadataReader.pos;s===null&&(this.clusterReader.pos=o,s=(await this.clusterReader.searchForNextElementId(Hr,t.elementEndPos)??t.elementEndPos)-o),m(i===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[u,d]of c.trackData){let l=t.tracks.find(g=>g.id===u)??null;m(d.blocks.length>0);let p=!1,h=!1;for(let g=0;g<d.blocks.length;g++){let b=d.blocks[g];b.timestamp+=c.timestamp,p||=b.referencedTimestamps.length>0,h||=b.lacing!==0}p&&(d.blocks=Uo(d.blocks)),d.presentationTimestamps=d.blocks.map((g,b)=>({timestamp:g.timestamp,blockIndex:b})).sort((g,b)=>g.timestamp-b.timestamp);for(let g=0;g<d.presentationTimestamps.length;g++){let b=d.presentationTimestamps[g],w=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&w.isKeyFrame&&(d.firstKeyFrameTimestamp=w.timestamp),g<d.presentationTimestamps.length-1){let C=d.presentationTimestamps[g+1];w.duration=C.timestamp-w.timestamp}else w.duration===0&&l?.defaultDuration!=null&&w.lacing===0&&(w.duration=l.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,l),d.presentationTimestamps=d.blocks.map((g,b)=>({timestamp:g.timestamp,blockIndex:b})).sort((g,b)=>g.timestamp-b.timestamp));let f=d.blocks[d.presentationTimestamps[0].blockIndex],k=d.blocks[U(d.presentationTimestamps).blockIndex];d.startTimestamp=f.timestamp,d.endTimestamp=k.timestamp+k.duration,l&&(pe(l.clusters,c,b=>b.elementStartPos),d.firstKeyFrameTimestamp!==null&&pe(l.clustersWithKeyFrame,c,b=>b.elementStartPos))}return pe(t.clusters,c,u=>u.elementStartPos),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}expandLacedBlocks(t,r){for(let a=0;a<t.length;a++){let i=t[a];if(i.lacing===0)continue;let s=i.data,o=0,c=[],u=s[o]+1;switch(o++,i.lacing){case 1:{let l=0;for(let p=0;p<u-1;p++){let h=0;for(;o<s.length;){let f=s[o];if(h+=f,o++,f<255){c.push(h),l+=h;break}}}c.push(s.length-(o+l))}break;case 2:{let l=s.length-1,p=Math.floor(l/u);for(let h=0;h<u;h++)c.push(p)}break;case 3:{let l=Ui(s,o),p=l.value;c.push(p),o+=l.width;let h=p;for(let f=1;f<u-1;f++){let k=Ui(s,o),g=k.value,b=(1<<k.width*7-1)-1,w=g-b;p+=w,c.push(p),o+=k.width,h+=p}c.push(s.length-(o+h))}break;default:m(!1)}m(c.length===u),t.splice(a,1);let d=o;for(let l=0;l<u;l++){let p=c[l],h=s.subarray(d,d+p),f=i.duration||u*(r?.defaultDuration??0),k=i.timestamp+f*l/u,g=f/u;t.splice(a+l,0,{timestamp:k,duration:g,isKeyFrame:i.isKeyFrame,referencedTimestamps:i.referencedTimestamps,data:h,lacing:0}),d+=p}a+=u,a--}}readContiguousElements(t,r){let a=t.pos;for(;t.pos-a<=r-Ae&&this.traverseElement(t););}traverseElement(t){let r=t.readElementHeader();if(!r)return!1;let{id:a,size:i}=r,s=t.pos;switch(Xe(i),a){case 17026:this.isWebM=t.readAsciiString(i)==="webm";break;case 19899:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(t,i),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=t.readUnsignedInt(i)}break;case 21420:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=t.readUnsignedInt(i)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=t.readUnsignedInt(i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=t.readFloat(i)}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,defaultDuration:null,languageCode:te,info:null},this.readContiguousElements(t,i),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.codecId===se.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===se.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===se.vp8?this.currentTrack.info.codec="vp8":c===se.vp9?this.currentTrack.info.codec="vp9":c===se.av1&&(this.currentTrack.info.codec="av1");let u=this.currentTrack,d=new he(new gn(u));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){c===se.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===se.mp3?this.currentTrack.info.codec="mp3":c===se.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===se.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===se.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 u=this.currentTrack,d=new J(new bn(u));this.currentTrack.inputTrack=d,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=t.readUnsignedInt(i)}break;case 131:{if(!this.currentTrack)break;let o=t.readUnsignedInt(i);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null}:o===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(i)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!t.readUnsignedInt(i)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=t.readAsciiString(i)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=t.readBytes(i)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*t.readUnsignedInt(i)/1e9}break;case 2274716:{if(!this.currentTrack)break;this.currentTrack.languageCode=t.readAsciiString(i),at(this.currentTrack.languageCode)||(this.currentTrack.languageCode=te)}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,i)}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=t.readUnsignedInt(i)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=t.readUnsignedInt(i)}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(t,i)}break;case 21937:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=t.readUnsignedInt(i),c=ar[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case 21945:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=t.readUnsignedInt(i)===2}break;case 21946:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=t.readUnsignedInt(i),c=nr[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case 21947:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=t.readUnsignedInt(i),c=ir[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,i)}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let c=-t.readFloat(i);try{this.currentTrack.info.rotation=De(c)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(t,i)}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=t.readFloat(i)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=t.readUnsignedInt(i)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=t.readUnsignedInt(i)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(t,i),this.currentCueTime=null}break;case 179:this.currentCueTime=t.readUnsignedInt(i);break;case 183:{if(this.currentCueTime===null)break;m(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(t,i),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=t.readUnsignedInt(i)}break;case 241:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;m(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+t.readUnsignedInt(i)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=t.readUnsignedInt(i)}break;case 163:{if(!this.currentCluster)break;let o=t.readVarInt();if(o===null)break;let c=t.readS16(),u=t.readU8(),d=!!(u&128),l=u>>1&3;this.getTrackDataInCluster(this.currentCluster,o).blocks.push({timestamp:c,duration:0,isKeyFrame:d,referencedTimestamps:[],data:t.readBytes(i-(t.pos-s)),lacing:l})}break;case 160:{if(!this.currentCluster)break;if(this.readContiguousElements(t,i),this.currentBlock){for(let o=0;o<this.currentBlock.referencedTimestamps.length;o++)this.currentBlock.referencedTimestamps[o]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case 161:{if(!this.currentCluster)break;let o=t.readVarInt();if(o===null)break;let c=t.readS16(),d=t.readU8()>>1&3,l=this.getTrackDataInCluster(this.currentCluster,o);this.currentBlock={timestamp:c,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:t.readBytes(i-(t.pos-s)),lacing:d},l.blocks.push(this.currentBlock)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=t.readUnsignedInt(i)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let o=t.readSignedInt(i);this.currentBlock.referencedTimestamps.push(o)}break}return t.pos=s+i,!0}},ui=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:H(this.internalTrack.clusters,r.elementStartPos,i=>i.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return nt(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),i=H(this.internalTrack.clusters,r.cluster.elementStartPos,s=>s.elementStartPos);return m(i!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<a.blocks.length)return{clusterIndex:i,blockIndex:r.blockIndex+1,correctBlockFound:!0};{let s=r.cluster;for(;s.nextCluster;)if(s=s.nextCluster,s.trackData.get(this.internalTrack.id)){let c=H(this.internalTrack.clusters,s.elementStartPos,u=>u.elementStartPos);return m(c!==-1),{clusterIndex:c,blockIndex:0,correctBlockFound:!0}}return{clusterIndex:i,blockIndex:-1,correctBlockFound:!1}}},-1/0,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),i=H(this.internalTrack.clusters,r.cluster.elementStartPos,s=>s.elementStartPos);return m(i!==-1),this.performClusterLookup(()=>{let s=a.blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(s!==-1)return{clusterIndex:i,blockIndex:s,correctBlockFound:!0};{let o=r.cluster;for(;o.nextCluster;){o=o.nextCluster;let c=o.trackData.get(this.internalTrack.id);if(c&&c.firstKeyFrameTimestamp!==null){let u=H(this.internalTrack.clusters,o.elementStartPos,l=>l.elementStartPos);m(u!==-1);let d=c.blocks.findIndex(l=>l.isKeyFrame);return m(d!==-1),{clusterIndex:u,blockIndex:d,correctBlockFound:!0}}}return{clusterIndex:i,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];m(i);let s=r.metadataOnly?ne:i.data,o=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,u=new D(s,i.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,i.data.byteLength);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}findBlockInClustersForTimestamp(e){let t=V(this.internalTrack.clusters,e,i=>i.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=V(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=V(this.internalTrack.clustersWithKeyFrame,e,s=>s.trackData.get(this.internalTrack.id).firstKeyFrameTimestamp),r=-1,a=-1,i=!1;if(t!==-1){let s=this.internalTrack.clustersWithKeyFrame[t];r=H(this.internalTrack.clusters,s.elementStartPos,d=>d.elementStartPos),m(r!==-1);let o=s.trackData.get(this.internalTrack.id),c=or(o.presentationTimestamps,d=>o.blocks[d.blockIndex].isKeyFrame&&d.timestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].blockIndex,i=e<o.endTimestamp}return{clusterIndex:r,blockIndex:a,correctBlockFound:i}}async performClusterLookup(e,t,r,a){let{demuxer:i,segment:s}=this.internalTrack,o=await s.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:u,correctBlockFound:d}=e();if(d){let y=this.internalTrack.clusters[c];return this.fetchPacketInCluster(y,u,a)}let l=i.metadataReader,p=i.clusterReader,h=null,f=c,k=u,g=V(this.internalTrack.cuePoints,t,y=>y.time),b=g!==-1?this.internalTrack.cuePoints[g]:null,w=!1;if(c===-1)l.pos=b?.clusterPosition??s.clusterSeekStartPos,w=l.pos===s.clusterSeekStartPos;else{let y=this.internalTrack.clusters[c];!b||y.elementStartPos>=b.clusterPosition?(l.pos=y.elementEndPos,h=y):l.pos=b.clusterPosition}for(;l.pos<=s.elementEndPos-Ae;){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+ht);let y=l.pos,T=l.readElementHeader();if(!T)break;let S=T.id,v=T.size,E=l.pos;if(S===524531317){let A=H(s.clusters,y,ge=>ge.elementStartPos),_;A===-1?(l.pos=y,_=await i.readCluster(s)):_=s.clusters[A],h&&(h.nextCluster=_),h=_,w&&(_.isKnownToBeFirstCluster=!0,w=!1);let{clusterIndex:M,blockIndex:N,correctBlockFound:X}=e();if(X){let ge=this.internalTrack.clusters[M];return this.fetchPacketInCluster(ge,N,a)}M!==-1&&(f=M,k=N)}if(v===null){S===524531317?(m(h),v=h.elementEndPos-E):(p.pos=E,v=(await p.searchForNextElementId(Hr,s.elementEndPos)??s.elementEndPos)-E);let A=E+v;if(A>s.elementEndPos-Ae)break;if(p.pos=A,p.readElementId()===408125543){s.elementEndPos=A;break}}l.pos=E+v}let C=null,x=f!==-1?this.internalTrack.clusters[f]:null;if(x&&(C=await this.fetchPacketInCluster(x,k,a)),!C&&b&&(!x||x.elementStartPos<b.clusterPosition)){let T=this.internalTrack.cuePoints[g-1]?.time??-1/0;return this.performClusterLookup(e,T,r,a)}return C}finally{o()}}},gn=class extends ui{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:wr({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?Rr(t.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&t?Fr(t.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&t?Or(t.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&t?Mr(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}},bn=class extends ui{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:Tr({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}},Uo=n=>{let e=new Map;for(let i=0;i<n.length;i++){let s=n[i];e.set(s.timestamp,s)}let t=new Set,r=[],a=i=>{if(!t.has(i)){t.add(i);for(let s=0;s<i.referencedTimestamps.length;s++){let o=i.referencedTimestamps[s],c=e.get(o);c&&a(c)}r.push(i)}};for(let i=0;i<n.length;i++)a(n[i]);return r};var It=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 i=0;i<e;i++)a+=String.fromCharCode(t.getUint8(r+i));return a}readId3(){return this.readAscii(3)!=="ID3"?(this.pos-=3,null):(this.pos+=3,{size:zo(this.readU32())})}readNextFrameHeader(e){for(m(this.fileSize),e??=this.fileSize;this.pos<=e-4;){let t=this.readU32();this.pos-=4;let r=jr(t,this);if(r)return r}return null}},zo=n=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=n&e,e>>=8;return t};var li=class extends ue{constructor(t){super(t);this.metadataPromise=null;this.firstFrameHeader=null;this.loadedSamples=[];this.tracks=[];this.loadingMutex=new ie;this.lastLoadedPos=0;this.fileSize=0;this.nextTimestampInSamples=0;this.reader=new It(t._mainReader)}async readMetadata(){return this.metadataPromise??=(async()=>{for(this.fileSize=await this.input.source.getSize(),this.reader.fileSize=this.fileSize;!this.firstFrameHeader&&this.lastLoadedPos<this.fileSize;)await this.loadNextChunk();if(!this.firstFrameHeader)throw new Error("No MP3 frames found.");this.tracks=[new J(new wn(this))]})()}async loadNextChunk(){let t=await this.loadingMutex.acquire();try{m(this.lastLoadedPos<this.fileSize);let r=.5*1024*1024,a=Math.min(this.lastLoadedPos+r,this.fileSize);if(await this.reader.reader.loadRange(this.lastLoadedPos,a),this.lastLoadedPos=a,m(this.lastLoadedPos<=this.fileSize),this.reader.pos===0){let i=this.reader.readId3();i&&(this.reader.pos+=i.size)}this.parseFramesFromLoadedData()}finally{t()}}parseFramesFromLoadedData(){for(;;){let t=this.reader.pos,r=this.reader.readNextFrameHeader();if(!r)break;if(r.startPos+r.totalSize>this.lastLoadedPos){this.reader.pos=t,this.lastLoadedPos=t;break}let a=kt(r.mpegVersionId,r.channel);this.reader.pos=r.startPos+a;let i=this.reader.readU32(),s=i===bt||i===qr;if(this.reader.pos=r.startPos+r.totalSize-1,s)continue;this.firstFrameHeader||(this.firstFrameHeader=r);let o=r.audioSamplesInFrame/r.sampleRate,c={timestamp:this.nextTimestampInSamples/r.sampleRate,duration:o,dataStart:r.startPos,dataSize:r.totalSize};this.loadedSamples.push(c),this.nextTimestampInSamples+=r.audioSamplesInFrame}}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let t=this.tracks[0];return m(t),t.computeDuration()}},wn=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}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getLanguageCode(){return te}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.loadedSamples[e];if(!r)return null;let a;return t.metadataOnly?a=ne:(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){for(;this.demuxer.loadedSamples.length===0&&this.demuxer.lastLoadedPos<this.demuxer.fileSize;)await this.demuxer.loadNextChunk();return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=H(this.demuxer.loadedSamples,e.timestamp,i=>i.timestamp);if(r===-1)throw new Error("Packet was not created from this track.");let a=r+1;for(;a>=this.demuxer.loadedSamples.length&&this.demuxer.lastLoadedPos<this.demuxer.fileSize;)await this.demuxer.loadNextChunk();return this.getPacketAtIndex(a,t)}async getPacket(e,t){for(;;){let r=V(this.demuxer.loadedSamples,e,a=>a.timestamp);if(r===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastLoadedPos===this.demuxer.fileSize)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.loadNextChunk()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var mi=class extends ue{constructor(t){super(t);this.readingMutex=new ie;this.metadataPromise=null;this.fileSize=null;this.bitstreams=[];this.tracks=[];this.reader=new wt(new le(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{for(this.fileSize=await this.input.source.getSize();this.reader.pos<this.fileSize-Tt;){await this.reader.reader.loadRange(this.reader.pos,this.reader.pos+Ye);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 J(new Tn(t,this))))}})()}async readVorbisMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let i=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!i||(a=await this.findNextPacketStart(this.reader,i),!a))return;let s=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!s||i.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(i.data.length);let u=new Uint8Array(1+o.length+t.data.length+i.data.length+s.data.length);u[0]=o.length,u.set(o,1),u.set(t.data,1+o.length),u.set(i.data,1+o.length+t.data.length),u.set(s.data,1+o.length+t.data.length+i.data.length),r.codecInfo.codec="vorbis",r.description=u,r.lastMetadataPacket=s;let d=ee(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:Br(s.data).modeBlockflags}}async readOpusMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let i=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!i)return;r.codecInfo.codec="opus",r.description=t.data,r.lastMetadataPacket=i;let s=Ue(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 i=0;for(let h=0;h<a;h++)i+=r.lacingValues[h];let s=r,o=i,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(i,o));break}let f=s.lacingValues[c];if(o+=f,f<255){u.push(h.subarray(i,o));break e}c++}for(;;){if(t.pos=s.headerStartPos+s.totalSize,t.pos>=this.fileSize-Tt)return null;await t.reader.loadRange(t.pos,t.pos+Ye);let f=t.readPageHeader();if(!f)return null;if(s=f,s.serialNumber===r.serialNumber)break}i=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-Tt)return null;await t.reader.loadRange(t.pos,t.pos+Ye);let i=t.readPageHeader();if(!i)return null;if(i.serialNumber===r.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t.pos=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return Jr({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)}},Tn=class{constructor(e,t){this.bitstream=e;this.demuxer=t;this.encodedPacketToMetadata=new WeakMap;this.internalSampleRate=e.codecInfo.codec==="opus"?ct: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 te}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:i}=Zr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new D(r.metadataOnly?ne: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:i}),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 i=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(this.demuxer.reader,a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,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 i=await this.demuxer.findNextPacketStart(this.demuxer.reader,a.packet);if(!i)return null;let s=a.timestampInSamples+a.durationInSamples,o=await this.demuxer.readPacket(this.demuxer.reader,i.startPage,i.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=nt(e*this.internalSampleRate,14);if(a===0)return this.getFirstPacket(t,!1);if(a<0)return null;let i=this.demuxer.reader;m(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(i,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 x=o.headerStartPos,y=Math.floor((x+c)/2),T=y;for(;;){let S=Math.min(T+ei,c-Tt);if(await i.reader.loadRange(T,S),i.pos=T,!i.findNextPageHeader(S)){c=y+Tt;continue e}await i.reader.loadRange(i.pos,i.pos+Ye);let E=i.readPageHeader();m(E);let A=!1;if(E.serialNumber===this.bitstream.serialNumber)A=!0;else{await i.reader.loadRange(E.headerStartPos,E.headerStartPos+E.totalSize),i.pos=E.headerStartPos;let M=i.readBytes(E.totalSize);A=Yr(M)===E.checksum}if(!A){T=E.headerStartPos+4;continue}if(A&&E.serialNumber!==this.bitstream.serialNumber){T=E.headerStartPos+E.totalSize;continue}if(E.granulePosition===-1){T=E.headerStartPos+E.totalSize;continue}this.granulePositionToTimestampInSamples(E.granulePosition)>a?c=E.headerStartPos:(o=E,u.push(E));continue e}}let d=s.startPage;for(let x of u){if(x.granulePosition===o.granulePosition)break;(!d||x.headerStartPos>d.headerStartPos)&&(d=x)}let l=d,p=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===o.granulePosition);){i.pos=l.headerStartPos+l.totalSize,await i.reader.loadRange(i.pos,i.pos+Ye);let x=i.readPageHeader();m(x),l=x,l.serialNumber===this.bitstream.serialNumber&&p.push(l)}m(l.granulePosition!==-1);let h=null,f,k,g=l,b=0;if(l.headerStartPos===s.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),k=!0,h=0;else{f=0,k=!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.");b=h-1;let x={data:ne,endPage:g,endSegmentIndex:b};if(await this.demuxer.findNextPacketStart(i,x)){let T=Oa(p,l,h);m(T);let S=Fa(p,T.page,T.segmentIndex);S&&(l=S.page,h=S.segmentIndex)}else for(;;){let T=Oa(p,l,h);if(!T)break;let S=Fa(p,T.page,T.segmentIndex);if(!S)break;if(l=S.page,h=S.segmentIndex,T.page.headerStartPos!==g.headerStartPos){g=T.page,b=T.segmentIndex;break}}}let w=null,C=null;for(;l!==null;){m(h!==null);let x=await this.demuxer.readPacket(i,l,h);if(!x)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&h<s.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f,vorbisLastBlocksize:C?.vorbisBlockSize??null},t);m(S);let v=this.encodedPacketToMetadata.get(S);if(m(v),!k&&x.endPage.headerStartPos===g.headerStartPos&&x.endSegmentIndex===b?(f=this.granulePositionToTimestampInSamples(l.granulePosition),k=!0,S=this.createEncodedPacketFromOggPacket(x,{timestampInSamples:f-v.durationInSamples,vorbisLastBlocksize:C?.vorbisBlockSize??null},t),m(S),v=this.encodedPacketToMetadata.get(S),m(v)):f+=v.durationInSamples,w=S,C=v,k&&(Math.max(f,0)>a||Math.max(v.timestampInSamples,0)===a))break}let T=await this.demuxer.findNextPacketStart(i,x);if(!T)break;l=T.startPage,h=T.startSegmentIndex}return w}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Fa=(n,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=Ci(n,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,a=r.lacingValues.length}if(m(a!==-1),a===r.lacingValues.length){let i=n[n.indexOf(r)+1];m(i),r=i,a=0}return{page:r,segmentIndex:a}},Oa=(n,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=Ci(n,a=>a.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Se=class{},Jt=class extends Se{async _getMajorBrand(e){if(await e._mainReader.source.getSize()<12)return null;let r=new je(e._mainReader);return r.pos=4,r.readAscii(4)!=="ftyp"?null:r.readAscii(4)}_createDemuxer(e){return new oi(e)}},fi=class extends Jt{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt  "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},pi=class extends Jt{async _canReadInput(e){return await this._getMajorBrand(e)==="qt  "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}};function Wo(){return 5}var er=class extends Se{async isSupportedEBMLOfDocType(e,t){if(await e._mainReader.source.getSize()<8)return!1;let a=new Ge(e._mainReader),i=a.readVarIntSize();if(i===null||(Wo(),i<1||i>8)||a.readUnsignedInt(i)!==440786851)return!1;let o=a.readElementSize();if(o===null)return!1;let c=a.pos;for(;a.pos<=c+o-Ae;){let u=a.readElementHeader();if(!u)break;let{id:d,size:l}=u,p=a.pos;if(l===null)return!1;switch(d){case 17030:if(a.readUnsignedInt(l)!==1)return!1;break;case 17143:if(a.readUnsignedInt(l)!==1)return!1;break;case 17026:if(a.readAsciiString(l)!==t)return!1;break;case 17031:if(a.readUnsignedInt(l)>4)return!1;break}a.pos=p+l}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new di(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},hi=class extends er{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},gi=class extends Se{async _canReadInput(e){let t=await e._mainReader.source.getSize();if(t<4)return!1;let r=new It(e._mainReader);r.fileSize=t;let a=r.readId3();a&&(r.pos+=a.size);let i=r.pos;await r.reader.loadRange(r.pos,r.pos+4096);let s=r.readNextFrameHeader(Math.min(i+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 li(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},bi=class extends Se{async _canReadInput(e){if(await e._mainReader.source.getSize()<12)return!1;let r=new et(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 ii(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},ki=class extends Se{async _canReadInput(e){return await e._mainReader.source.getSize()<4?!1:new wt(e._mainReader).readAscii(4)==="OggS"}_createDemuxer(e){return new mi(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Ma=new fi,Ba=new pi,Da=new er,Va=new hi,Ua=new gi,za=new bi,Wa=new ki,No=[Ma,Ba,Da,Va,za,Wa,Ua];var tr=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 Se)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Me))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._mainReader=new le(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 Na=n=>{if(n!==void 0&&(!n||typeof n!="object"))throw new TypeError("options.video, when provided, must be an object.");if(n?.discard!==void 0&&typeof n.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(n?.forceTranscode!==void 0&&typeof n.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(n?.codec!==void 0&&!G.includes(n.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${G.join(", ")}.`);if(n?.bitrate!==void 0&&!(n.bitrate instanceof Q)&&(!Number.isInteger(n.bitrate)||n.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(n?.width!==void 0&&(!Number.isInteger(n.width)||n.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(n?.height!==void 0&&(!Number.isInteger(n.height)||n.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(n?.fit!==void 0&&!["fill","contain","cover"].includes(n.fit))throw new TypeError('options.video.fit, when provided, must be one of "fill", "contain", or "cover".');if(n?.width!==void 0&&n.height!==void 0&&n.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(n?.rotate!==void 0&&![0,90,180,270].includes(n.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(n?.frameRate!==void 0&&(!Number.isFinite(n.frameRate)||n.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.")},La=n=>{if(n!==void 0&&(!n||typeof n!="object"))throw new TypeError("options.audio, when provided, must be an object.");if(n?.discard!==void 0&&typeof n.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(n?.forceTranscode!==void 0&&typeof n.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(n?.codec!==void 0&&!Y.includes(n.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Y.join(", ")}.`);if(n?.bitrate!==void 0&&!(n.bitrate instanceof Q)&&(!Number.isInteger(n.bitrate)||n.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(n?.numberOfChannels!==void 0&&(!Number.isInteger(n.numberOfChannels)||n.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(n?.sampleRate!==void 0&&(!Number.isInteger(n.sampleRate)||n.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.")},yn=2,Sn=48e3,Cn=class n{constructor(e){this._addedCounts={video:0,audio:0,subtitle:0};this._totalTrackCount=0;this._trackPromises=[];this._executed=!1;this._synchronizer=new xn;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 tr))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Zt))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(typeof e.video!="function"&&Na(e.video),typeof e.audio!="function"&&La(e.audio),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}=W();this._started=t,this._start=r}static async init(e){let t=new n(e);return await t._init(),t}async _init(){let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts(),r=1,a=1;for(let s of e){let o;if(s.isVideoTrack()?this._options.video&&(typeof this._options.video=="function"?(o=await this._options.video(s,r),Na(o),r++):o=this._options.video):s.isAudioTrack()?this._options.audio&&(typeof this._options.audio=="function"?(o=await this._options.audio(s,a),La(o),a++):o=this._options.audio):m(!1),o?.discard){this.discardedTracks.push({track:s,reason:"discarded_by_user"});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:s,reason:"max_track_count_reached"});continue}if(this._addedCounts[s.type]===t[s.type].max){this.discardedTracks.push({track:s,reason:"max_track_count_of_type_reached"});continue}s.isVideoTrack()?await this._processVideoTrack(s,o??{}):s.isAudioTrack()&&await this._processAudioTrack(s,o??{})}let i=this.discardedTracks.filter(s=>s.reason!=="discarded_by_user");i.length>0&&console.warn("Some tracks had to be discarded from the conversion:",i)}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||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,t){let r=e.codec;if(!r){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let a,i=De(e.rotation+(t.rotate??0)),s=this.output.format.supportsVideoRotationMetadata,[o,c]=i%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],u=o,d=c,l=u/d,p=b=>Math.ceil(b/2)*2;t.width!==void 0&&t.height===void 0?(u=p(t.width),d=p(Math.round(u/l))):t.width===void 0&&t.height!==void 0?(d=p(t.height),u=p(Math.round(d*l))):t.width!==void 0&&t.height!==void 0&&(u=p(t.width),d=p(t.height));let h=await e.getFirstTimestamp(),f=!!t.forceTranscode||this._startTimestamp>0||h<0||!!t.frameRate,k=u!==o||d!==c||i!==0&&!s,g=this.output.format.getSupportedVideoCodecs();if(!f&&!t.bitrate&&!k&&g.includes(r)&&(!t.codec||t.codec===r)){let b=new $t(r);a=b,this._trackPromises.push((async()=>{await this._started;let w=new Te(e),x={decoderConfig:await e.getDecoderConfig()??void 0},y=Number.isFinite(this._endTimestamp)?await w.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let T of w.packets(void 0,y,{verifyKeyPackets:!0})){if(this._synchronizer.shouldWait(e.id,T.timestamp)&&await this._synchronizer.wait(T.timestamp),this._canceled)return;await b.add(T,x),this._reportProgress(e.id,T.timestamp+T.duration)}b.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}t.codec&&(g=g.filter(T=>T===t.codec));let w=t.bitrate??yr,C=await Ei(g,{width:u,height:d,bitrate:w});if(!C){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}let x={codec:C,bitrate:w,onEncodedPacket:T=>this._reportProgress(e.id,T.timestamp+T.duration)},y=new Gt(x);a=y,k?this._trackPromises.push((async()=>{await this._started;let S=new Kt(e,{width:u,height:d,fit:t.fit??"fill",rotation:i,poolSize:1}).canvases(this._startTimestamp,this._endTimestamp),v=t.frameRate,E=null,A=null,_=null,M=async N=>{m(E),m(v!==void 0);let X=Math.round((N-A)*v);for(let ge=1;ge<X;ge++){let tt=new oe(E,{timestamp:A+ge/v,duration:1/v});await y.add(tt)}};for await(let{canvas:N,timestamp:X,duration:ge}of S){if(this._synchronizer.shouldWait(e.id,X)&&await this._synchronizer.wait(X),this._canceled)return;let tt=Math.max(X-this._startTimestamp,0);if(_=X+ge,v!==void 0){let rr=Math.floor(tt*v)/v;if(E!==null)if(rr<=A){E=N,A=rr;continue}else await M(rr);tt=rr}let Pn=new oe(N,{timestamp:tt,duration:v!==void 0?1/v:ge});await y.add(Pn),v!==void 0?(E=N,A=tt):Pn.close()}E&&(m(_!==null),m(v!==void 0),await M(Math.floor(_*v)/v)),y.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let T=new St(e),S=t.frameRate,v=null,E=null,A=null,_=async M=>{m(v),m(S!==void 0);let N=Math.round((M-E)*S);for(let X=1;X<N;X++)v.setTimestamp(E+X/S),v.setDuration(1/S),await y.add(v);v.close()};for await(let M of T.samples(this._startTimestamp,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,M.timestamp)&&await this._synchronizer.wait(M.timestamp),this._canceled){v?.close();return}let N=Math.max(M.timestamp-this._startTimestamp,0);if(A=M.timestamp+M.duration,S!==void 0){let X=Math.floor(N*S)/S;if(v!==null)if(X<=E){v.close(),v=M,E=X;continue}else await _(X);N=X,M.setDuration(1/S)}M.setTimestamp(N),await y.add(M),S!==void 0?(v=M,E=N):M.close()}v&&(m(A!==null),m(S!==void 0),await _(Math.floor(A*S)/S)),y.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(a,{frameRate:t.frameRate,languageCode:e.languageCode,rotation:k?0:i}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _processAudioTrack(e,t){let r=e.codec;if(!r){this.discardedTracks.push({track:e,reason:"unknown_source_codec"});return}let a,i=e.numberOfChannels,s=e.sampleRate,o=await e.getFirstTimestamp(),c=t.numberOfChannels??i,u=t.sampleRate??s,d=c!==i||u!==s||this._startTimestamp>0||o<0,l=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!d&&l.includes(r)&&(!t.codec||t.codec===r)){let p=new Xt(r);a=p,this._trackPromises.push((async()=>{await this._started;let h=new Te(e),k={decoderConfig:await e.getDecoderConfig()??void 0},g=Number.isFinite(this._endTimestamp)?await h.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let b of h.packets(void 0,g)){if(this._synchronizer.shouldWait(e.id,b.timestamp)&&await this._synchronizer.wait(b.timestamp),this._canceled)return;await p.add(b,k),this._reportProgress(e.id,b.timestamp+b.duration)}p.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});return}let h=null;t.codec&&(l=l.filter(g=>g===t.codec));let f=t.bitrate??yr,k=await Rt(l,{numberOfChannels:c,sampleRate:u,bitrate:f});if(!k.some(g=>Ee.includes(g))&&l.some(g=>Ee.includes(g))&&(c!==yn||u!==Sn)){let b=(await Rt(l,{numberOfChannels:yn,sampleRate:Sn,bitrate:f})).find(w=>Ee.includes(w));b&&(d=!0,h=b,c=yn,u=Sn)}else h=k[0]??null;if(h===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});return}if(d)a=this._resampleAudio(e,h,c,u,f);else{let g=new vt({codec:h,bitrate:f,onEncodedPacket:b=>this._reportProgress(e.id,b.timestamp+b.duration)});a=g,this._trackPromises.push((async()=>{await this._started;let b=new Ze(e);for await(let w of b.samples(void 0,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,w.timestamp)&&await this._synchronizer.wait(w.timestamp),this._canceled)return;await g.add(w),w.close()}g.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(a,{languageCode:e.languageCode}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}_resampleAudio(e,t,r,a,i){let s=new vt({codec:t,bitrate:i,onEncodedPacket:o=>this._reportProgress(e.id,o.timestamp+o.duration)});return this._trackPromises.push((async()=>{await this._started;let o=new vn({sourceNumberOfChannels:e.numberOfChannels,sourceSampleRate:e.sampleRate,targetNumberOfChannels:r,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:d=>s.add(d)}),u=new Ze(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,i=j(a/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,this.onProgress?.(i))}},Ha=5,xn=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<Ha&&(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>=Ha}wait(e){let{promise:t,resolve:r}=W();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},vn=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,i)=>r[a*e]*+(i<2):e===1&&t===6?this.channelMixer=(r,a,i)=>r[a*e]*+(i===2):e===2&&t===1?this.channelMixer=(r,a)=>{let i=a*e;return .5*(r[i]+r[i+1])}:e===2&&t===4?this.channelMixer=(r,a,i)=>r[a*e+i]*+(i<2):e===2&&t===6?this.channelMixer=(r,a,i)=>r[a*e+i]*+(i<2):e===4&&t===1?this.channelMixer=(r,a)=>{let i=a*e;return .25*(r[i]+r[i+1]+r[i+2]+r[i+3])}:e===4&&t===2?this.channelMixer=(r,a,i)=>{let s=a*e;return .5*(r[s+i]+r[s+i+2])}:e===4&&t===6?this.channelMixer=(r,a,i)=>{let s=a*e;return i<2?r[s+i]:i===2||i===3?0:r[s+i-2]}:e===6&&t===1?this.channelMixer=(r,a)=>{let i=a*e;return Math.SQRT1_2*(r[i]+r[i+1])+r[i+2]+.5*(r[i+4]+r[i+5])}:e===6&&t===2?this.channelMixer=(r,a,i)=>{let s=a*e;return r[s+i]+Math.SQRT1_2*(r[s+2]+r[s+i+4])}:e===6&&t===4?this.channelMixer=(r,a,i)=>{let s=a*e;return i<2?r[s+i]+Math.SQRT1_2*r[s+2]:r[s+i+2]}:this.channelMixer=(r,a,i)=>i<e?r[a*e+i]: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 i=e.timestamp-this.startTime,s=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+s,this.endTime-this.startTime),c=Math.floor(i*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-i)*this.sourceSampleRate,k=Math.floor(f),g=Math.ceil(f),b=f-k;for(let w=0;w<this.targetNumberOfChannels;w++){let C=0,x=0;k>=0&&k<e.numberOfFrames&&(C=this.channelMixer(a,k,w)),g>=0&&g<e.numberOfFrames&&(x=this.channelMixer(a,g,w));let y=C+b*(x-C),T=l*this.targetNumberOfChannels+w;this.outputBuffer[T]+=y}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 ae({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{No as ALL_FORMATS,Ea as ALL_TRACK_TYPES,Y as AUDIO_CODECS,$i as AudioBufferSink,rn as AudioBufferSource,ae as AudioSample,Ze as AudioSampleSink,vt as AudioSampleSource,Oe as AudioSource,Ht as BaseMediaSampleSink,ln as BlobSource,dn as BufferSource,Dt as BufferTarget,Kt as CanvasSink,en as CanvasSource,Cn as Conversion,lr as CustomAudioDecoder,fr as CustomAudioEncoder,ur as CustomVideoDecoder,mr as CustomVideoEncoder,Xt as EncodedAudioPacketSource,D as EncodedPacket,Te as EncodedPacketSink,$t as EncodedVideoPacketSource,tr as Input,J as InputAudioTrack,Se as InputFormat,Je as InputTrack,he as InputVideoTrack,Jt as IsobmffInputFormat,Qt as IsobmffOutputFormat,Da as MATROSKA,Ua as MP3,Ma as MP4,er as MatroskaInputFormat,xt as MediaSource,nn as MediaStreamAudioTrackSource,tn as MediaStreamVideoTrackSource,qt as MkvOutputFormat,mt as MovOutputFormat,gi as Mp3InputFormat,Gi as Mp3OutputFormat,fi as Mp4InputFormat,si as Mp4OutputFormat,Ee as NON_PCM_AUDIO_CODECS,Wa as OGG,ki as OggInputFormat,Yi as OggOutputFormat,Zt as Output,ye as OutputFormat,z as PCM_AUDIO_CODECS,Ba as QTFF,yr as QUALITY_HIGH,ja as QUALITY_LOW,Ga as QUALITY_MEDIUM,Xa as QUALITY_VERY_HIGH,$a as QUALITY_VERY_LOW,Q as Quality,pi as QuickTimeInputFormat,ce as SUBTITLE_CODECS,Me as Source,un as StreamSource,Vi as StreamTarget,Pt as SubtitleSource,$e as Target,an as TextSubtitleSource,mn as UrlSource,G as VIDEO_CODECS,oe as VideoSample,St as VideoSampleSink,Gt as VideoSampleSource,Fe as VideoSource,za as WAVE,Va as WEBM,Xi as WavOutputFormat,bi as WaveInputFormat,hi as WebMInputFormat,gt as WebMOutputFormat,is as canEncode,vr as canEncodeAudio,Pr as canEncodeSubtitles,xr as canEncodeVideo,Rt as getEncodableAudioCodecs,ns as getEncodableCodecs,Kn as getEncodableSubtitleCodecs,Hn as getEncodableVideoCodecs,as as getFirstEncodableAudioCodec,ss as getFirstEncodableSubtitleCodec,Ei as getFirstEncodableVideoCodec,Qa as registerDecoder,qa as registerEncoder};