mediabunny
Version:
Pure TypeScript media toolkit for reading, writing, and converting media files, directly in the browser.
18 lines • 305 kB
JavaScript
/*!
* 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/.
*/
"use strict";var Mediabunny=(()=>{var Bi=Object.defineProperty;var rs=Object.getOwnPropertyDescriptor;var is=Object.getOwnPropertyNames;var ns=Object.prototype.hasOwnProperty;var as=(i,e)=>{for(var t in e)Bi(i,t,{get:e[t],enumerable:!0})},ss=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of is(e))!ns.call(i,a)&&a!==t&&Bi(i,a,{get:()=>e[a],enumerable:!(r=rs(e,a))||r.enumerable});return i};var os=i=>ss(Bi({},"__esModule",{value:!0}),i);var Go={};as(Go,{ALL_FORMATS:()=>Za,ALL_TRACK_TYPES:()=>bn,AUDIO_CODECS:()=>X,AudioBufferSink:()=>mi,AudioBufferSource:()=>yi,AudioSample:()=>ie,AudioSampleSink:()=>He,AudioSampleSource:()=>at,AudioSource:()=>ve,BaseMediaSampleSink:()=>Et,BlobSource:()=>Pi,BufferSource:()=>xi,BufferTarget:()=>kt,CanvasSink:()=>_t,CanvasSource:()=>wi,Conversion:()=>Mi,CustomAudioDecoder:()=>Qt,CustomAudioEncoder:()=>$t,CustomVideoDecoder:()=>Kt,CustomVideoEncoder:()=>qt,EncodedAudioPacketSource:()=>Bt,EncodedPacket:()=>M,EncodedPacketSink:()=>ge,EncodedVideoPacketSource:()=>Ot,Input:()=>Wt,InputAudioTrack:()=>Y,InputFormat:()=>ke,InputTrack:()=>Ke,InputVideoTrack:()=>le,IsobmffInputFormat:()=>Ut,IsobmffOutputFormat:()=>Rt,MATROSKA:()=>En,MP3:()=>An,MP4:()=>Pn,MatroskaInputFormat:()=>zt,MediaSource:()=>nt,MediaStreamAudioTrackSource:()=>Si,MediaStreamVideoTrackSource:()=>Ti,MkvOutputFormat:()=>Ft,MovOutputFormat:()=>Ye,Mp3InputFormat:()=>pr,Mp3OutputFormat:()=>gi,Mp4InputFormat:()=>lr,Mp4OutputFormat:()=>cr,NON_PCM_AUDIO_CODECS:()=>ye,OGG:()=>Fn,OggInputFormat:()=>gr,OggOutputFormat:()=>ki,Output:()=>Dt,OutputFormat:()=>be,PCM_AUDIO_CODECS:()=>U,QTFF:()=>In,QUALITY_HIGH:()=>jt,QUALITY_LOW:()=>ia,QUALITY_MEDIUM:()=>na,QUALITY_VERY_HIGH:()=>aa,QUALITY_VERY_LOW:()=>ra,Quality:()=>K,QuickTimeInputFormat:()=>mr,SUBTITLE_CODECS:()=>oe,Source:()=>Pe,StreamSource:()=>vi,StreamTarget:()=>jr,SubtitleSource:()=>st,Target:()=>Ne,TextSubtitleSource:()=>Ci,UrlSource:()=>Ii,VIDEO_CODECS:()=>$,VideoSample:()=>se,VideoSampleSink:()=>rt,VideoSampleSource:()=>Mt,VideoSource:()=>xe,WAVE:()=>Rn,WEBM:()=>_n,WavOutputFormat:()=>bi,WaveInputFormat:()=>hr,WebMInputFormat:()=>fr,WebMOutputFormat:()=>et,canEncode:()=>sa,canEncodeAudio:()=>Xt,canEncodeSubtitles:()=>Yt,canEncodeVideo:()=>Gt,getEncodableAudioCodecs:()=>ht,getEncodableCodecs:()=>oa,getEncodableSubtitleCodecs:()=>qi,getEncodableVideoCodecs:()=>Qi,getFirstEncodableAudioCodec:()=>ca,getFirstEncodableSubtitleCodec:()=>da,getFirstEncodableVideoCodec:()=>Mr,registerDecoder:()=>$n,registerEncoder:()=>jn});function m(i){if(!i)throw new Error("Assertion failed.")}var De=i=>{let e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},z=i=>i&&i[i.length-1],Qe=i=>i>=0&&i<2**32,q=class i{constructor(e){this.bytes=e;this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(this.pos&7),a=(t&1<<r)>>r;return this.pos++,a}readBits(e){if(e===1)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new i(this.bytes);return e.pos=this.pos,e}},I=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},ct=i=>{let e=I(i);return(e&1)===0?-(e>>1):e+1>>1},Un=(i,e,t,r)=>{for(let a=e;a<t;a++){let n=Math.floor(a/8),s=i[n],o=7-(a&7);s&=~(1<<o),s|=(r&1<<t-a-1)>>t-a-1<<o,i[n]=s}},Q=i=>i instanceof Uint8Array?i:i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),ee=i=>i instanceof DataView?i:i instanceof ArrayBuffer?new DataView(i):new DataView(i.buffer,i.byteOffset,i.byteLength),pe=new TextEncoder,Vi=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),Ie={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},kr=Vi(Ie),Ee={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},wr=Vi(Ee),_e={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Tr=Vi(_e),yr=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,dt=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),ne=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e,t=new Promise(a=>{e=a}),r=this.currentPromise;return this.currentPromise=t,await r,e}},Ui=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),zi=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),H=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+a>>1,o=t(i[s]);o===e?(n=s,a=s-1):o<e?r=s+1:a=s-1}return n},V=(i,e,t)=>{let r=0,a=i.length-1,n=-1;for(;r<=a;){let s=r+(a-r+1)/2|0;t(i[s])<=e?(n=s,r=s+1):a=s-1}return n},he=(i,e,t)=>{let r=V(i,t(e),t);i.splice(r+1,0,e)},W=()=>{let i,e;return{promise:new Promise((r,a)=>{i=r,e=a}),resolve:i,reject:e}},zn=(i,e)=>{let t=i.indexOf(e);t!==-1&&i.splice(t,1)},Wi=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},Sr=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},Wn=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},Nn=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},Ae=i=>{throw new Error(`Unexpected value: ${i}`)},Ni=(i,e,t)=>{let r=i.getUint8(e),a=i.getUint8(e+1),n=i.getUint8(e+2);return t?r|a<<8|n<<16:r<<16|a<<8|n},Ln=(i,e,t)=>Ni(i,e,t)<<8>>8,Li=(i,e,t,r)=>{t=t>>>0,t=t&16777215,r?(i.setUint8(e,t&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t>>>16&255)):(i.setUint8(e,t>>>16&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t&255))},Hn=(i,e,t,r)=>{t=G(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Li(i,e,t,r)},Kn=(i,e,t,r)=>{r?(i.setUint32(e+0,t,!0),i.setInt32(e+4,Math.floor(t/2**32),!0)):(i.setInt32(e+0,Math.floor(t/2**32),!0),i.setUint32(e+4,t,!0))},Nt=(i,e)=>({async next(){let t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),G=(i,e,t)=>Math.max(e,Math.min(t,i)),te="und",ut=(i,e)=>{let t=10**e;return Math.round(i*t)/t},Lt=(i,e)=>Math.round(i/e)*e,Qn=i=>{let e=0;for(;i;)e++,i>>=1;return e},cs=/^[a-z]{3}$/,lt=i=>cs.test(i),Te=1e6*(1+Number.EPSILON),Ht=(i,e)=>{let t={...i};for(let r in e)typeof i[r]=="object"&&i[r]!==null&&typeof e[r]=="object"&&e[r]!==null?t[r]=Ht(i[r],e[r]):t[r]=e[r];return t},Cr=async(i,e,t)=>{let r=0;for(;;)try{return await fetch(i,e)}catch(a){r++;let n=t(r);if(n===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(n)||n<0)throw new TypeError("Retry delay must be a non-negative finite number.");n>0&&await new Promise(s=>setTimeout(s,1e3*n))}},qn=(i,e)=>{let t=i<0?-1:1;i=Math.abs(i);let r=0,a=1,n=1,s=0,o=i;for(;;){let c=Math.floor(o),u=c*n+r,d=c*s+a;if(d>e)return{numerator:t*n,denominator:s};if(r=n,a=s,n=u,s=d,o=1/(o-c),!isFinite(o))break}return{numerator:t*n,denominator:s}},Be=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Di=null,xr=()=>{if(Di!==null)return Di;let i=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i)&&!navigator.userAgent?.match(/crios/i)&&!navigator.userAgent?.match(/fxios/i)&&!navigator.userAgent?.match(/Opera|OPT\//));return Di=i,i};var Kt=class{static supports(e,t){return!1}},Qt=class{static supports(e,t){return!1}},qt=class{static supports(e,t){return!1}},$t=class{static supports(e,t){return!1}},mt=[],ft=[],qe=[],$e=[],$n=i=>{if(i.prototype instanceof Kt){let e=i;if(mt.includes(e)){console.warn("Video decoder already registered.");return}mt.push(e)}else if(i.prototype instanceof Qt){let e=i;if(ft.includes(e)){console.warn("Audio decoder already registered.");return}ft.push(e)}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},jn=i=>{if(i.prototype instanceof qt){let e=i;if(qe.includes(e)){console.warn("Video encoder already registered.");return}qe.push(e)}else if(i.prototype instanceof $t){let e=i;if($e.includes(e)){console.warn("Audio encoder already registered.");return}$e.push(e)}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var $=["avc","hevc","vp9","av1","vp8"],U=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],ye=["aac","opus","mp3","vorbis","flac"],X=[...ye,...U],oe=["webvtt"],Gn=[{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}],Xn=[{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}],Re=[{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}],Yn=[{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",Jn=".0.110.01.01.01.0",vr=(i,e,t,r)=>{if(i==="avc"){let n=Math.ceil(e/16)*Math.ceil(t/16),s=Gn.find(l=>n<=l.maxMacroblocks&&r<=l.maxBitrate)??z(Gn),o=s?s.level:0,c="64".padStart(2,"0"),u="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${u}${d}`}else if(i==="hevc"){let a="",s="6",o=e*t,c=Xn.find(d=>o<=d.maxPictureSize&&r<=d.maxBitrate)??z(Xn);return`hev1.${a}1.${s}.${c.tier}${c.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",n=e*t,s=Re.find(c=>n<=c.maxPictureSize&&r<=c.maxBitrate)??z(Re);return`vp09.${a}.${s.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let n=e*t,s=Yn.find(u=>n<=u.maxPictureSize&&r<=u.maxBitrate)??z(Yn);return`av01.0.${s.level.toString().padStart(2,"0")}${s.tier}.08`}}throw new TypeError(`Unhandled codec '${i}'.`)},ea=i=>{let e=i.split("."),t=Number(e[1]),r=Number(e[2]),a=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,a,4,1,n]},_r=i=>{let e=i.split("."),a=(1<<7)+1,n=Number(e[1]),s=e[2],o=Number(s.slice(0,-1)),c=(n<<5)+o,u=s.slice(-1)==="H"?1:0,l=Number(e[3])===8?0:1,p=0,h=e[4]?Number(e[4]):0,f=e[5]?Number(e[5][0]):1,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]},Ar=i=>{let{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:n,vp9CodecInfo:s,av1CodecInfo:o}=i;if(e==="avc"){if(a){let c=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc1.${Ui(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.${Ui(t.subarray(1,4))}`}else if(e==="hevc"){let c,u,d,l,p,h;if(n)c=n.generalProfileSpace,u=n.generalProfileIdc,d=zi(n.generalProfileCompatibilityFlags),l=n.generalTierFlag,p=n.generalLevelIdc,h=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let k=ee(t),g=k.getUint8(1);c=g>>6&3,u=g&31,d=zi(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=i.width*i.height,w=z(Re).level;for(let C of Re)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=i.width*i.height,x=z(Re).level;for(let y of Re)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?Ie[r.primaries]:1,k=r?.transfer?Ee[r.transfer]:1,g=r?.matrix?_e[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(Jn)&&(w=w.slice(0,-Jn.length)),w}}throw new TypeError(`Unhandled codec '${e}'.`)},Pr=(i,e,t)=>{if(i==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(U.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Rr=i=>{let{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");return r.isMpeg2?"mp4a.67":`mp4a.40.${Hi(t).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&U.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Hi=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new q(i),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let r=e.readBits(4),a=null;if(r===15)a=e.readBits(24);else{let o=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r<o.length&&(a=o[r])}let n=e.readBits(4),s=null;return n>=1&&n<=7&&(s={1:1,2:2,3:3,4:4,5:5,6:6,7:8}[n]),{objectType:t,frequencyIndex:r,sampleRate:a,channelConfiguration:n,numberOfChannels:s}},pt=48e3,ta=/^pcm-([usf])(\d+)+(be)?$/,J=i=>{if(m(U.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=ta.exec(i);m(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let r=Number(e[2])/8,a=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:a,silentValue:n}},Ki=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":i.startsWith("mp4a.40")||i==="mp4a.67"?"aac":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp3":i==="opus"?"opus":i==="vorbis"?"vorbis":i==="flac"?"flac":i==="ulaw"?"ulaw":i==="alaw"?"alaw":ta.test(i)?i:i==="webvtt"?"webvtt":null,Ir=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},Er=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},K=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){let a=t*r,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},s=1920*1080,o=3e6,c=Math.pow(a/s,.95),l=o*c*n[e]*this._factor;return Math.ceil(l/1e3)*1e3}_toAudioBitrate(e){if(U.includes(e)||e==="flac")return;let r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!r)throw new Error(`Unhandled codec: ${e}`);let a=r*this._factor;return e==="aac"?a=[96e3,128e3,16e4,192e3].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s):e==="opus"||e==="vorbis"?a=Math.max(6e3,a):e==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((s,o)=>Math.abs(o-a)<Math.abs(s-a)?o:s)),Math.round(a/1e3)*1e3}},ra=new K(.3),ia=new K(.6),na=new K(1),jt=new K(2),aa=new K(4),ds=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],us=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ls=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ms=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,fs=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Fr=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ds.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.description!==void 0&&!dt(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(Ie);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(Ee);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(_e);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!us.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!ls.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!ms.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(i.decoderConfig.codec.startsWith("av01")&&!fs.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},ps=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],Ve=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ps.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!dt(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!i.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!U.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${U.join(", ")}).`)},Or=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},sa=i=>{if($.includes(i))return Gt(i);if(X.includes(i))return Xt(i);if(oe.includes(i))return Yt(i);throw new TypeError(`Unknown codec '${i}'.`)},Gt=async(i,{width:e=1280,height:t=720,bitrate:r=1e6}={})=>{if(!$.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("height must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");let a=r instanceof K?r._toVideoBitrate(i,e,t):r;if(qe.length>0){let s={codec:vr(i,e,t,a),width:e,height:t,bitrate:a,...Ir(i)};if(qe.some(o=>o.supports(i,s)))return!0}return typeof VideoEncoder>"u"?!1:(await VideoEncoder.isConfigSupported({codec:vr(i,e,t,a),width:e,height:t,bitrate:a,...Ir(i)})).supported===!0},Xt=async(i,{numberOfChannels:e=2,sampleRate:t=48e3,bitrate:r=128e3}={})=>{if(!X.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(t)||t<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");let a=r instanceof K?r._toAudioBitrate(i):r;if($e.length>0){let s={codec:Pr(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...Er(i)};if($e.some(o=>o.supports(i,s)))return!0}return U.includes(i)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported({codec:Pr(i,e,t),numberOfChannels:e,sampleRate:t,bitrate:a,...Er(i)})).supported===!0},Yt=async i=>!!oe.includes(i),oa=async()=>{let[i,e,t]=await Promise.all([Qi(),ht(),qi()]);return[...i,...e,...t]},Qi=async(i=$,e)=>{let t=await Promise.all(i.map(r=>Gt(r,e)));return i.filter((r,a)=>t[a])},ht=async(i=X,e)=>{let t=await Promise.all(i.map(r=>Xt(r,e)));return i.filter((r,a)=>t[a])},qi=async(i=oe)=>{let e=await Promise.all(i.map(Yt));return i.filter((t,r)=>e[r])},Mr=async(i,e)=>{for(let t of i)if(await Gt(t,e))return t;return null},ca=async(i,e)=>{for(let t of i)if(await Xt(t,e))return t;return null},da=async i=>{for(let e of i)if(await Yt(e))return e;return null};var Zt=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,hs=/^WEBVTT(.|\n)*?\n{2}/,gt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Br=class{constructor(e){this.preambleText=null;this.preambleEmitted=!1;this.options=e}parse(e){e=e.replaceAll(`\r
`,`
`).replaceAll("\r",`
`),Zt.lastIndex=0;let t;if(!this.preambleText){if(!hs.test(e))throw new Error("WebVTT preamble incorrect.");t=Zt.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),Zt.lastIndex=0)}for(;t=Zt.exec(e);){let r=e.slice(0,t.index),a=t[1],n=t.index+t[0].length,s=e.indexOf(`
`,n)+1,o=e.slice(n,s).trim(),c=e.indexOf(`
`,n);c===-1&&(c=e.length);let u=Dr(t[2]),l=Dr(t[3])-u,p=e.slice(s,c).trim();e=e.slice(c).trimStart(),Zt.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)}}},gs=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Dr=i=>{let e=gs.exec(i);if(!e)throw new Error("Expected match.");return 60*60*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},Vr=i=>{let e=Math.floor(i/36e5),t=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),a=i%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var Jt=i=>{let e=[],t=0;for(;t<i.length;){let r=-1,a=0;for(let n=t;n<i.length-3;n++){if(i[n]===0&&i[n+1]===0&&i[n+2]===1){r=n,a=3;break}if(n<i.length-4&&i[n]===0&&i[n+1]===0&&i[n+2]===0&&i[n+3]===1){r=n,a=4;break}}if(r===-1)break;if(t>0&&r>t){let n=i.subarray(t,r);n.length>0&&e.push(n)}t=r+a}if(t<i.length){let r=i.subarray(t);r.length>0&&e.push(r)}return e},ua=(i,e)=>{let t=[],r=0,a=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;r+e<=i.length;){let n;e===1?n=a.getUint8(r):e===2?n=a.getUint16(r,!1):e===3?n=(a.getUint16(r,!1)<<8)+a.getUint8(r+2):e===4?n=a.getUint32(r,!1):(Ae(e),m(!1)),r+=e;let s=i.subarray(r,r+n);t.push(s),r+=n}return t},$i=i=>{let e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)},ha=i=>{let t=Jt(i);if(t.length===0)return null;let r=0;for(let o of t)r+=4+o.byteLength;let a=new Uint8Array(r),n=new DataView(a.buffer),s=0;for(let o of t){let c=o.byteLength;n.setUint32(s,c,!1),s+=4,a.set(o,s),s+=o.byteLength}return a},Ur=i=>i[0]&31,zr=i=>{try{let e=Jt(i),t=e.filter(p=>Ur(p)===7),r=e.filter(p=>Ur(p)===8),a=e.filter(p=>Ur(p)===13);if(t.length===0||r.length===0)return null;let n=t[0],s=new q($i(n));if(s.skipBits(1),s.skipBits(2),s.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let c=s.readAlignedByte(),u=s.readAlignedByte(),d=s.readAlignedByte(),l={configurationVersion:1,avcProfileIndication:c,profileCompatibility:u,avcLevelIndication:d,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(c===100||c===110||c===122||c===144){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}},ga=i=>{let e=[];e.push(i.configurationVersion),e.push(i.avcProfileIndication),e.push(i.profileCompatibility),e.push(i.avcLevelIndication),e.push(252|i.lengthSizeMinusOne&3),e.push(224|i.sequenceParameterSets.length&31);for(let t of i.sequenceParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}e.push(i.pictureParameterSets.length);for(let t of i.pictureParameterSets){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}if(i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144){m(i.chromaFormat!==null),m(i.bitDepthLumaMinus8!==null),m(i.bitDepthChromaMinus8!==null),m(i.sequenceParameterSetExt!==null),e.push(252|i.chromaFormat&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.sequenceParameterSetExt.length);for(let t of i.sequenceParameterSetExt){let r=t.byteLength;e.push(r>>8),e.push(r&255);for(let a=0;a<r;a++)e.push(t[a])}}return new Uint8Array(e)},la=32,ma=33,fa=34,bs=39,ks=40,je=i=>i[0]>>1&63,Wr=i=>{try{let e=Jt(i),t=e.filter(A=>je(A)===la),r=e.filter(A=>je(A)===ma),a=e.filter(A=>je(A)===fa),n=e.filter(A=>je(A)===bs||je(A)===ks);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}=ws(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)&&Ts(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(ys(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=Cs(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(_),ct(_),_.skipBits(1),_.skipBits(1),_.readBits(1)&&I(_),ct(_),ct(_),_.skipBits(1),_.skipBits(1),_.skipBits(1),_.skipBits(1);let B=_.readBits(1),N=_.readBits(1);!B&&!N?S=0:B&&!N?S=2:!B&&N?S=3:S=0}let v=[...t.length?[{arrayCompleteness:1,nalUnitType:la,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ma,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:fa,nalUnits:a}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:je(n[0]),nalUnits:n}]:[]];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}},ws=(i,e)=>{let t=i.readBits(2),r=i.readBits(1),a=i.readBits(5),n=0;for(let d=0;d<32;d++)n=n<<1|i.readBits(1);let s=new Uint8Array(6);for(let d=0;d<6;d++)s[d]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let d=0;d<e;d++)c.push(i.readBits(1)),u.push(i.readBits(1));if(e>0)for(let d=e;d<8;d++)i.skipBits(2);for(let d=0;d<e;d++)c[d]&&i.skipBits(88),u[d]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:n,general_constraint_indicator_flags:s,general_level_idc:o}},Ts=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))I(i);else{let a=Math.min(64,1<<4+(e<<1));e>1&&ct(i);for(let n=0;n<a;n++)ct(i)}},ys=(i,e)=>{let t=[];for(let r=0;r<e;r++)t[r]=Ss(i,r,e,t)},Ss=(i,e,t,r)=>{let a=0,n=0,s=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){let c=I(i);s=e-(c+1)}else s=e-1;i.readBits(1),I(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);a=r[s]}else{let o=I(i),c=I(i);for(let u=0;u<o;u++)I(i),i.readBits(1);for(let u=0;u<c;u++)I(i),i.readBits(1);a=o+c}return a},Cs=(i,e)=>{if(i.readBits(1)&&i.readBits(8)===255&&(i.readBits(16),i.readBits(16)),i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),i.readBits(1),i.readBits(1)&&(i.readBits(8),i.readBits(8),i.readBits(8))),i.readBits(1)&&(I(i),I(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(I(i),I(i),I(i),I(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&I(i),i.readBits(1)&&xs(i,!0,e)),i.readBits(1)){i.readBits(1),i.readBits(1),i.readBits(1);let t=I(i);return I(i),I(i),I(i),I(i),t}return 0},xs=(i,e,t)=>{let r=!1,a=!1,n=!1;e&&(r=i.readBits(1)===1,a=i.readBits(1)===1,(r||a)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=t;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let u=!1;c?I(i):u=i.readBits(1)===1;let d=1;u||(d=I(i)+1),r&&pa(i,d,n),a&&pa(i,d,n)}},pa=(i,e,t)=>{for(let r=0;r<e;r++)I(i),I(i),t&&(I(i),I(i)),i.readBits(1)},ba=i=>{let e=[];e.push(i.configurationVersion),e.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),e.push(i.generalProfileCompatibilityFlags>>>24&255),e.push(i.generalProfileCompatibilityFlags>>>16&255),e.push(i.generalProfileCompatibilityFlags>>>8&255),e.push(i.generalProfileCompatibilityFlags&255),e.push(...i.generalConstraintIndicatorFlags),e.push(i.generalLevelIdc&255),e.push(240|i.minSpatialSegmentationIdc>>8&15),e.push(i.minSpatialSegmentationIdc&255),e.push(252|i.parallelismType&3),e.push(252|i.chromaFormatIdc&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.avgFrameRate>>8&255),e.push(i.avgFrameRate&255),e.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),e.push(i.arrays.length&255);for(let t of i.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let r of t.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let a=0;a<r.length;a++)e.push(r[a])}}return new Uint8Array(e)},Nr=i=>{let e=new q(i);if(e.readBits(2)!==2)return null;let r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;n>=2&&(u=e.readBits(1)?12:10);let d=e.readBits(3),l=0,p=0;if(d!==7)if(p=e.readBits(1),n===1||n===3){let 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=z(Re).level;for(let T of Re)if(b<=T.maxPictureSize){w=T.level;break}return{profile:n,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*ka(i){let e=new q(i),t=()=>{let r=0;for(let a=0;a<8;a++){let n=e.readAlignedByte();if(r|=(n&127)<<a*7,!(n&128))break;if(a===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);let r=e.readBits(4),a=e.readBits(1),n=e.readBits(1);e.skipBits(1),a&&e.skipBits(8);let s;if(n){let o=t();if(o===null)return;s=o}else s=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+s)},e.skipBits(s*8)}}var Lr=i=>{for(let{type:e,data:t}of ka(i)){if(e!==1)continue;let r=new q(t),a=r.readBits(3),n=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;let 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=i=>{let e=ee(i),t=e.getUint8(9),r=e.getUint16(10,!0),a=e.getUint32(12,!0),n=e.getInt16(16,!0),s=e.getUint8(18),o=null;return s&&(o=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:a,outputGain:n,channelMappingFamily:s,channelMappingTable:o}},vs=[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],wa=i=>{let e=i[0]>>3;return{durationInSamples:vs[e]}},Hr=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=i.length,r=new Uint8Array(t);for(let l=0;l<t;l++)r[l]=i[t-1-l];let a=new q(r),n=0;for(;a.getBitsLeft()>97;)if(a.readBits(1)===1){n=a.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;a.getBitsLeft()>=97;){let l=a.pos,p=a.readBits(8),h=a.readBits(16),f=a.readBits(16);if(p>63||h!==0||f!==0){a.pos=l;break}if(a.skipBits(1),s++,s>64)break;a.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let u=c;a.pos=0,a.skipBits(n);let d=Array(u).fill(0);for(let l=u-1;l>=0;l--)a.skipBits(40),d[l]=a.readBits(1);return{modeBlockflags:d}},Ta=async(i,e)=>{switch(m(i.codec),i.codec){case"avc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(Q(t.description)[4]&3)+1;r=ua(e.data,o)}else r=Jt(e.data);return r.some(n=>Ur(n)===5)?"key":"delta"}case"hevc":{let t=await i.getDecoderConfig();m(t);let r;if(t.description){let o=(Q(t.description)[21]&3)+1;r=ua(e.data,o)}else r=Jt(e.data);return r.some(n=>{let s=je(n);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 ka(e.data))if(r===1){let n=new q(a);n.skipBits(4),t=!!n.readBits(1)}else if(r===3||r===6||r===7){if(t)return"key";let n=new q(a);return n.readBits(1)?null:n.readBits(2)===0?"key":"delta"}return null}default:Ae(i.codec),m(!1)}};var er=class{constructor(e){this.writer=e;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let r=this.writer.getPos(),a=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,a),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);m(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let r of e.children)r&&(t+=this.measureBox(r));return t}}},O=new Uint8Array(8),Ce=new DataView(O.buffer),L=i=>[(i%256+256)%256],R=i=>(Ce.setUint16(0,i,!1),[O[0],O[1]]),Sa=i=>(Ce.setInt16(0,i,!1),[O[0],O[1]]),Ca=i=>(Ce.setUint32(0,i,!1),[O[1],O[2],O[3]]),P=i=>(Ce.setUint32(0,i,!1),[O[0],O[1],O[2],O[3]]),We=i=>(Ce.setInt32(0,i,!1),[O[0],O[1],O[2],O[3]]),Ge=i=>(Ce.setUint32(0,Math.floor(i/2**32),!1),Ce.setUint32(4,i,!1),[O[0],O[1],O[2],O[3],O[4],O[5],O[6],O[7]]),xa=i=>(Ce.setInt16(0,2**8*i,!1),[O[0],O[1]]),Fe=i=>(Ce.setInt32(0,2**16*i,!1),[O[0],O[1],O[2],O[3]]),ji=i=>(Ce.setInt32(0,2**30*i,!1),[O[0],O[1],O[2],O[3]]),Gi=(i,e)=>{let t=[],r=i;do{let a=r&127;r>>=7,t.length>0&&(a|=128),t.push(a),e!==void 0&&e--}while(r>0||e);return t.reverse()},re=(i,e=!1)=>{let t=Array(i.length).fill(null).map((r,a)=>i.charCodeAt(a));return e&&t.push(0),t},Yi=i=>{let e=null;for(let t of i)(!e||t.timestamp>e.timestamp)&&(e=t);return e},va=i=>{let e=i*(Math.PI/180),t=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[t,r,0,-r,t,0,0,0,1]},Pa=va(0),Ia=i=>[Fe(i[0]),Fe(i[1]),ji(i[2]),Fe(i[3]),Fe(i[4]),ji(i[5]),Fe(i[6]),Fe(i[7]),ji(i[8])],F=(i,e,t)=>({type:i,contents:e&&new Uint8Array(e.flat(10)),children:t}),D=(i,e,t,r,a)=>F(i,[L(e),Ca(t),r??[]],a),Ea=i=>i.isQuickTime?F("ftyp",[re("qt "),P(512),re("qt ")]):i.fragmented?F("ftyp",[re("iso5"),P(512),re("iso5"),re("iso6"),re("mp41")]):F("ftyp",[re("isom"),P(512),re("isom"),i.holdsAvc?re("avc1"):[],re("mp41")]),Qr=i=>({type:"mdat",largeSize:i}),tr=(i,e,t=!1)=>F("moov",void 0,[Ps(e,i),...i.map(r=>Is(r,e)),t?uo(i):null]),Ps=(i,e)=>{let t=j(Math.max(0,...e.filter(s=>s.samples.length>0).map(s=>{let o=Yi(s.samples);return o.timestamp+o.duration})),Kr),r=Math.max(0,...e.map(s=>s.track.id))+1,a=!Qe(i)||!Qe(t),n=a?Ge:P;return D("mvhd",+a,0,[n(i),n(i),P(Kr),n(t),Fe(1),xa(1),Array(10).fill(0),Ia(Pa),Array(24).fill(0),P(r)])},Is=(i,e)=>F("trak",void 0,[Es(i,e),_s(i,e)]),Es=(i,e)=>{let t=Yi(i.samples),r=j(t?t.timestamp+t.duration:0,Kr),a=!Qe(e)||!Qe(r),n=a?Ge:P,s;if(i.type==="video"){let o=i.track.metadata.rotation;s=va(o??0)}else s=Pa;return D("tkhd",+a,3,[n(e),n(e),P(i.track.id),P(0),n(r),Array(8).fill(0),R(0),R(i.track.id),xa(i.type==="audio"?1:0),R(0),Ia(s),Fe(i.type==="video"?i.info.width:0),Fe(i.type==="video"?i.info.height:0)])},_s=(i,e)=>F("mdia",void 0,[As(i,e),Os(i),Ms(i)]),As=(i,e)=>{let t=Yi(i.samples),r=j(t?t.timestamp+t.duration:0,i.timescale),a=!Qe(e)||!Qe(r),n=a?Ge:P,s=0;for(let o of i.track.metadata.languageCode??te)s<<=5,s+=o.charCodeAt(0)-96;return D("mdhd",+a,0,[n(e),n(e),P(i.timescale),n(r),R(s),R(0)])},Rs={video:"vide",audio:"soun",subtitle:"text"},Fs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Os=i=>D("hdlr",0,0,[re("mhlr"),re(Rs[i.type]),P(0),P(0),P(0),re(Fs[i.type],!0)]),Ms=i=>F("minf",void 0,[Us[i.type](),zs(),Ls(i)]),Bs=()=>D("vmhd",0,1,[R(0),R(0),R(0),R(0)]),Ds=()=>D("smhd",0,0,[R(0),R(0)]),Vs=()=>D("nmhd",0,0),Us={video:Bs,audio:Ds,subtitle:Vs},zs=()=>F("dinf",void 0,[Ws()]),Ws=()=>D("dref",0,0,[P(1)],[Ns()]),Ns=()=>D("url ",0,1),Ls=i=>{let e=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return F("stbl",void 0,[Hs(i),ro(i),e?oo(i):null,e?co(i):null,no(i),ao(i),so(i),io(i)])},Hs=i=>{let e;if(i.type==="video")e=Ks(wo[i.track.source._codec],i);else if(i.type==="audio"){let t=Ma(i.track.source._codec,i.muxer.isQuickTime);m(t),e=Gs(t,i)}else i.type==="subtitle"&&(e=eo(So[i.track.source._codec],i));return m(e),D("stsd",0,0,[P(1)],[e])},Ks=(i,e)=>F(i,[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),Sa(65535)],[To[e.track.source._codec](e),yr(e.info.decoderConfig.colorSpace)?Qs(e):null]),Qs=i=>F("colr",[re("nclx"),R(Ie[i.info.decoderConfig.colorSpace.primaries]),R(Ee[i.info.decoderConfig.colorSpace.transfer]),R(_e[i.info.decoderConfig.colorSpace.matrix]),L((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),qs=i=>i.info.decoderConfig&&F("avcC",[...Q(i.info.decoderConfig.description)]),$s=i=>i.info.decoderConfig&&F("hvcC",[...Q(i.info.decoderConfig.description)]),ya=i=>{if(!i.info.decoderConfig)return null;let e=i.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),a=Number(t[2]),n=Number(t[3]),s=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(s<<1)+o,u=t[5]?Number(t[5]):e.colorSpace?.primaries?Ie[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?Ee[e.colorSpace.transfer]:2,l=t[7]?Number(t[7]):e.colorSpace?.matrix?_e[e.colorSpace.matrix]:2;return D("vpcC",1,0,[L(r),L(a),L(c),L(u),L(d),L(l),R(0)])},js=i=>F("av1C",_r(i.info.decoderConfig.codec)),Gs=(i,e)=>{let t=0,r,a=16;if(U.includes(e.track.source._codec)){let n=e.track.source._codec,{sampleSize:s}=J(n);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(i,r,[yo(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Xi=i=>{let e;switch(i.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let t=[...L(e),...L(21),...Ca(0),...P(0),...P(0)];if(i.info.decoderConfig.description){let r=Q(i.info.decoderConfig.description);t=[...t,...L(5),...Gi(r.byteLength),...r]}return t=[...R(1),...L(0),...L(4),...Gi(t.length),...t,...L(6),...L(1),...L(2)],t=[...L(3),...Gi(t.length),...t],D("esds",0,0,t)},ze=i=>F("wave",void 0,[Xs(i),Ys(i),F("\0\0\0\0")]),Xs=i=>F("frma",[re(Ma(i.track.source._codec,i.muxer.isQuickTime))]),Ys=i=>{let{littleEndian:e}=J(i.track.source._codec);return F("enda",[R(+e)])},Zs=i=>{let e=i.info.numberOfChannels,t=3840,r=i.info.sampleRate,a=0,n=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){m(o.byteLength>=18);let c=Q(o),u=Ue(c);e=u.outputChannelCount,t=u.preSkip,r=u.inputSampleRate,a=u.outputGain,n=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return F("dOps",[L(0),L(e),R(t),P(r),Sa(a),L(n),...s])},Js=i=>{let e=i.info.decoderConfig?.description;m(e);let t=Q(e);return D("dfLa",0,0,[...t.subarray(4)])},Se=i=>{let{littleEndian:e,sampleSize:t}=J(i.track.source._codec),r=+e;return D("pcmC",0,0,[L(r),L(8*t)])},eo=(i,e)=>F(i,[Array(6).fill(0),R(1)],[Co[e.track.source._codec](e)]),to=i=>F("vttC",[...pe.encode(i.info.config.description)]);var ro=i=>D("stts",0,0,[P(i.timeToSampleTable.length),i.timeToSampleTable.map(e=>[P(e.sampleCount),P(e.sampleDelta)])]),io=i=>{if(i.samples.every(t=>t.type==="key"))return null;let e=[...i.samples.entries()].filter(([,t])=>t.type==="key");return D("stss",0,0,[P(e.length),e.map(([t])=>P(t+1))])},no=i=>D("stsc",0,0,[P(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(e=>[P(e.firstChunk),P(e.samplesPerChunk),P(1)])]),ao=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:e}=J(i.track.source._codec);return D("stsz",0,0,[P(e*i.info.numberOfChannels),P(i.samples.reduce((t,r)=>t+j(r.duration,i.timescale),0))])}return D("stsz",0,0,[P(0),P(i.samples.length),i.samples.map(e=>P(e.size))])},so=i=>i.finalizedChunks.length>0&&z(i.finalizedChunks).offset>=2**32?D("co64",0,0,[P(i.finalizedChunks.length),i.finalizedChunks.map(e=>Ge(e.offset))]):D("stco",0,0,[P(i.finalizedChunks.length),i.finalizedChunks.map(e=>P(e.offset))]),oo=i=>D("ctts",1,0,[P(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(e=>[P(e.sampleCount),We(e.sampleCompositionTimeOffset)])]),co=i=>{let e=1/0,t=-1/0,r=1/0,a=-1/0;m(i.compositionTimeOffsetTable.length>0),m(i.samples.length>0);for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,j(o.timestamp,i.timescale)),a=Math.max(a,j(o.timestamp+o.duration,i.timescale))}let n=Math.max(-e,0);return a>=2**31?null:D("cslg",0,0,[We(n),We(e),We(t),We(r),We(a)])},uo=i=>F("mvex",void 0,i.map(lo)),lo=i=>D("trex",0,0,[P(i.track.id),P(1),P(0),P(0),P(0)]),Zi=(i,e)=>F("moof",void 0,[mo(i),...e.map(fo)]),mo=i=>D("mfhd",0,0,[P(i)]),_a=i=>{let e=0,t=0,r=0,a=0,n=i.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|r<<8|a},fo=i=>F("traf",void 0,[po(i),ho(i),go(i)]),po=i=>{m(i.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:_a(t)};return D("tfhd",0,e,[P(i.track.id),P(r.duration),P(r.size),P(r.flags)])},ho=i=>(m(i.currentChunk),D("tfdt",1,0,[Ge(j(i.currentChunk.startTimestamp,i.timescale))])),go=i=>{m(i.currentChunk);let e=i.currentChunk.samples.map(k=>k.timescaleUnitsToNextSample),t=i.currentChunk.samples.map(k=>k.size),r=i.currentChunk.samples.map(_a),a=i.currentChunk.samples.map(k=>j(k.timestamp-k.decodeTimestamp,i.timescale)),n=new Set(e),s=new Set(t),o=new Set(r),c=new Set(a),u=o.size===2&&r[0]!==r[1],d=n.size>1,l=s.size>1,p=!u&&o.size>1,h=c.size>1||[...c].some(k=>k!==0),f=0;return f|=1,f|=4*+u,f|=256*+d,f|=512*+l,f|=1024*+p,f|=2048*+h,D("trun",1,f,[P(i.currentChunk.samples.length),P(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?P(r[0]):[],i.currentChunk.samples.map((k,g)=>[d?P(e[g]):[],l?P(t[g]):[],p?P(r[g]):[],h?We(a[g]):[]])])},Aa=i=>F("mfra",void 0,[...i.map(bo),ko()]),bo=(i,e)=>D("tfra",1,0,[P(i.track.id),P(63),P(i.finalizedChunks.length),i.finalizedChunks.map(r=>[Ge(j(r.samples[0].timestamp,i.timescale)),Ge(r.moofOffset),P(e+1),P(1),P(1)])]),ko=()=>D("mfro",0,0,[P(0)]),Ra=()=>F("vtte"),Fa=(i,e,t,r,a)=>F("vttc",void 0,[a!==null?F("vsid",[We(a)]):null,t!==null?F("iden",[...pe.encode(t)]):null,e!==null?F("ctim",[...pe.encode(Vr(e))]):null,r!==null?F("sttg",[...pe.encode(r)]):null,F("payl",[...pe.encode(i)])]),Oa=i=>F("vtta",[...pe.encode(i)]),wo={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},To={avc:qs,hevc:$s,vp8:ya,vp9:ya,av1:js},Ma=(i,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},yo=(i,e)=>{switch(i){case"aac":return Xi;case"mp3":return Xi;case"opus":return Zs;case"vorbis":return Xi;case"flac":return Js}if(e)switch(i){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(i){case"pcm-s16":return Se;case"pcm-s16be":return Se;case"pcm-s24":return Se;case"pcm-s24be":return Se;case"pcm-s32":return Se;case"pcm-s32be":return Se;case"pcm-f32":return Se;case"pcm-f32be":return Se;case"pcm-f64":return Se;case"pcm-f64be":return Se}return null},So={webvtt:"wvtt"},Co={webvtt:to};var de=class{constructor(e){this.mutex=new ne;this.firstMediaStreamTimestamp=null;this.trackTimestampInfo=new WeakMap;this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let a=this.trackTimestampInfo.get(e);if(!a){if(!r)throw new Error("First frame must be a key frame.");a={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,a)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(a.maxTimestampBeforeLastKeyFrame=a.maxTimestamp),t<a.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous run (a run begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${a.maxTimestampBeforeLastKeyFrame}s.`);return a.maxTimestamp=Math.max(a.maxTimestamp,t),t}};var qr=class{constructor(){this.ensureMonotonicity=!1;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let r=t+e.byteLength-this.trackedStart,a=this.trackedWrites.byteLength;for(;a<r;)a*=2;if(a!==this.trackedWrites.byteLength){let n=new Uint8Array(a);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},Ji=2**16,en=2**32,bt=class extends qr{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(Ji,{maxByteLength:en})}catch{this.buffer=new ArrayBuffer(Ji),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Ji);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>en)throw new Error(`ArrayBuffer exceeded maximum size of ${en} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(r);else{let a=new ArrayBuffer(r),n=new Uint8Array(a);n.set(this.bytes,0),this.buffer=a,this.bytes=n}}}write(t){this.maybeTrackWrites(t),this.ensureSize(this.pos+t.byteLength),this.bytes.set(t,this.pos),this.pos+=t.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(t,r){return this.bytes.slice(t,r)}},xo=2**24,vo=2,$r=class extends qr{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??xo}start(){this.writer=this.target._writable.getWriter()}write(t){if(this.pos>this.lastWriteEnd){let r=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(r))}this.maybeTrackWrites(t),this.sections.push({data:t.slice(),start:this.pos}),this.pos+=t.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(t){this.pos=t}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let a=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(a))}if(m(this.writer),this.sections.length===0)return;let t=[],r=[...this.sections].sort((a,n)=>a.start-n.start);t.push({start:r[0].start,size:r[0].data.byteLength});for(let a=1;a<r.length;a++){let n=t[t.length-1],s=r[a];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):t.push({start:s.start,size:s.data.byteLength})}for(let a of t){a.data=new Uint8Array(a.size);for(let n of this.sections)a.start<=n.start&&n.start<a.start+a.size&&a.data.set(n.data,n.start-a.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(a.data,a.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&a.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data,position:a.start}),this.lastFlushEnd=a.start+a.data.byteLength}}this.sections.length=0}writeDataIntoChunks(t,r){let a=this.chunks.findIndex(u=>u.start<=r&&r<u.start+this.chunkSize);a===-1&&(a=this.createChunk(r));let n=this.chunks[a],s=r-n.start,o=t.subarray(0,Math.min(this.chunkSize-s,t.byteLength));n.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this.insertSectionIntoChunk(n,c),n.written[0].start===0&&n.written[0].end===this.chunkSize&&(n.shouldFlush=!0),this.chunks.length>vo){for(let u=0;u<this.chunks.length-1;u++)this.chunks[u].shouldFlush=!0;this.tryToFlushChunks()}o.byteLength<t.byteLength&&this.writeDataIntoChunks(t.subarray(o.byteLength),r+o.byteLength)}insertSectionIntoChunk(t,r){let a=0,n=t.written.length-1,s=-1;for(;a<=n;){let o=Math.floor(a+(n-a+1)/2);t.written[o].start<=r.start?(a=o+1,s=o):n=o-1}for(t.written.splice(s+1,0,r),(s===-1||t.written[s].end<r.start)&&s++;s<t.written.length-1&&t.written[s].end>=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)}createChunk(t){let a={start:Math.floor(t/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(a),this.chunks.sort((n,s)=>n.start-s.start),this.chunks.indexOf(a)}tryToFlushChunks(t=!1){m(this.writer);for(let r=0;r<this.chunks.length;r++){let a=this.chunks[r];if(!(!a.shouldFlush&&!t)){for(let n of a.written){let s=a.start+n.start;if(this.ensureMonotonicity&&s!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:a.data.subarray(n.start,n.end),position:s}),this.lastFlushEnd=a.start+n.end}this.chunks.splice(r--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),m(this.writer),this.writer.close()}async close(){return this.writer?.close()}};var Ne=class{constructor(){this._output=null}},kt=class extends Ne{constructor(){super(...arguments);this.buffer=null}_createWriter(){return new bt(this)}},jr=class extends Ne{constructor(e,t={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t}_createWriter(){return new $r(this)}};var Gr=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t};var wt=8,Le=16,Xe=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos++,e.getUint8(t)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readI16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getInt16(t,!1)}readU24(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+3);this.pos+=3;let r=e.getUint16(t,!1),a=e.getUint8(t+2);return r*256+a}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!1)}readU64(){let e=this.readU32(),t=this.readU32();return e*4294967296+t}readI64(){let e=this.readI32(),t=this.readU32();return e*4294967296+t}readF64(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+8);return this.pos+=8,e.getFloat64(t,!1)}readFixed_16_16(){return this.readI32()/65536}readFixed_2_30(){return this.readI32()/1073741824}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readIsomVariableInteger(){let e=0;for(let t=0;t<4;t++){e<<=7;let r=this.readU8();if(e|=r&127,(r&128)===0)break}return e}readBoxHeader(){let e=this.readU32(),t=this.readAscii(4),r=8;return e===1&&(e=this.readU64(),r=16),{name:t,totalSize:e,headerSize:r,contentSize:e-r}}};var Kr=1e3,Po=2082844800,j=(i,e,t=!0)=>{let r=i*e;return t?Math.round(r):r},Xr=class extends de{constructor(t,r){super(t);this.auxTarget=new kt;this.auxWriter=this.auxTarget._createWriter();this.auxBoxWriter=new er(this.auxWriter);this.mdat=null;this.trackDatas=[];this.allTracksKnown=W();this.creationTime=Math.floor(Date.now()/1e3)+Po;this.finalizedChunks=[];this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.format=r,this.writer=t._writer,this.boxWriter=new er(this.writer),this.isQuickTime=r instanceof Ye;let a=this.writer instanceof bt?"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(Ea({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:a,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(a,n)}this.fastStart==="in-memory"?this.mdat=Qr(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Qr(!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 Gr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r,a){let n=this.trackDatas.find(d=>d.track===t);if(n)return n;Fr(a),m(a),m(a.decoderConfig);let s={...a.decoderConfig};m(s.codedWidth!==void 0),m(s.codedHeight!==void 0);let o=!1;if(t.source._codec==="avc"&&!s.description){let d=zr(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=ga(d),o=!0}else if(t.source._codec==="hevc"&&!s.description){let d=Wr(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=ba(d),o=!0}let c=qn(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 n={muxer:this,track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&U.includes(t.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Or(r),m(r),m(r.config);let n={muxer:this,track:t,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,r,a),o=r.data;if(s.info.requiresAnnexBTransformation){let d=ha(o);if(!d)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=d}let c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.createSampleForTrack(s,o,c,r.duration,r.type);await this.registerSample(s,u)}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),c=this.createSampleForTrack(s,r.data,o,r.duration,r.type);s.info.requiresPcmTransformation&&await this.maybePadWithSilence(s,o),await this.registerSample(s,c)}finally{n()}}async maybePadWithSilence(t,r){let a=z(t.samples),n=a?a.timestamp+a.duration:0,s=r-n,o=j(s,t.timescale);if(o>0){let{sampleSize:c,silentValue:u}=J(t.info.decoderConfig.codec),d=o*t.info.numberOfChannels,l=new Uint8Array(c*d).fill(u),p=this.createSampleForTrack(t,new Uint8Array(l.buffer),n,s,"key");await this.registerSample(t,p)}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),t.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(t,r){for(;t.cueQueue.length>0;){let a=new Set([]);for(let d of t.cueQueue)m(d.timestamp<=r),m(t.lastCueEndTimestamp<=d.timestamp+d.duration),a.add(Math.max(d.timestamp,t.lastCueEndTimestamp)),a.add(d.timestamp+d.duration);let n=[...a].sort((d,l)=>d-l),s=n[0],o=n[1]??s;if(r<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);let d=Ra();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;gt.lastIndex=0;let p=gt.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=Oa(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,n,s){return{timestamp:a,decodeTimestamp:a,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:j(n,t.timescale)}}processTimestamps(t,r){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){let n=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){let o=t.timestampProcessingQueue[s],c=j(o.duration,t.timescale);n+=c}if(t.timeToSampleTable.length===0)t.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{let s=z(t.timeToSampleTable);s.sampleCount+=n}t.timestampProcessingQueue.length=0;return}let a=t.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);for(let n=0;n<t.timestampProcessingQueue.length;n++){let s=t.timestampProcessingQueue[n];s.decodeTimestamp=a[n],!this.isFragmented&&t.lastTimescaleUnits===null&&(s.decodeTimestamp=0);let o=j(s.timestamp-s.decodeTimestamp,t.timescale),c=j(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){m(t.lastSample);let u=j(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=z(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=z(t.compositionTimeOffsetTable);m(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=j(s.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));t.lastSample=s}if(t.timestampProcessingQueue.length=0,m(t.lastSample),m(t.lastTimescaleUnits!==null),r!==void 0&&t.lastSample.timescaleUnitsToNextSample===0){m(r.type==="key");let n=j(r.timestamp,t.timescale,!1),s=Math.round(n-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=s}}async registerSample(t,r){r.type==="key"&&this.processTimestamps(t,r),t.timestampProcessingQueue.push(r),this.isFragmented?(t.sampleQueue.push(r),await this.interleaveSamples()):await this.addSampleToTrack(t,r)}async addSampleToTrack(t,r){this.isFragmented||t.samples.push(r);let a=!1;if(!t.currentChunk)a=!0;else{t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,r.timestamp);let n=r.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(t===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.track.source._closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(a=!0,await this.finalizeFragment())}else a=n>=.5}a&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),m(t.currentChunk),t.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(t){if(m(!this.isFragmented),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let r=t.currentChunk.samples.length;if(t.type==="audio"&&t.info.requiresPcmTransformation&&(r=t.currentChunk.samples.reduce((a,n)=>a+j(n.duration,t.timescale),0)),(t.compactlyCodedChunkTable.length===0||z(t.compactlyCodedChunkTable).samplesPerChunk!==r)&&t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){t.currentChunk.offset=0;return}t.currentChunk.offset=this.writer.getPos();for(let a of t.currentChunk.samples)m(a.data),this.writer.write(a.data),a.data=null;await this.writer.flush()}async interleaveSamples(t=!1){if(m(this.isFragmented),!(!t&&!this.allTracksAreKnown()))e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<a&&(r=s,a=s.sampleQueue[0].timestamp)}if(!r)break;let n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(t=!0){m(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let f=tr(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),n=Zi(r,a),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n),c=o+wt,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+=Le-wt;this.format._options.onMoof&&this.writer.startTrackingWrites();let p=Zi(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=Qr(l);h.size=d,this.boxWriter.writeBox(h),this.writer.seek(o+(l?Le:wt));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(n=>n.track===t);a&&await this.processWebVTTCues(a,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let t=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(let r of this.trackDatas)this.processTimestamps(r);await this.finalizeFragment(!1)}else for(let r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if(this.fastStart==="in-memory"){m(this.mdat);let r;for(let n=0;n<2;n++){let s=tr(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=tr(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(a),this.format._options.onMoov){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let n of this.finalizedChunks)for(let s of n.samples)m(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,s)}}else if(this.isFragmented){let r=this.writer.getPos(),a=Aa(this.trackDatas);this.boxWriter.writeBox(a);let n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{m(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);m(r!==void 0);let a=this.writer.getPos()-r;if(this.mdat.size=a,this.mdat.largeSize=a>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}this.format._options.onMoov&&this.writer.startTrackingWrites();let n=tr(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(n),this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}t()}};var Tt=class{constructor(e){this.value=e}},yt=class{constructor(e){this.value=e}},rr=class{constructor(e){this.value=e}};var Io=[440786851,408125543],Eo=[17138,17139,290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],Zr=[...Io,...Eo],Ba=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Da=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,_o=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},Yr=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=Ba(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=Da(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=_o(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 n=this.writer.getPos()-a,s=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,r),this.writer.seek(s)}}else if(typeof e.data=="number"){let t=e.size??Ba(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 Tt)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof yt)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof rr){let t=e.size??Da(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}}}},Ao=8,Oe=2,St=2*Ao,Ze=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,n=128;for(;(r&n)===0;)a++,n>>=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,n=128;for(;(r&n)===0;)a++,n>>=1;let{view:s,offset:o}=this.reader.getViewAndOffset(this.pos,this.pos+a),c=r&n-1;for(let u=1;u<a;u++)c*=256,c+=s.getUint8(o+u);return this.pos+=a,c}readUnsignedInt(e){if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=0;for(let n=0;n<e;n++)a*=256,a+=t.getUint8(r+n);return this.pos+=e,a}readSignedInt(e){let t=this.readUnsignedInt(e);return t&1<<e*8-1&&(t-=2**(e*8)),t}readFloat(e){if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e),a=e===4?t.getFloat32(r,!1):t.getFloat64(r,!1);return this.pos+=e,a}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-Oe;){this.reader.rangeIsLoaded(this.pos,Math.min(this.pos+St,t))||await this.reader.loadRange(this.pos,Math.min(this.pos+1048576,t));let n=this.pos,s=this.readElementHeader();if(!s)break;if(a.has(s.id))return n;Je(s.size),this.pos+=s.size}return null}},ce={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"},tn=(i,e)=>{if(e>=i.length)throw new Error("Offset out of bounds.");let t=i[e],r=1,a=128;for(;(t&a)===0&&r<8;)r++,a>>=1;if(e+r>i.length)throw new Error("VarInt extends beyond data bounds.");let n=t&a-1;for(let s=1;s<r;s++)n*=256,n+=i[e+s];return{value:n,width:r}};function Je(i){if(i===null)throw new Error("Undefined element size is used in a place where it is not supported.")}var Jr=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};var Ro=-(2**15),Fo=2**15-1,Va="https://github.com/Vanilagy/mediabunny",Ua=6,za=5,Oo={video:1,audio:2,subtitle:17},ei=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 Yr(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 et?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format._options.onEbmlHeader){let{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,a)}}createSeekHead(){let t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),n={id:290298740,data:[{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:0}]}]};this.seekHead=n}createSegmentInfo(){let t={id:17545,data:new yt(0)};this.segmentDuration=t;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Va},{id:22337,data:Va},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=ce[r.track.source._codec];m(a);let n=0;if(r.type==="audio"&&r.track.source._codec==="opus"){n=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=Q(s),c=Ue(o);n=Math.round(1e9*(c.preSkip/pt))}}t.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:Oo[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:n},r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(t){let{frameRate:r,rotation:a}=t.track.metadata,n=[t.info.decoderConfig.description?{id:25506,data:Q(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},yr(o)?{id:21936,data:[{id:21937,data:_e[o.matrix]},{id:21946,data:Ee[o.transfer]},{id:21947,data:Ie[o.primaries]},{id:21945,data:o.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new Tt((s+180)%360-180)}]}:null]};return n.push(c),n}audioSpecificTrackInfo(t){let r=U.includes(t.track.source._codec)?J(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:25506,data:Q(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new Tt(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:25506,data:pe.encode(t.info.config.description)}]}createSegment(){let t={id:408125543,size:this.format._options.appendOnly?-1:Ua,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 Jr({isWebM:this.format instanceof et,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:t})}getVideoTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Fr(r),m(r),m(r.decoderConfig),m(r.decoderConfig.codedWidth!==void 0),m(r.decoderConfig.codedHeight!==void 0);let n={track:t,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return t.source._codec==="vp9"?n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(ea(n.info.decoderConfig.codec))}:t.source._codec==="av1"&&(n.info.decoderConfig={...n.info.decoderConfig,description:new Uint8Array(_r(n.info.decoderConfig.codec))}),this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getAudioTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Ve(r),m(r),m(r.decoderConfig);let n={track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,r){let a=this.trackDatas.find(s=>s.track===t);if(a)return a;Or(r),m(r),m(r.config);let n={track:t,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getVideoTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=r.duration;t.metadata.frameRate!==void 0&&(c=Lt(c,1/t.metadata.frameRate),u=Lt(u,1/t.metadata.frameRate));let d=this.createInternalChunk(r.data,c,u,r.type);t.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{n()}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getAudioTrackData(t,a),o=r.type==="key",c=this.validateAndNormalizeTimestamp(s.track,r.timestamp,o),u=this.createInternalChunk(r.data,c,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{n()}}async addSubtitleCue(t,r,a){let n=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(t,a),o=this.validateAndNormalizeTimestamp(s.track,r.timestamp,!0),c=r.text,u=Math.round(o*1e3);gt.lastIndex=0,c=c.replace(gt,h=>{let k=Dr(h.slice(1,-1))-u;return`<${Vr(k)}>`});let d=pe.encode(c),l=`${r.settings??""}
${r.identifier??""}
${r.notes??""}`,p=this.createInternalChunk(d,o,r.duration,"key",l.trim()?pe.encode(l):null);s.chunkQueue.push(p),await this.interleaveChunks()}finally{n()}}async interleaveChunks(t=!1){if(!(!t&&!this.allTracksAreKnown())){e:for(;;){let r=null,a=1/0;for(let s of this.trackDatas){if(!t&&s.chunkQueue.length===0&&!s.track.source._closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<a&&(r=s,a=s.chunkQueue[0].timestamp)}if(!r)break;let n=r.chunkQueue.shift();this.writeBlock(r,n)}t||await this.writer.flush()}}fixVP9ColorSpace(t,r){if(r.type!=="key"||!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;let a=new q(r.data);a.skipBits(2);let n=a.readBits(1),o=(a.readBits(1)<<1)+n;if(o===3&&a.skipBits(1),a.readBits(1)||a.readBits(1)!==0||(a.skipBits(2),a.readBits(24)!==4817730))return;o>=2&&a.skipBits(1);let l={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];Un(r.data,a.pos,a.pos+3,l)}createInternalChunk(t,r,a,n,s=null){return{data:t,type:n,timestamp:r,duration:a,additions:s}}writeBlock(t,r){this.segment||(this.createTracks(),this.createSegment());let a=Math.round(1e3*r.timestamp),n=this.trackDatas.every(l=>{if(t===l)return r.type==="key";let p=l.chunkQueue[0];return p?p.type==="key":l.track.source._closed}),s=!1;if(!this.currentCluster)s=!0;else{m(this.currentClusterStartMsTimestamp!==null),m(this.currentClusterMaxMsTimestamp!==null);let l=a-this.currentClusterStartMsTimestamp;s=n&&a>this.currentClusterMaxMsTimestamp&&l>=1e3*(this.format._options.minimumClusterDuration??1)||l>Fo}s&&this.createNewCluster(a);let o=a-this.currentClusterStartMsTimestamp;if(o<Ro)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 rr(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:za,data:[{id:231,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(m(this.currentCluster),!this.format._options.appendOnly){let n=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(n,za),this.writer.seek(s)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(n,s,this.currentClusterStartMsTimestamp/1e3)}let t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[n,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(n);let a=[...r.entries()].sort((n,s)=>n[0]-s[0]);for(let[n,s]of a)m(this.cues),this.cues.data.push({id:187,data:[{id:179,data:n},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:t}]}))]})}async onTrackClose(){let t=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let t=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||(this.createTracks(),this.createSegment()),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),m(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos(),a=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(a,Ua),this.segmentDuration.data=new yt(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 rn={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]},nn={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]},an={0:[11025,12e3,8e3,-1],2:[22050,24e3,16e3,-1],3:[44100,48e3,32e3,-1]},Ct=1483304551,ti=1231971951,ri=(i,e,t,r)=>Math.floor(i===3?(12*e/t+r)*4:144*e/t+r),xt=(i,e)=>i===3?e===3?21:36:e===3?13:21,ii=(i,e)=>{let t=e.pos,r=i>>>24,a=i>>>16&255,n=i>>>8&255,s=i&255;if(r!==255&&a!==255&&n!==255&&s!==255)return e.pos+=4,null;if(e.pos+=1,r!==255||(a&224)!==224)return null;let o=a>>3&3,c=a>>1&3,u=n>>4&15,d=n>>2&3,l=n>>1&1,p=s>>6&3,h=s>>4&3,f=s>>3&1,k=s>>2&1,g=s&3,b=o===3?rn[c]?.[u]:nn[c]?.[u];if(!b||b===-1)return null;let w=b*1e3,C=an[o]?.[d];if(!C||C===-1)return null;let x=ri(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 ni=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?rn:nn)?.[e.layer];if(!s)throw new Error("Invalid MPEG version and layer combination.");let o=an[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=>ri(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=xt(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(Ct);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=ri(e.layer,1e3*s[d],o,c);this.writer.seek(t+k)}};var ai=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 ni(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 n=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&n){let s=ee(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=ii(o,{pos:0,fileSize:null});if(!c)throw new Error("Invalid MP3 header in sample.");let u=xt(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let d=s.getUint32(u,!1);if(d===Ct||d===ti)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(),n&&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 n=0;n<100;n++){let s=Math.floor(this.framePositions.length*(n/100));m(s!==-1&&s<this.framePositions.length);let o=this.framePositions[s];a[n]=256*(o/r)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,s)}this.writer.seek(r),t()}};var ir=1399285583,Mo=79764919,Na=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Mo:e<<1;Na[i]=e>>>0&4294967295}var si=i=>{let e=ee(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let a=0;a<i.length;a++){let n=i[a];r=(r<<8^Na[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},oi=(i,e,t)=>{let r=0,a=null;if(i.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,o=(1<<Qn(n-1))-1<<1,c=(i[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=t,d=e.vorbisInfo.modeBlockflags[c];if(a=e.vorbisInfo.blocksizes[d],d===1){let l=(o|1)+1,p=i[0]&l?1:0;u=e.vorbisInfo.blocksizes[p]}r=u!==null?u+a>>2:0}else e.codec==="opus"&&(r=wa(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:a}},ci=i=>{let e="audio/ogg";if(i.codecStrings){let t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var Pt=27,tt=282,di=tt+255*255,vt=class{constructor(e){this.reader=e;this.pos=0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU8(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+1);return this.pos+=1,e.getUint8(t)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!0)}readI32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getInt32(t,!0)}readI64(){let e=this.readU32();return this.readI32()*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readPageHeader(){let e=this.pos;if(this.readU32()!==ir)return null;this.pos+=1;let r=this.readU8(),a=this.readI64(),n=this.readU32(),s=this.readU32(),o=this.readU32(),c=this.readU8(),u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=this.readU8();let d=27+c,l=u.reduce((h,f)=>h+f,0),p=d+l;return{headerStartPos:e,totalSize:p,dataStartPos:e+d,dataSize:l,headerType:r,granulePosition:a,serialNumber:n,sequenceNumber:s,checksum:o,lacingValues:u}}findNextPageHeader(e){for(;this.pos<e-3;){let t=this.readU32(),r=t&255,a=t>>>8&255,n=t>>>16&255,s=t>>>24&255,o=79;if(!(r!==o&&a!==o&&n!==o&&s!==o)){if(this.pos-=4,t===ir)return!0;this.pos+=1}}return!1}};var Bo=8192,ui=class extends de{constructor(t,r){super(t);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=W();this.pageBytes=new Uint8Array(di);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,ci({codecStrings:this.trackDatas.map(t=>t.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(t,r){let a=this.trackDatas.find(o=>o.track===t);if(a)return a;let n;do n=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===n));m(t.source._codec==="vorbis"||t.source._codec==="opus"),Ve(r),m(r),m(r.decoderConfig);let s={track:t,serialNumber:n,internalSampleRate:t.source._codec==="opus"?pt: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=Q(r.decoderConfig.description);if(a[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let n=1,s=()=>{let k=0;for(;;){let g=a[n++];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-n<=0)throw new TypeError("Vorbis decoder description is too short.");let d=a.subarray(n,n+=o),l=a.subarray(n,n+=c),p=a.subarray(n);t.packetQueue.push({data:d,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:l,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:p,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let f=ee(d).getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Hr(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=Q(r.decoderConfig.description),n=new Uint8Array(16),s=new DataView(n.buffer);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1),s.setUint32(8,0,!0),s.setUint32(12,0,!0),t.packetQueue.push({data:a,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:n,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),t.codecInfo.opusInfo={preSkip:Ue(a).preSkip}}}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{let s=this.getTrackData(t,a);this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=oi(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u,s.packetQueue.push({data:r.data,endGranulePosition:s.currentTimestampInSamples,timestamp:o/s.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{n()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async interleavePages(t=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let a=r.packetQueue.shift();if(this.writePacket(r,a,!1),a.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,a=1/0;for(let o of this.trackDatas){if(!t&&o.packetQueue.length<=1&&!o.track.source._closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestamp<a&&(r=o,a=o.packetQueue[0].timestamp)}if(!r)break;let n=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,n,s)}t||await this.writer.flush()}writePacket(t,r,a){let n=r.data.length,s=0,o=0;for(;;){t.currentLacingValues.length===0&&s>0&&(t.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,n);t.currentLacingValues.push(u),t.currentPageSize++,o+=u;let d=n<255;if(t.currentLacingValues.length===255){let l=r.data.subarray(s,o);if(s=o,t.currentPageData.push(l),t.currentPageSize+=l.length,this.writePage(t,a&&d),d)return}if(d)break;n-=255}let c=r.data.subarray(s);t.currentPageData.push(c),t.currentPageSize+=c.length,t.currentGranulePosition=r.endGranulePosition,(t.currentPageSize>=Bo||r.forcePageFlush)&&this.writePage(t,a)}writePage(t,r){this.pageView.setUint32(0,ir,!0),this.pageView.setUint8(4,0);let a=0;t.currentPageStartsWithFreshPacket||(a|=1),t.pagesWritten===0&&(a|=2),r&&(a|=4),this.pageView.setUint8(5,a);let n=t.currentLacingValues.every(u=>u===255)?-1:t.currentGranulePosition;Kn(this.pageView,6,n,!0),this.pageView.setUint32(14,t.serialNumber,!0),this.pageView.setUint32(18,t.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,t.currentLacingValues.length),this.pageBytes.set(t.currentLacingValues,27);let s=27+t.currentLacingValues.length;for(let u of t.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=si(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 ae=new Uint8Array(0),M=class i{constructor(e,t,r,a,n=-1,s){this.data=e;this.type=t;this.timestamp=r;this.duration=a;this.sequenceNumber=n;if(e===ae&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=s}get isMetadataOnly(){return this.data===ae}get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let t=new Uint8Array(e.byteLength);return e.copyTo(t),new i(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new i(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}};var La=i=>{let r=i,a=4096,n=0,s=12,o=0;for(r<0&&(r=-r,n=128),r+=33,r>8191&&(r=8191);(r&a)!==a&&s>=5;)a>>=1,s--;return o=r>>s-4&15,~(n|s-5<<4|o)&255},Ha=i=>{let t=0,r=0,a=~i;a&128&&(a&=-129,t=-1),r=((a&240)>>4)+5;let n=(1<<r|(a&15)<<r-4|1<<r-5)-33;return t===0?n:-n},Ka=i=>{let t=2048,r=0,a=11,n=0,s=i;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&a>=5;)t>>=1,a--;return n=s>>(a===4?1:a-4)&15,(r|a-4<<4|n)^85},Qa=i=>{let e=0,t=0,r=i^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let a=0;return t!==4?a=1<<t|(r&15)<<t-4|1<<t-5:a=r<<1|1,e===0?a:-a};var se=class i{constructor(e,t){this._closed=!1;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=Q(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=e.colorSpace}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new i(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Te),duration:Math.trunc((t.duration??0)*Te)}),t);let r=0,a=0;if("naturalWidth"in e?(r=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,a=e.videoHeight):"width"in e&&(r=Number(e.width),a=Number(e.height)),!r||!a)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(r,a),s=n.getContext("2d",{alpha:!1,willReadFrequently:!0});m(s),s.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=r,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),nr(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new i(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new i(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||(nr(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),nr(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!dt(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),nr(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)Q(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);Q(e).set(a.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),nr(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,r,a,n,s,o,c,u){let d=0,l=0,p=this.displayWidth,h=this.displayHeight,f=0,k=0,g=this.displayWidth,b=this.displayHeight;if(s!==void 0?(d=t,l=r,p=a,h=n,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=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(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}},nr=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,sn=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),ie=class i{constructor(e){this._closed=!1;if(sr(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(!sn.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/(ar(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*ar(this.format);if(r.byteLength<a)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*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&&!sn.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let a=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(a>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let n=ar(t),s=li(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?a:a*this.numberOfChannels)*n}copyTo(e,t){if(!dt(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&&!sn.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{planeIndex:r,format:a,frameCount:n,frameOffset:s}=t,o=a??this.format;if(!o)throw new Error("Destination format not determined");let c=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=c)throw new RangeError("frameOffset out of range");let l=n!==void 0?n:c-d;if(l>c-d)throw new RangeError("frameCount out of range");let p=ar(o),h=li(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=Vo(o);if(sr(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=Do(x),T=ar(x),S=li(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,B;S?B=(E*c+(v+d))*T:B=((v+d)*u+E)*T;let N=y(C,B);b(g,_,N)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(sr(this._data)){let e=new i(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new i({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(sr(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(sr(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(li(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,n=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 i({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:a,timestamp:t+c/n,data:p});d.push(h),c+=l,u-=l}return d}},ar=i=>{switch(i){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},li=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Do=i=>{switch(i){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Vo=i=>{switch(i){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,G((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,G(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,G(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},sr=i=>typeof AudioData<"u"&&i instanceof AudioData;var It=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},Me=i=>{if(typeof i!="number"||Number.isNaN(i))throw new TypeError("timestamp must be a number.")},on=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;let a=await i.determinePacketType(r);return a&&(r.type=a),r}):e,ge=class{constructor(e){if(!(e instanceof Ke))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){return It(e),on(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){return Me(e),It(t),on(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof M))throw new TypeError("packet must be an EncodedPacket.");return It(t),on(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Me(e),It(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 M))throw new TypeError("packet must be an EncodedPacket.");if(It(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 M))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 M))throw new TypeError("endPacket must be an EncodedPacket.");It(r);let a=[],{promise:n,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:n,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 n}}},async return(){return d=!0,c(),s(),{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}},or=class{constructor(e,t){this.onSample=e;this.onError=t}},Et=class{mediaSamplesInRange(e=0,t=1/0){Me(e),Me(t);let r=[],a=!1,n=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}n&&(y.timestamp>e?(r.push(n),a=!0):n.close()),y.timestamp>=e&&(r.push(y),a=!0),n=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=qa(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&&n&&r.push(n),d=!0,o()})().catch(f=>{h||(h=f,o())}),{async next(){for(;;){if(p)return{value:void 0,done:!0};if(h)throw h;if(r.length>0){let f=r.shift();return u(),{value:f,done:!1}}else if(!d)await s;else return{value:void 0,done:!0}}},async return(){p=!0,l=!0,u(),o(),n?.close();for(let f of r)f.close();return{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Nn(e);let t=Wn(e),r=[],a=[],{promise:n,resolve:s}=W(),{promise:o,resolve:c}=W(),u=!1,d=!1,l=null,p=h=>{a.push(h),s(),{promise:n,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=qa(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(Me(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 n;else return{value:void 0,done:!0}}},async return(){d=!0,c(),s();for(let h of a)h?.close();return{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},qa=i=>i===0?40:8,cn=class extends or{constructor(t,r,a,n,s,o){super(t,r);this.rotation=s;this.timeResolution=o;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Be;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];let c=mt.find(u=>u.supports(a,n));if(c)this.customDecoder=new c,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=u=>{if(!(u instanceof se))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(xr()){if(this.sampleQueue.length>0&&d.timestamp>=z(this.sampleQueue).timestamp){for(let l of this.sampleQueue)this.finalizeAndEmitSample(l);this.sampleQueue.length=0}he(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 se(d)),error:r}),this.decoder.configure(n)}}finalizeAndEmitSample(t){t.setTimestamp(Math.round(t.timestamp*this.timeResolution)/this.timeResolution),t.setDuration(Math.round(t.duration*this.timeResolution)/this.timeResolution),t.setRotation(this.rotation),this.onSample(t)}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),xr()||he(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()),xr()){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}},rt=class extends Et{constructor(e){if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._videoTrack=e}async _createDecoder(e,t){if(!await this._videoTrack.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._videoTrack.codec,a=this._videoTrack.rotation,n=await this._videoTrack.getDecoderConfig(),s=this._videoTrack.timeResolution;return m(r&&n),new cn(e,t,r,n,a,s)}_createPacketSink(){return new ge(this._videoTrack)}async getSample(e){Me(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)}},_t=class{constructor(e,t={}){this._nextCanvasIndex=0;if(!(e instanceof le))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");let r=t.rotation??e.rotation,[a,n]=r%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=a/n;t.width!==void 0&&t.height===void 0?(a=t.width,n=Math.round(a/s)):t.width===void 0&&t.height!==void 0?(n=t.height,a=Math.round(n*s)):t.width!==void 0&&t.height!==void 0&&(a=t.width,n=t.height),this._videoTrack=e,this._width=a,this._height=n,this._rotation=r,this._fit=t.fit??"fill",this._videoSampleSink=new rt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex];t||(typeof document<"u"?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t)),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext("2d",{alpha:!1});m(r),r.resetTransform();let a,n,s,o;if(this._fit==="fill")a=0,n=0,s=this._width,o=this._height;else{let[d,l]=this._rotation%180===0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],p=this._fit==="contain"?Math.min(this._width/d,this._height/l):Math.max(this._width/d,this._height/l);s=d*p,o=l*p,a=(this._width-s)/2,n=(this._height-o)/2}let c=this._rotation%180===0?1:s/o;r.translate(this._width/2,this._height/2),r.rotate(this._rotation*Math.PI/180),r.scale(1/c,c),r.translate(-this._width/2,-this._height/2),r.drawImage(e.toCanvasImageSource(),a,n,s,o);let u={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),u}async getCanvas(e){Me(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return Nt(this._videoSampleSink.samples(e,t),r=>this._videoSampleToWrappedCanvas(r))}canvasesAtTimestamps(e){return Nt(this._videoSampleSink.samplesAtTimestamps(e),t=>t&&this._videoSampleToWrappedCanvas(t))}},dn=class extends or{constructor(t,r,a,n){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=n.sampleRate;c.setTimestamp(Math.round(c.timestamp*u)/u),t(c)},o=ft.find(c=>c.supports(a,n));o?(this.customDecoder=new o,this.customDecoder.codec=a,this.customDecoder.config=n,this.customDecoder.onSample=c=>{if(!(c instanceof ie))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:c=>s(new ie(c)),error:r}),this.decoder.configure(n))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(t){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(t)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.decoder.decode(t.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}},un=class extends or{constructor(t,r,a){super(t,r);this.decoderConfig=a;this.currentTimestamp=null;m(U.includes(a.codec)),this.codec=a.codec;let{dataType:n,sampleSize:s,littleEndian:o}=J(this.codec);switch(this.inputSampleSize=s,s){case 1:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:n==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):n==="ulaw"?this.readInputValue=(c,u)=>Ha(c.getUint8(u)):n==="alaw"?this.readInputValue=(c,u)=>Qa(c.getUint8(u)):m(!1);break;case 2:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:n==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):m(!1);break;case 3:n==="unsigned"?this.readInputValue=(c,u)=>Ni(c,u,o)-2**23:n==="signed"?this.readInputValue=(c,u)=>Ln(c,u,o):m(!1);break;case 4:n==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:n==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):n==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):m(!1);break;case 8:n==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):m(!1);break;default:Ae(s),m(!1)}switch(s){case 1:n==="ulaw"||n==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,d)=>c.setUint8(u,d+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,d)=>c.setInt16(u,d,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d<<8,!0);break;case 4:this.outputSampleSize=4,n==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,d)=>c.setInt32(u,d,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,d)=>c.setFloat32(u,d,!0);break;default:Ae(s),m(!1)}}getDecodeQueueSize(){return 0}decode(t){let r=ee(t.data),a=t.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,n=a*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(n),o=new DataView(s);for(let l=0;l<a*this.decoderConfig.numberOfChannels;l++){let p=l*this.inputSampleSize,h=l*this.outputSampleSize,f=this.readInputValue(r,p);this.writeOutputValue(o,h,f)}let c=a/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=t.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let d=new ie({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:a,timestamp:u});this.onSample(d)}async flush(){}close(){}},He=class extends Et{constructor(e){if(!(e instanceof Y))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._audioTrack=e}async _createDecoder(e,t){if(!await this._audioTrack.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=this._audioTrack.codec,a=await this._audioTrack.getDecoderConfig();return m(r&&a),U.includes(a.codec)?new un(e,t,a):new dn(e,t,r,a)}_createPacketSink(){return new ge(this._audioTrack)}async getSample(e){Me(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)}},mi=class{constructor(e){if(!(e instanceof Y))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new He(e)}_audioSampleToWrappedArrayBuffer(e){return{buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration}}async getBuffer(e){Me(e);let t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return Nt(this._audioSampleSink.samples(e,t),r=>this._audioSampleToWrappedArrayBuffer(r))}buffersAtTimestamps(e){return Nt(this._audioSampleSink.samplesAtTimestamps(e),t=>t&&this._audioSampleToWrappedArrayBuffer(t))}};var Ke=class{constructor(e){this._backing=e}isVideoTrack(){return this instanceof le}isAudioTrack(){return this instanceof Y}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 ge(this),r=1/0,a=-1/0,n=0,s=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(n>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),n++,s+=o.byteLength}return{packetCount:n,averagePacketRate:n?Number((n/(a-r)).toPrecision(16)):0,averageBitrate:n?Number((8*s/(a-r)).toPrecision(16)):0}}},le=class extends Ke{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),mt.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 M))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)}},Y=class extends Ke{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),ft.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 M))throw new TypeError("packet must be an EncodedPacket.");return this.codec===null?null:"key"}};var me=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 n=this.source._read(e,t),s={start:e,end:t,promise:n};this.loadingSegments.push(s);let o=await n;zn(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 n=this.loadedSegments[a];if(n.start>e)break;if(n.end>=t)return!0}return!1}insertIntoLoadedSegments(e,t){let r={start:e,end:e+t.byteLength,bytes:t,view:new DataView(t.buffer),age:this.nextAge++},a=V(this.loadedSegments,e,n=>n.start);(a===-1||this.loadedSegments[a].start<r.start)&&a++,this.loadedSegments.splice(a,0,r),this.totalStoredBytes+=t.byteLength;for(let n=a+1;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>=r.end)break;r.start<=s.start&&s.end<=r.end&&(this.loadedSegments.splice(n,1),n--)}for(;this.totalStoredBytes>this.maxStorableBytes&&this.loadedSegments.length>1;){let n=null,s=-1;for(let o=0;o<this.loadedSegments.length;o++){let c=this.loadedSegments[o];(!n||c.age<n.age)&&(n=c,s=o)}m(n),this.totalStoredBytes-=n.bytes.byteLength,this.loadedSegments.splice(s,1)}}getViewAndOffset(e,t){let r=V(this.loadedSegments,e,n=>n.start),a=null;if(r!==-1)for(let n=r;n<this.loadedSegments.length;n++){let s=this.loadedSegments[n];if(s.start>e)break;if(t<=s.end){a=s;break}}if(!a)throw new Error(`No segment loaded for range [${e}, ${t}).`);return a.age=this.nextAge++,{view:a.view,offset:a.bytes.byteOffset+e-a.start}}forgetRange(e,t){if(t<=e)return;let r=V(this.loadedSegments,e,n=>n.start);if(r===-1)return;let a=this.loadedSegments[r];a.start!==e||a.end!==t||(this.loadedSegments.splice(r,1),this.totalStoredBytes-=a.bytes.byteLength)}};var it=class{constructor(e){this.reader=e;this.pos=0;this.littleEndian=!0}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,this.littleEndian)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,this.littleEndian)}readU64(){let e,t;return this.littleEndian?(e=this.readU32(),t=this.readU32()):(t=this.readU32(),e=this.readU32()),t*4294967296+e}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}};var fi=class extends ue{constructor(t){super(t);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.tracks=[];this.metadataReader=new it(t._mainReader),this.chunkReader=new it(new me(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{let t=await this.metadataReader.reader.source.getSize(),r=this.metadataReader.readAscii(4);this.metadataReader.littleEndian=r!=="RIFX";let a=r==="RF64",n=this.metadataReader.readU32(),s=a?t:Math.min(n+8,t);if(this.metadataReader.readAscii(4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");this.metadataReader.pos=12;let c=0,u=null;for(;this.metadataReader.pos<s;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+8);let l=this.metadataReader.readAscii(4),p=this.metadataReader.readU32(),h=this.metadataReader.pos;if(a&&c===0&&l!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(l==="fmt ")await this.parseFmtChunk(p);else if(l==="data")u??=p,this.dataStart=this.metadataReader.pos,this.dataSize=Math.min(u,s-this.dataStart);else if(l==="ds64"){let f=this.metadataReader.readU64();u=this.metadataReader.readU64(),s=Math.min(f+8,t)}this.metadataReader.pos=h+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.tracks.push(new Y(new ln(this)))})()}async parseFmtChunk(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+t);let r=this.metadataReader.readU16(),a=this.metadataReader.readU16(),n=this.metadataReader.readU32();this.metadataReader.pos+=4;let s=this.metadataReader.readU16(),o;if(t===14?o=8:o=this.metadataReader.readU16(),t>=18&&r!==357){let c=this.metadataReader.readU16(),u=t-18;if(Math.min(u,c)>=22&&r===65534){this.metadataReader.pos+=6;let l=this.metadataReader.readBytes(16);r=l[0]|l[1]<<8}}(r===7||r===6)&&(o=8),this.audioInfo={format:r,numberOfChannels:a,sampleRate:n,sampleSizeInBytes:Math.ceil(o/8),blockSizeInBytes:s}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===3&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){return await this.readMetadata(),m(this.audioInfo),this.dataSize/this.audioInfo.blockSizeInBytes/this.audioInfo.sampleRate}async getTracks(){return await this.readMetadata(),this.tracks}},At=2048,ln=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*At*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let a=Math.min(At*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r),n;if(t.metadataOnly)n=ae;else{let c=At*this.demuxer.audioInfo.blockSizeInBytes,u=Math.ceil(2**19/c)*c,d=Math.floor(r/u)*u,l=d+u;await this.demuxer.chunkReader.reader.loadRange(this.demuxer.dataStart+d,this.demuxer.dataStart+l),this.demuxer.chunkReader.pos=this.demuxer.dataStart+r,n=this.demuxer.chunkReader.readBytes(a)}let s=e*At/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return new M(n,"key",s,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){m(this.demuxer.audioInfo);let r=Math.floor(e*this.demuxer.audioInfo.sampleRate/At);return this.getPacketAtIndex(r,t)}getNextPacket(e,t){m(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/At);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var pi=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 hi=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 pi(t._writer),this.isRf64=!!r._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(t,r,a){let n=await this.mutex.acquire();try{if(this.headerWritten||(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{n()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(t,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let a,n=t.source._codec,s=J(n);s.dataType==="ulaw"?a=7:s.dataType==="alaw"?a=6:s.dataType==="float"?a=3:a=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(a),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):this.riffWriter.writeU32(0),this.format._options.onHeader){let{data:d,start:l}=this.writer.stopTrackingWrites();this.format._options.onHeader(d,l)}}async finalize(){let t=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(this.writer.seek(20),this.riffWriter.writeU64(r-8),this.writer.seek(28),this.riffWriter.writeU64(this.dataSize),this.writer.seek(36),this.riffWriter.writeU64(this.sampleCount)):(this.writer.seek(4),this.riffWriter.writeU32(r-8),this.writer.seek(40),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(r),t()}};var be=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>$.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>X.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>oe.includes(e))}_codecUnsupportedHint(e){return""}},Rt=class extends be{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 Xr(e,this)}},cr=class extends Rt{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...$,...ye,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...oe]}_codecUnsupportedHint(e){return new Ye().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Ye=class extends Rt{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...$,...X]}_codecUnsupportedHint(e){return new cr().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},Ft=class extends be{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 ei(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[...$,...ye,...U.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...oe]}get supportsVideoRotationMetadata(){return!1}},et=class extends Ft{getSupportedCodecs(){return[...$.filter(e=>["vp8","vp9","av1"].includes(e)),...X.filter(e=>["opus","vorbis"].includes(e)),...oe]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Ft().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},gi=class extends be{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 ai(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}},bi=class extends be{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 hi(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...U.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}},ki=class extends be{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 ui(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[...X.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}};var nt=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)}},xe=class extends nt{constructor(t){super();this._connectedTrack=null;if(!$.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${$.join(", ")}.`);this._codec=t}},Ot=class extends xe{constructor(e){super(e)}add(e,t){if(!(e instanceof M))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)}},pn=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!$.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${$.join(", ")}.`);if(!(i.bitrate instanceof K)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(i.latencyMode!==void 0&&!["quality","realtime"].includes(i.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&Ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},dr=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,n=Math.floor(e.timestamp/a),s={...r,keyFrame:r?.keyFrame||a===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;let o=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 K?this.encodingConfig.bitrate._toVideoBitrate(this.encodingConfig.codec,t,r):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??vr(this.encodingConfig.codec,t,r,a),width:t,height:r,bitrate:a,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.encodingConfig.latencyMode,...Ir(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=qe.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof M))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(!(await VideoEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.width}x${n.height}) is not supported by this browser. Consider using another codec or changing your video parameters.`);this.encoder=new VideoEncoder({output:(c,u)=>{let d=M.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(n)}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}},Mt=class extends xe{constructor(e){pn(e),super(e.codec),this._encoder=new dr(this,e)}add(e,t){if(!(e instanceof se))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},wi=class extends xe{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.");pn(t),super(t.codec),this._encoder=new dr(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 se(this._canvas,{timestamp:e,duration:t});return this._encoder.add(a,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Ti=class extends xe{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");pn(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 dr(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=n=>{if(r){n.close();return}if(t===null){t=n.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){n.close();return}this._encoder.add(new se(n),!0).catch(s=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(s),this._workerTrackId!==null&&fn({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let n=new MediaStreamTrackProcessor({track:this._track}),s=new WritableStream({write:a});n.readable.pipeTo(s,{signal:this._abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||this._promiseWithResolvers.reject(o)})}else if(await No())this._workerTrackId=zo++,fn({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)},fe.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),fn({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let a=n=>{let s=n.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(m(this._workerListener),fe.removeEventListener("message",this._workerListener),fe.removeEventListener("message",a),r())};fe.addEventListener("message",a)})),await this._encoder.flushAndClose(t)}},ve=class extends nt{constructor(t){super();this._connectedTrack=null;if(!X.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${X.join(", ")}.`);this._codec=t}},Bt=class extends ve{constructor(e){super(e)}add(e,t){if(!(e instanceof M))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)}},hn=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!X.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${X.join(", ")}.`);if(i.bitrate===void 0&&(!U.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(i.bitrate!==void 0&&!(i.bitrate instanceof K)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.fullCodecString!==void 0&&typeof i.fullCodecString!="string")throw new TypeError("config.fullCodecString, when provided, must be a string.");if(i.fullCodecString!==void 0&&Ki(i.fullCodecString)!==i.codec)throw new TypeError(`config.fullCodecString, when provided, must be a string that matches the specified codec (${i.codec}).`);if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.")},ur=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(n=>this.encoderError??=n).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:n,timestamp:s}=e,o=2048,c=[];for(let p=0;p<a;p+=o){let h=Math.min(o,e.numberOfFrames-p),f=h*r*this.outputSampleSize,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:n}};for(let p=0;p<c.length;p++){let{frameCount:h,view:f}=c[p],k=f.buffer,g=p*o,b=new M(new Uint8Array(k),"key",s+g/n,h/n);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 K?this.encodingConfig.bitrate._toAudioBitrate(this.encodingConfig.codec):this.encodingConfig.bitrate,n={codec:this.encodingConfig.fullCodecString??Pr(this.encodingConfig.codec,t,r),numberOfChannels:t,sampleRate:r,bitrate:a,...Er(this.encodingConfig.codec)};this.encodingConfig.onEncoderConfig?.(n);let s=$e.find(o=>o.supports(this.encodingConfig.codec,n));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof M))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c)},await this.customEncoder.init();else if(U.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(c,u)=>{let d=M.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(n)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:a}=J(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint8(s,G((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,s,o)=>{n.setInt8(s,G(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,s,o)=>{let c=G(Math.floor(o*32767),-32768,32767);n.setUint8(s,La(c))}:t==="alaw"?this.writeOutputValue=(n,s,o)=>{let c=G(Math.floor(o*32767),-32768,32767);n.setUint8(s,Ka(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint16(s,G((o+1)*32767.5,0,65535),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt16(s,G(Math.round(o*32767),-32768,32767),a):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,s,o)=>Li(n,s,G((o+1)*83886075e-1,0,16777215),a):t==="signed"?this.writeOutputValue=(n,s,o)=>Hn(n,s,G(Math.round(o*8388607),-8388608,8388607),a):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,s,o)=>n.setUint32(s,G((o+1)*21474836475e-1,0,4294967295),a):t==="signed"?this.writeOutputValue=(n,s,o)=>n.setInt32(s,G(Math.round(o*2147483647),-2147483648,2147483647),a):t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat32(s,o,a):m(!1);break;case 8:t==="float"?this.writeOutputValue=(n,s,o)=>n.setFloat64(s,o,a):m(!1);break;default:Ae(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}},at=class extends ve{constructor(e){hn(e),super(e.codec),this._encoder=new ur(this,e)}add(e){if(!(e instanceof ie))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},yi=class extends ve{constructor(t){hn(t);super(t.codec);this._accumulatedTime=0;this._encoder=new ur(this,t)}add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let a=ie.fromAudioBuffer(t,this._accumulatedTime).map(n=>this._encoder.add(n,!0));return this._accumulatedTime+=t.duration,Promise.all(a)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Si=class extends ve{constructor(t,r){if(!(t instanceof MediaStreamTrack)||t.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");hn(r);super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=W();this._errorPromiseAccessed=!1;this._encoder=new ur(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:n=>{if(t===null){t=n.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){n.close();return}this._encoder.add(new ie(n),!0).catch(s=>{this._abortController?.abort(),this._promiseWithResolvers.reject(s)})}});r.readable.pipeTo(a,{signal:this._abortController.signal}).catch(n=>{n instanceof DOMException&&n.name==="AbortError"||this._promiseWithResolvers.reject(n)})}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,n=0;this._scriptProcessorNode.onaudioprocess=s=>{let o=ie.fromAudioBuffer(s.inputBuffer,n);n+=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)}},Uo=()=>{let i=(r,a)=>{a?self.postMessage(r,{transfer:a}):self.postMessage(r)};i({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 n=new MediaStreamTrackProcessor({track:a.track}),s=new WritableStream({write:c=>{if(t.has(a.trackId)){c.close();return}i({type:"videoFrame",trackId:a.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(a.trackId,o),n.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:a.trackId,error:c})})}break;case"stopTrack":{let n=e.get(a.trackId);n&&(n.abort(),e.delete(a.trackId)),t.add(a.trackId),i({type:"trackStopped",trackId:a.trackId})}break;default:Ae(a)}})},zo=0,fe=null,Wo=()=>{let i=new Blob([`(${Uo.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(i);fe=new Worker(e)},mn=null,No=async()=>mn!==null?mn:(fe||Wo(),new Promise(i=>{m(fe);let e=t=>{let r=t.data;r.type==="support"&&(mn=r.supported,fe.removeEventListener("message",e),i(r.supported))};fe.addEventListener("message",e)})),fn=(i,e)=>{m(fe),e?fe.postMessage(i,e):fe.postMessage(i)},st=class extends nt{constructor(t){super();this._connectedTrack=null;if(!oe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${oe.join(", ")}.`);this._codec=t}},Ci=class extends st{constructor(e){super(e),this._parser=new Br({codec:e,output:(t,r)=>this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,t,r)})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._ensureValidAdd(),this._parser.parse(e),this._connectedTrack.output._muxer.mutex.currentPromise}};var bn=["video","audio","subtitle"],gn=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!lt(i.languageCode))throw new TypeError("metadata.languageCode must be a three-letter, ISO 639-2/T language code.")},Dt=class{constructor(e){this.state="pending";this._tracks=[];this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new ne;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof be))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Ne))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 xe))throw new TypeError("source must be a VideoSource.");if(gn(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 ve))throw new TypeError("source must be an AudioSource.");gn(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof st))throw new TypeError("source must be a SubtitleSource.");gn(t),this._addTrack("subtitle",e,t)}_addTrack(e,t,r){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");let a=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((u,d)=>u+(d.type===e?1:0),0),s=a[e].max;if(n===s)throw new Error(s===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track${s===1?"":"s"}.`);let o=a.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);let c={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if(c.type==="video"){let u=this.format.getSupportedVideoCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="audio"){let u=this.format.getSupportedAudioCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}else if(c.type==="subtitle"){let u=this.format.getSupportedSubtitleCodecs();if(u.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(c.source._codec));if(!u.includes(c.source._codec))throw new Error(`Codec '${c.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${u.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(c.source._codec))}this._tracks.push(c),t._connectedTrack=c}async start(){let e=this.format.getSupportedTrackCounts();for(let r of bn){let a=this._tracks.reduce((s,o)=>s+(o.type===r?1:0),0),n=e[r].min;if(a<n)throw new Error(n===e[r].max?`${this.format._name} requires exactly ${n} ${r} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${r} track${n===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();let r=await this._mutex.acquire();await this._muxer.start();let a=this._tracks.map(n=>n.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 Pe=class{constructor(){this._sizePromise=null;this.onread=null}getSize(){return this._sizePromise??=this._retrieveSize()}},xi=class extends Pe{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}},vi=class extends Pe{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()}},Pi=class extends Pe{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}},Ii=class extends Pe{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,Ht(this._options.requestInit??{},{method:"GET",headers:r}),this._options.getRetryDelay??(()=>null));if(!a.ok)throw new Error(`Error fetching ${this._url}: ${a.status} ${a.statusText}`);let n=await a.arrayBuffer();return a.status===206&&t&&n.byteLength!==t.end-t.start&&this._nextUrlVersion===null?(this._nextUrlVersion=1,this._makeRequest(t)):(a.status===200&&(this._fullData=n),{response:n,statusCode:a.status})}async _read(t,r){if(this._fullData)return new Uint8Array(this._fullData,t,r-t);let{response:a,statusCode:n}=await this._makeRequest({start:t,end:r});return n===200?new Uint8Array(a).subarray(t,r):new Uint8Array(a)}async _retrieveSize(){if(this._fullData)return this._fullData.byteLength;try{let a=await Cr(this._url,Ht(this._options.requestInit??{},{method:"HEAD"}),this._options.getRetryDelay??(()=>null));if(a.ok){let n=a.headers.get("Content-Length");if(n)return parseInt(n)}}catch{}let t=await Cr(this._url,Ht(this._options.requestInit??{},{method:"GET",headers:{Range:"bytes=0-0"}}),this._options.getRetryDelay??(()=>null));if(t.status===206){let a=t.headers.get("Content-Range");if(a){let n=a.match(/bytes \d+-\d+\/(\d+)/);if(n&&n[1])return parseInt(n[1])}}else if(t.status===200)return this._fullData=await t.arrayBuffer(),this._fullData.byteLength;let{response:r}=await this._makeRequest();return r.byteLength}};var Ei=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 ne;this.metadataReader=new Xe(t._mainReader),this.chunkReader=new Xe(new me(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 Gr({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+Le);let r=this.metadataReader.pos,a=this.metadataReader.readBoxHeader();if(a.name==="ftyp"){let n=this.metadataReader.readAscii(4);this.isQuickTime=n==="qt "}else if(a.name==="moov"){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+a.contentSize),this.readContiguousBoxes(a.contentSize);for(let n of this.tracks){let s=n.editListPreviousSegmentDurations/this.movieTimescale;n.editListOffset-=Math.round(s*n.timescale)}break}this.metadataReader.pos=r+a.totalSize}if(this.isFragmented){await this.metadataReader.reader.loadRange(t-4,t),this.metadataReader.pos=t-4;let r=this.metadataReader.readU32(),a=t-r;if(a>=0&&a<t){await this.metadataReader.reader.loadRange(a,t),this.metadataReader.pos=a;let n=this.metadataReader.readBoxHeader();n.name==="mfra"&&this.readContiguousBoxes(n.contentSize)}}})()}getSampleTableForTrack(t){if(t.sampleTable)return t.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(t.sampleTable=r,this.metadataReader.pos=t.sampleTableByteOffset,this.currentTrack=t,this.traverseBox(),this.currentTrack=null,t.info?.type==="audio"&&t.info.codec&&U.includes(t.info.codec)&&r.sampleCompositionTimeOffsets.length===0){m(t.info?.type==="audio");let n=J(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=z(s);T&&T.delta===y?T.count++:s.push({startIndex:u.startChunkIndex+p,startDecodeTimestamp:C,count:1,delta:y});let S=u.samplesPerChunk*n.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 n of r.sampleTimingEntries)for(let s=0;s<n.count;s++)r.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+s*n.delta,sampleIndex:n.startIndex+s});for(let n of r.sampleCompositionTimeOffsets)for(let s=0;s<n.count;s++){let o=n.startIndex+s,c=r.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}r.presentationTimestamps.sort((n,s)=>n.presentationTimestamp-s.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let n=0;n<r.presentationTimestamps.length;n++)r.presentationTimestampIndexMap[r.presentationTimestamps[n].sampleIndex]=n}return r}async readFragment(){let t=this.metadataReader.pos;await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+Le);let r=this.metadataReader.readBoxHeader();m(r.name==="moof");let a=this.metadataReader.pos;await this.metadataReader.reader.loadRange(a,a+r.contentSize),this.metadataReader.pos=t,this.traverseBox();let n=H(this.fragments,t,o=>o.moofOffset);m(n!==-1);let s=this.fragments[n];m(s.moofOffset===t),this.metadataReader.reader.forgetRange(a,a+r.contentSize);for(let[o,c]of s.trackData){if(c.startTimestampIsFinal)continue;let u=this.tracks.find(f=>f.id===o);this.metadataReader.pos=0;let d=null,l=null,p=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+Le);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),ja(c,f.endTimestamp)}c.startTimestampIsFinal=!0}return s}readContiguousBoxes(t){let r=this.metadataReader.pos;for(;this.metadataReader.pos-r<=t-wt;)this.traverseBox()}traverseBox(){let t=this.metadataReader.pos,r=this.metadataReader.readBoxHeader(),a=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes(r.contentSize);break;case"mvhd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3,n===1?(this.metadataReader.pos+=16,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU64()):(this.metadataReader.pos+=8,this.movieTimescale=this.metadataReader.readU32(),this.movieDurationInTimescale=this.metadataReader.readU32())}break;case"trak":{let n={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,languageCode:te,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:null,currentFragmentState:null,fragments:[],fragmentsWithKeyFrame:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=n,this.readContiguousBoxes(r.contentSize),n.id!==-1&&n.timescale!==-1&&n.info!==null){if(n.info.type==="video"&&n.info.width!==-1){let s=n;n.inputTrack=new le(new kn(s)),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){let s=n;n.inputTrack=new Y(new wn(s)),this.tracks.push(n)}}this.currentTrack=null}break;case"tkhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();if(!((this.metadataReader.readU24()&1)!==0))break;if(s===0)this.metadataReader.pos+=8,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU32();else if(s===1)this.metadataReader.pos+=16,n.id=this.metadataReader.readU32(),this.metadataReader.pos+=4,n.durationInMovieTimescale=this.metadataReader.readU64();else throw new Error(`Incorrect track header version ${s}.`);this.metadataReader.pos+=2*4+2+2+2+2;let u=[this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_16_16(),this.metadataReader.readFixed_2_30()],d=De(Lt(Qo(u),90));m(d===0||d===90||d===180||d===270),n.rotation=d}break;case"elst":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=!1,c=0,u=this.metadataReader.readU32();for(let d=0;d<u;d++){let l=s===1?this.metadataReader.readU64():this.metadataReader.readU32(),p=s===1?this.metadataReader.readI64():this.metadataReader.readI32(),h=this.metadataReader.readFixed_16_16();if(l!==0){if(o){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){c+=l;continue}if(h!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}n.editListPreviousSegmentDurations=c,n.editListOffset=p,o=!0}}}break;case"mdhd":{let n=this.currentTrack;m(n);let s=this.metadataReader.readU8();this.metadataReader.pos+=3,s===0?(this.metadataReader.pos+=8,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU32()):s===1&&(this.metadataReader.pos+=16,n.timescale=this.metadataReader.readU32(),n.durationInMediaTimescale=this.metadataReader.readU64());let o=this.metadataReader.readU16();if(o>0){n.languageCode="";for(let c=0;c<3;c++)n.languageCode=String.fromCharCode(96+(o&31))+n.languageCode,o>>=5;lt(n.languageCode)||(n.languageCode=te)}}break;case"hdlr":{let n=this.currentTrack;m(n),this.metadataReader.pos+=8;let s=this.metadataReader.readAscii(4);s==="vide"?n.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:s==="soun"&&(n.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{let n=this.currentTrack;m(n),n.sampleTableByteOffset=t,this.readContiguousBoxes(r.contentSize)}break;case"stsd":{let n=this.currentTrack;if(m(n),n.info===null||n.sampleTable)break;let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=this.metadataReader.readU32();for(let c=0;c<o;c++){let u=this.metadataReader.pos,d=this.metadataReader.readBoxHeader(),l=d.name.toLowerCase();if(n.info.type==="video")l==="avc1"?n.info.codec="avc":l==="hvc1"||l==="hev1"?n.info.codec="hevc":l==="vp08"?n.info.codec="vp8":l==="vp09"?n.info.codec="vp9":l==="av01"?n.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${d.name}').`),this.metadataReader.pos+=6*1+2+2+2+3*4,n.info.width=this.metadataReader.readU16(),n.info.height=this.metadataReader.readU16(),this.metadataReader.pos+=50,this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos);else{l==="mp4a"||(l==="opus"?n.info.codec="opus":l==="flac"?n.info.codec="flac":l==="twos"||l==="sowt"||l==="raw "||l==="in24"||l==="in32"||l==="fl32"||l==="fl64"||l==="lpcm"||l==="ipcm"||l==="fpcm"||(l==="ulaw"?n.info.codec="ulaw":l==="alaw"?n.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${d.name}').`))),this.metadataReader.pos+=6*1+2;let p=this.metadataReader.readU16();this.metadataReader.pos+=3*2;let h=this.metadataReader.readU16(),f=this.metadataReader.readU16();this.metadataReader.pos+=2*2;let 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&&(n.info.codec=C?"pcm-f32be":"pcm-f32"):x&1<<b-1?b===1?n.info.codec="pcm-s8":b===2?n.info.codec=C?"pcm-s16be":"pcm-s16":b===3?n.info.codec=C?"pcm-s24be":"pcm-s24":b===4&&(n.info.codec=C?"pcm-s32be":"pcm-s32"):b===1&&(n.info.codec="pcm-u8")),n.info.codec===null&&console.warn("Unsupported PCM format.")}}}n.info.numberOfChannels=h,n.info.sampleRate=k,l==="twos"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${f} for codec 'twos'.`),n.info.codec=null):l==="sowt"?f===8?n.info.codec="pcm-s8":f===16?n.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${f} for codec 'sowt'.`),n.info.codec=null):l==="raw "?n.info.codec="pcm-u8":l==="in24"?n.info.codec="pcm-s24be":l==="in32"?n.info.codec="pcm-s32be":l==="fl32"?n.info.codec="pcm-f32be":l==="fl64"?n.info.codec="pcm-f64be":l==="ipcm"?n.info.codec="pcm-s16be":l==="fpcm"&&(n.info.codec="pcm-f32be"),this.readContiguousBoxes(u+d.totalSize-this.metadataReader.pos)}}}break;case"avcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"hvcC":{let n=this.currentTrack;m(n&&n.info),n.info.codecDescription=this.metadataReader.readBytes(r.contentSize)}break;case"vpcC":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8(),o=this.metadataReader.readU8(),c=this.metadataReader.readU8(),u=c>>4,d=c>>1&7,l=c&1,p=this.metadataReader.readU8(),h=this.metadataReader.readU8(),f=this.metadataReader.readU8();n.info.vp9CodecInfo={profile:s,level:o,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:l,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:f}}break;case"av1C":{let n=this.currentTrack;m(n&&n.info?.type==="video"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=s>>5,c=s&31,u=this.metadataReader.readU8(),d=u>>7,l=u>>6&1,p=u>>5&1,h=u>>4&1,f=u>>3&1,k=u>>2&1,g=u&3,b=o==2&&l?p?12:10:l?10:8;n.info.av1CodecInfo={profile:o,level:c,tier:d,bitDepth:b,monochrome:h,chromaSubsamplingX:f,chromaSubsamplingY:k,chromaSamplePosition:g}}break;case"colr":{let n=this.currentTrack;if(m(n&&n.info?.type==="video"),this.metadataReader.readAscii(4)!=="nclx")break;let o=this.metadataReader.readU16(),c=this.metadataReader.readU16(),u=this.metadataReader.readU16(),d=!!(this.metadataReader.readU8()&128);n.info.colorSpace={primaries:kr[o],transfer:wr[c],matrix:Tr[u],fullRange:d}}break;case"wave":this.readContiguousBoxes(r.contentSize);break;case"esds":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=this.metadataReader.readU8();m(s===3),this.metadataReader.readIsomVariableInteger(),this.metadataReader.pos+=2;let o=this.metadataReader.readU8(),c=(o&128)!==0,u=(o&64)!==0,d=(o&32)!==0;if(c&&(this.metadataReader.pos+=2),u){let 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?(n.info.codec="aac",n.info.aacCodecInfo={isMpeg2:f===103}):f===105||f===107?n.info.codec="mp3":f===221?n.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${f}) - discarding track.`),this.metadataReader.pos+=12,p>this.metadataReader.pos-h){let k=this.metadataReader.readU8();m(k===5);let g=this.metadataReader.readIsomVariableInteger();if(n.info.codecDescription=this.metadataReader.readBytes(g),n.info.codec==="aac"){let b=Hi(n.info.codecDescription);b.numberOfChannels!==null&&(n.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(n.info.sampleRate=b.sampleRate)}}}break;case"enda":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.readU16()&255&&(n.info.codec==="pcm-s16be"?n.info.codec="pcm-s16":n.info.codec==="pcm-s24be"?n.info.codec="pcm-s24":n.info.codec==="pcm-s32be"?n.info.codec="pcm-s32":n.info.codec==="pcm-f32be"?n.info.codec="pcm-f32":n.info.codec==="pcm-f64be"&&(n.info.codec="pcm-f64"))}break;case"pcmC":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let o=!!(this.metadataReader.readU8()&1),c=this.metadataReader.readU8();n.info.codec==="pcm-s16be"?o?c===16?n.info.codec="pcm-s16":c===24?n.info.codec="pcm-s24":c===32?n.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):c===16?n.info.codec="pcm-s16be":c===24?n.info.codec="pcm-s24be":c===32?n.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${c}.`),n.info.codec=null):n.info.codec==="pcm-f32be"&&(o?c===32?n.info.codec="pcm-f32":c===64?n.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null):c===32?n.info.codec="pcm-f32be":c===64?n.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${c}.`),n.info.codec=null));break}case"dOps":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=1;let s=this.metadataReader.readU8(),o=this.metadataReader.readU16(),c=this.metadataReader.readU32(),u=this.metadataReader.readI16(),d=this.metadataReader.readU8(),l;d!==0?l=this.metadataReader.readBytes(2+s):l=new Uint8Array(0);let p=new Uint8Array(19+l.byteLength),h=new DataView(p.buffer);h.setUint32(0,1332770163,!1),h.setUint32(4,1214603620,!1),h.setUint8(8,1),h.setUint8(9,s),h.setUint16(10,o,!0),h.setUint32(12,c,!0),h.setInt16(16,u,!0),h.setUint8(18,d),p.set(l,19),n.info.codecDescription=p,n.info.numberOfChannels=s,n.info.sampleRate=c}break;case"dfLa":{let n=this.currentTrack;m(n&&n.info?.type==="audio"),this.metadataReader.pos+=4;let s=127,o=128,c=this.metadataReader.pos;for(;this.metadataReader.pos<a;){let h=this.metadataReader.readU8(),f=this.metadataReader.readU24();if((h&s)===0){this.metadataReader.pos+=10;let g=this.metadataReader.readU32(),b=g>>>12,w=(g>>9&7)+1;n.info.sampleRate=b,n.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),n.info.codecDescription=l}break;case"stts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0,c=0;for(let u=0;u<s;u++){let d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleTimingEntries.push({startIndex:o,startDecodeTimestamp:c,count:d,delta:l}),o+=d,c+=d*l}}break;case"ctts":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=0;for(let c=0;c<s;c++){let u=this.metadataReader.readU32(),d=this.metadataReader.readI32();n.sampleTable.sampleCompositionTimeOffsets.push({startIndex:o,count:u,offset:d}),o+=u}}break;case"stsz":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32(),o=this.metadataReader.readU32();if(s===0)for(let c=0;c<o;c++){let u=this.metadataReader.readU32();n.sampleTable.sampleSizes.push(u)}else n.sampleTable.sampleSizes.push(s)}break;case"stz2":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,this.metadataReader.pos+=3;let s=this.metadataReader.readU8(),o=this.metadataReader.readU32(),c=this.metadataReader.readBytes(Math.ceil(o*s/8)),u=new q(c);for(let d=0;d<o;d++){let l=u.readBits(s);n.sampleTable.sampleSizes.push(l)}}break;case"stss":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4,n.sampleTable.keySampleIndices=[];let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32()-1;n.sampleTable.keySampleIndices.push(c)}n.sampleTable.keySampleIndices[0]!==0&&n.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let c=0;c<s;c++){let u=this.metadataReader.readU32()-1,d=this.metadataReader.readU32(),l=this.metadataReader.readU32();n.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:l})}let o=0;for(let c=0;c<n.sampleTable.sampleToChunk.length;c++)if(n.sampleTable.sampleToChunk[c].startSampleIndex=o,c<n.sampleTable.sampleToChunk.length-1){let d=n.sampleTable.sampleToChunk[c+1].startChunkIndex-n.sampleTable.sampleToChunk[c].startChunkIndex;o+=d*n.sampleTable.sampleToChunk[c].samplesPerChunk}}break;case"stco":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU32();n.sampleTable.chunkOffsets.push(c)}}break;case"co64":{let n=this.currentTrack;if(m(n),!n.sampleTable)break;this.metadataReader.pos+=4;let s=this.metadataReader.readU32();for(let o=0;o<s;o++){let c=this.metadataReader.readU64();n.sampleTable.chunkOffsets.push(c)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(r.contentSize);break;case"mehd":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=n===1?this.metadataReader.readU64():this.metadataReader.readU32();this.movieDurationInTimescale=s}break;case"trex":{this.metadataReader.pos+=4;let n=this.metadataReader.readU32(),s=this.metadataReader.readU32(),o=this.metadataReader.readU32(),c=this.metadataReader.readU32(),u=this.metadataReader.readU32();this.fragmentTrackDefaults.push({trackId:n,defaultSampleDescriptionIndex:s,defaultSampleDuration:o,defaultSampleSize:c,defaultSampleFlags:u})}break;case"tfra":{let n=this.metadataReader.readU8();this.metadataReader.pos+=3;let s=this.metadataReader.readU32(),o=this.tracks.find(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=n===1?this.metadataReader.readU64():this.metadataReader.readU32(),x=n===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),he(this.fragments,this.currentFragment,n=>n.moofOffset);for(let[,n]of this.currentFragment.trackData){let s=n.samples[0],o=z(n.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 n=this.currentFragment.trackData.get(this.currentTrack.id);if(n){he(this.currentTrack.fragments,this.currentFragment,c=>c.moofOffset),n.firstKeyFrameTimestamp!==null&&he(this.currentTrack.fragmentsWithKeyFrame,this.currentFragment,c=>c.moofOffset);let{currentFragmentState:o}=this.currentTrack;m(o),o.startTimestamp!==null&&(ja(n,o.startTimestamp),n.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{m(this.currentFragment),this.metadataReader.pos+=1;let n=this.metadataReader.readU24(),s=!!(n&1),o=!!(n&2),c=!!(n&8),u=!!(n&16),d=!!(n&32),l=!!(n&65536),p=!!(n&131072),h=this.metadataReader.readU32(),f=this.tracks.find(g=>g.id===h);if(!f)break;let 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 n=this.currentTrack;if(!n)break;m(n.currentFragmentState);let s=this.metadataReader.readU8();this.metadataReader.pos+=3;let o=s===0?this.metadataReader.readU32():this.metadataReader.readU64();n.currentFragmentState.startTimestamp=o}break;case"trun":{let n=this.currentTrack;if(!n)break;if(m(this.currentFragment),m(n.currentFragmentState),this.currentFragment.trackData.has(n.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let s=this.metadataReader.readU8(),o=this.metadataReader.readU24(),c=!!(o&1),u=!!(o&4),d=!!(o&256),l=!!(o&512),p=!!(o&1024),h=!!(o&2048),f=this.metadataReader.readU32(),k=n.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(n.id,C);for(let T=0;T<f;T++){let S;d?S=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleDuration!==null),S=n.currentFragmentState.defaultSampleDuration);let v;l?v=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleSize!==null),v=n.currentFragmentState.defaultSampleSize);let E;p?E=this.metadataReader.readU32():(m(n.currentFragmentState.defaultSampleFlags!==null),E=n.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[z(C.presentationTimestamps).sampleIndex];C.startTimestamp=x.presentationTimestamp,C.endTimestamp=y.presentationTimestamp+y.duration,this.currentFragment.implicitBaseDataOffset=b}break}this.metadataReader.pos=a}},_i=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 ut(e*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=$a(a,r),s=await this.fetchPacketForSampleIndex(n,t);return!Ga(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 n=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<n.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),n=$a(a,r),s=n===-1?-1:Ho(a,n),o=await this.fetchPacketForSampleIndex(s,t);return!Ga(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=Ko(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 n=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=n.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=Lo(r,e);if(!a)return null;let n;t.metadataOnly?n=ae:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(a.chunkOffset,a.chunkOffset+a.chunkSize),this.internalTrack.demuxer.chunkReader.pos=a.sampleOffset,n=this.internalTrack.demuxer.chunkReader.readBytes(a.sampleSize));let s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new M(n,a.isKeyFrame?"key":"delta",s,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];m(n);let s;r.metadataOnly?s=ae:(await this.internalTrack.demuxer.chunkReader.reader.loadRange(e.dataStart,e.dataEnd),this.internalTrack.demuxer.chunkReader.pos=n.byteOffset,s=this.internalTrack.demuxer.chunkReader.readBytes(n.byteSize));let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,u=new M(s,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}findSampleInFragmentsForTimestamp(e){let t=V(this.internalTrack.fragments,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.fragments[t].trackData.get(this.internalTrack.id),o=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,n=!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=Sr(o.presentationTimestamps,d=>o.samples[d.sampleIndex].isKeyFrame&&d.presentationTimestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].sampleIndex,n=e<o.endTimestamp}return{fragmentIndex:r,sampleIndex:a,correctSampleFound:n}}async performFragmentedLookup(e,t,r,a){let n=this.internalTrack.demuxer,s=await n.fragmentLookupMutex.acquire();try{let{fragmentIndex:o,sampleIndex:c,correctSampleFound:u}=e();if(u){let x=this.internalTrack.fragments[o];return this.fetchPacketInFragment(x,c,a)}let d=n.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+Le);let x=d.pos,y=d.readBoxHeader();if(y.name==="moof"){let T=H(n.fragments,x,_=>_.moofOffset),S;T===-1?(d.pos=x,S=await n.readFragment()):S=n.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()}}},kn=class extends _i{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&&Nr(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Lr(t.data)}return{codec:Ar(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}},wn=class extends _i{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:Rr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},$a=(i,e)=>{if(i.presentationTimestamps){let t=V(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{let t=V(i.sampleTimingEntries,e,a=>a.startDecodeTimestamp);if(t===-1)return-1;let r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},Lo=(i,e)=>{let t=V(i.sampleTimingEntries,e,b=>b.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta,s=V(i.sampleCompositionTimeOffsets,e,b=>b.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&e-o.startIndex<o.count&&(n+=o.offset);let c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],u=V(i.sampleToChunk,e,b=>b.startSampleIndex),d=i.sampleToChunk[u];m(d);let l=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),p=i.chunkOffsets[l],h=d.startSampleIndex+(l-d.startChunkIndex)*d.samplesPerChunk,f=0,k=p;if(i.sampleSizes.length===1)k+=c*(e-h),f+=c*d.samplesPerChunk;else for(let b=h;b<h+d.samplesPerChunk;b++){let w=i.sampleSizes[b];b<e&&(k+=w),f+=w}let g=r.delta;if(i.presentationTimestamps){let b=i.presentationTimestampIndexMap[e];m(b!==void 0),b<i.presentationTimestamps.length-1&&(g=i.presentationTimestamps[b+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:g,sampleOffset:k,sampleSize:c,chunkOffset:p,chunkSize:f,isKeyFrame:i.keySampleIndices?H(i.keySampleIndices,e,b=>b)!==-1:!0}},Ho=(i,e)=>{if(!i.keySampleIndices)return e;let t=V(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t]??-1},Ko=(i,e)=>{if(!i.keySampleIndices)return e+1;let t=V(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},ja=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(let t of i.samples)t.presentationTimestamp+=e;for(let t of i.presentationTimestamps)t.presentationTimestamp+=e},Qo=i=>{let[e,,,t]=i,r=Math.hypot(e,t),a=e/r,n=t/r;return-Math.atan2(n,a)*(180/Math.PI)},Ga=i=>i.sampleSizes.length===0;var Tn=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],Ai=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 Ze(t._mainReader),this.clusterReader=new Ze(new me(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 Jr({isWebM:this.isWebM,hasVideo:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="video")),hasAudio:this.segments.some(a=>a.tracks.some(n=>n.info?.type==="audio")),codecStrings:r.filter(Boolean)})}readMetadata(){return this.readMetadataPromise??=(async()=>{this.metadataReader.pos=0;let t=await this.input.source.getSize();for(;this.metadataReader.pos<=t-Oe;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+St);let r=this.metadataReader.readElementHeader();if(!r)break;let a=r.id,n=r.size,s=this.metadataReader.pos;if(a===440786851)Je(n),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+n),this.readContiguousElements(this.metadataReader,n);else if(a===408125543){if(await this.readSegment(n),n===null)break}else if(a===524531317){n===null&&(n=(await this.clusterReader.searchForNextElementId(Zr,t)??t)-s);let o=z(this.segments);o&&(o.elementEndPos=s+n)}Je(n),this.metadataReader.pos=s+n}})()}async readSegment(t){let r=this.metadataReader.pos;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:r,elementEndPos:t===null?await this.input.source.getSize():r+t,clusterSeekStartPos:r,clusters:[],clusterLookupMutex:new ne},this.segments.push(this.currentSegment),await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+2**14);let a=!1;for(;this.metadataReader.pos<=this.currentSegment.elementEndPos-Oe;){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+St);let u=this.metadataReader.pos,d=this.metadataReader.readElementHeader();if(!d)break;let{id:l,size:p}=d,h=this.metadataReader.pos,f=Tn.findIndex(k=>k.id===l);if(f!==-1){let k=Tn[f].flag;this.currentSegment[k]=!0,Je(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 Tn){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&&(Je(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 n=this.currentSegment.tracks.map(u=>u.id),s=new Set,o=null,c=null;for(let u of this.currentSegment.cuePoints){if(u.clusterPosition!==o){for(let l of s)m(c),this.currentSegment.tracks.find(h=>h.id===l).cuePoints.push(c);for(let l of n)s.add(l)}if(c=u,!s.has(u.trackId))continue;this.currentSegment.tracks.find(l=>l.id===u.trackId).cuePoints.push(u),s.delete(u.trackId),o=u.clusterPosition}for(let u of s)m(c),this.currentSegment.tracks.find(l=>l.id===u).cuePoints.push(c);for(let u of this.currentSegment.tracks)u.cuePoints.sort((d,l)=>d.time-l.time);this.currentSegment=null}async readCluster(t){await this.metadataReader.reader.loadRange(this.metadataReader.pos,this.metadataReader.pos+St);let r=this.metadataReader.pos,a=this.metadataReader.readElementHeader();m(a);let n=a.id,s=a.size,o=this.metadataReader.pos;s===null&&(this.clusterReader.pos=o,s=(await this.clusterReader.searchForNextElementId(Zr,t.elementEndPos)??t.elementEndPos)-o),m(n===524531317),this.clusterReader.pos=o,await this.clusterReader.reader.loadRange(this.clusterReader.pos,this.clusterReader.pos+s);let c={elementStartPos:r,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map,nextCluster:null,isKnownToBeFirstCluster:!1};this.currentCluster=c,this.readContiguousElements(this.clusterReader,s);for(let[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=qo(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[z(d.presentationTimestamps).blockIndex];d.startTimestamp=f.timestamp,d.endTimestamp=k.timestamp+k.duration,l&&(he(l.clusters,c,b=>b.elementStartPos),d.firstKeyFrameTimestamp!==null&&he(l.clustersWithKeyFrame,c,b=>b.elementStartPos))}return he(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 n=t[a];if(n.lacing===0)continue;let s=n.data,o=0,c=[],u=s[o]+1;switch(o++,n.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=tn(s,o),p=l.value;c.push(p),o+=l.width;let h=p;for(let f=1;f<u-1;f++){let k=tn(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=n.duration||u*(r?.defaultDuration??0),k=n.timestamp+f*l/u,g=f/u;t.splice(a+l,0,{timestamp:k,duration:g,isKeyFrame:n.isKeyFrame,referencedTimestamps:n.referencedTimestamps,data:h,lacing:0}),d+=p}a+=u,a--}}readContiguousElements(t,r){let a=t.pos;for(;t.pos-a<=r-Oe&&this.traverseElement(t););}traverseElement(t){let r=t.readElementHeader();if(!r)return!1;let{id:a,size:n}=r,s=t.pos;switch(Je(n),a){case 17026:this.isWebM=t.readAsciiString(n)==="webm";break;case 19899:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(t,n),(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(n)}break;case 21420:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=t.readUnsignedInt(n)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=t.readUnsignedInt(n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=t.readFloat(n)}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,n),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===ce.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ce.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ce.vp8?this.currentTrack.info.codec="vp8":c===ce.vp9?this.currentTrack.info.codec="vp9":c===ce.av1&&(this.currentTrack.info.codec="av1");let u=this.currentTrack,d=new le(new yn(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===ce.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===ce.mp3?this.currentTrack.info.codec="mp3":c===ce.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ce.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ce.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 Y(new Sn(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(n)}break;case 131:{if(!this.currentTrack)break;let o=t.readUnsignedInt(n);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(n)||(this.currentSegment.tracks.pop(),this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!t.readUnsignedInt(n)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=t.readAsciiString(n)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=t.readBytes(n)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*t.readUnsignedInt(n)/1e9}break;case 2274716:{if(!this.currentTrack)break;this.currentTrack.languageCode=t.readAsciiString(n),lt(this.currentTrack.languageCode)||(this.currentTrack.languageCode=te)}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,n)}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=t.readUnsignedInt(n)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=t.readUnsignedInt(n)}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(t,n)}break;case 21937:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=t.readUnsignedInt(n),c=Tr[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(n)===2}break;case 21946:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=t.readUnsignedInt(n),c=wr[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(n),c=kr[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(t,n)}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let c=-t.readFloat(n);try{this.currentTrack.info.rotation=De(c)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(t,n)}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=t.readFloat(n)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=t.readUnsignedInt(n)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=t.readUnsignedInt(n)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(t,n),this.currentCueTime=null}break;case 179:this.currentCueTime=t.readUnsignedInt(n);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,n),(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(n)}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(n)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=t.readUnsignedInt(n)}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(n-(t.pos-s)),lacing:l})}break;case 160:{if(!this.currentCluster)break;if(this.readContiguousElements(t,n),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(n-(t.pos-s)),lacing:d},l.blocks.push(this.currentBlock)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=t.readUnsignedInt(n)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let o=t.readSignedInt(n);this.currentBlock.referencedTimestamps.push(o)}break}return t.pos=s+n,!0}},Ri=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,n=>n.elementStartPos),blockIndex:0,correctBlockFound:!0};r=r.nextCluster}}return{clusterIndex:-1,blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}intoTimescale(e){return ut(e*this.internalTrack.segment.timestampFactor,14)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(()=>this.findBlockInClustersForTimestamp(r),r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");let a=r.cluster.trackData.get(this.internalTrack.id),n=H(this.internalTrack.clusters,r.cluster.elementStartPos,s=>s.elementStartPos);return m(n!==-1),this.performClusterLookup(()=>{if(r.blockIndex+1<a.blocks.length)return{clusterIndex:n,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:n,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),n=H(this.internalTrack.clusters,r.cluster.elementStartPos,s=>s.elementStartPos);return m(n!==-1),this.performClusterLookup(()=>{let s=a.blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(s!==-1)return{clusterIndex:n,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:n,blockIndex:-1,correctBlockFound:!1}}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];m(n);let s=r.metadataOnly?ae:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,u=new M(s,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}findBlockInClustersForTimestamp(e){let t=V(this.internalTrack.clusters,e,n=>n.trackData.get(this.internalTrack.id).startTimestamp),r=-1,a=!1;if(t!==-1){let s=this.internalTrack.clusters[t].trackData.get(this.internalTrack.id),o=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,n=!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=Sr(o.presentationTimestamps,d=>o.blocks[d.blockIndex].isKeyFrame&&d.timestamp<=e);m(c!==-1),a=o.presentationTimestamps[c].blockIndex,n=e<o.endTimestamp}return{clusterIndex:r,blockIndex:a,correctBlockFound:n}}async performClusterLookup(e,t,r,a){let{demuxer:n,segment:s}=this.internalTrack,o=await s.clusterLookupMutex.acquire();try{let{clusterIndex:c,blockIndex:u,correctBlockFound:d}=e();if(d){let y=this.internalTrack.clusters[c];return this.fetchPacketInCluster(y,u,a)}let l=n.metadataReader,p=n.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-Oe;){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+St);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,we=>we.elementStartPos),_;A===-1?(l.pos=y,_=await n.readCluster(s)):_=s.clusters[A],h&&(h.nextCluster=_),h=_,w&&(_.isKnownToBeFirstCluster=!0,w=!1);let{clusterIndex:B,blockIndex:N,correctBlockFound:Z}=e();if(Z){let we=this.internalTrack.clusters[B];return this.fetchPacketInCluster(we,N,a)}B!==-1&&(f=B,k=N)}if(v===null){S===524531317?(m(h),v=h.elementEndPos-E):(p.pos=E,v=(await p.searchForNextElementId(Zr,s.elementEndPos)??s.elementEndPos)-E);let A=E+v;if(A>s.elementEndPos-Oe)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()}}},yn=class extends Ri{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:Ar({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?zr(t.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&t?Wr(t.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&t?Nr(t.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&t?Lr(t.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},Sn=class extends Ri{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:Rr({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}},qo=i=>{let e=new Map;for(let n=0;n<i.length;n++){let s=i[n];e.set(s.timestamp,s)}let t=new Set,r=[],a=n=>{if(!t.has(n)){t.add(n);for(let s=0;s<n.referencedTimestamps.length;s++){let o=n.referencedTimestamps[s],c=e.get(o);c&&a(c)}r.push(n)}};for(let n=0;n<i.length;n++)a(i[n]);return r};var Vt=class{constructor(e){this.reader=e;this.pos=0;this.fileSize=null}readBytes(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);return this.pos+=e,new Uint8Array(t.buffer,r,e)}readU16(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+2);return this.pos+=2,e.getUint16(t,!1)}readU32(){let{view:e,offset:t}=this.reader.getViewAndOffset(this.pos,this.pos+4);return this.pos+=4,e.getUint32(t,!1)}readAscii(e){let{view:t,offset:r}=this.reader.getViewAndOffset(this.pos,this.pos+e);this.pos+=e;let a="";for(let n=0;n<e;n++)a+=String.fromCharCode(t.getUint8(r+n));return a}readId3(){return this.readAscii(3)!=="ID3"?(this.pos-=3,null):(this.pos+=3,{size:$o(this.readU32())})}readNextFrameHeader(e){for(m(this.fileSize),e??=this.fileSize;this.pos<=e-4;){let t=this.readU32();this.pos-=4;let r=ii(t,this);if(r)return r}return null}},$o=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var Fi=class extends ue{constructor(t){super(t);this.metadataPromise=null;this.firstFrameHeader=null;this.loadedSamples=[];this.tracks=[];this.loadingMutex=new ne;this.lastLoadedPos=0;this.fileSize=0;this.nextTimestampInSamples=0;this.reader=new Vt(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 Y(new xn(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 n=this.reader.readId3();n&&(this.reader.pos+=n.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=xt(r.mpegVersionId,r.channel);this.reader.pos=r.startPos+a;let n=this.reader.readU32(),s=n===Ct||n===ti;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()}},xn=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=ae:(this.demuxer.reader.pos=r.dataStart,a=this.demuxer.reader.readBytes(r.dataSize)),new M(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,n=>n.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 Oi=class extends ue{constructor(t){super(t);this.readingMutex=new ne;this.metadataPromise=null;this.fileSize=null;this.bitstreams=[];this.tracks=[];this.reader=new vt(new me(t.source,64*2**20))}async readMetadata(){return this.metadataPromise??=(async()=>{for(this.fileSize=await this.input.source.getSize();this.reader.pos<this.fileSize-Pt;){await this.reader.reader.loadRange(this.reader.pos,this.reader.pos+tt);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 Y(new vn(t,this))))}})()}async readVorbisMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n||(a=await this.findNextPacketStart(this.reader,n),!a))return;let s=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!s||n.data[0]!==3||s.data[0]!==5)return;let o=[],c=p=>{for(;o.push(Math.min(255,p)),!(p<255);)p-=255};c(t.data.length),c(n.data.length);let u=new Uint8Array(1+o.length+t.data.length+n.data.length+s.data.length);u[0]=o.length,u.set(o,1),u.set(t.data,1+o.length),u.set(n.data,1+o.length+t.data.length),u.set(s.data,1+o.length+t.data.length+n.data.length),r.codecInfo.codec="vorbis",r.description=u,r.lastMetadataPacket=s;let d=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:Hr(s.data).modeBlockflags}}async readOpusMetadata(t,r){let a=await this.findNextPacketStart(this.reader,t);if(!a)return;let n=await this.readPacket(this.reader,a.startPage,a.startSegmentIndex);if(!n)return;r.codecInfo.codec="opus",r.description=t.data,r.lastMetadataPacket=n;let s=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 n=0;for(let h=0;h<a;h++)n+=r.lacingValues[h];let s=r,o=n,c=a,u=[];e:for(;;){await t.reader.loadRange(s.dataStartPos,s.dataStartPos+s.dataSize),t.pos=s.dataStartPos;let h=t.readBytes(s.dataSize);for(;;){if(c===s.lacingValues.length){u.push(h.subarray(n,o));break}let f=s.lacingValues[c];if(o+=f,f<255){u.push(h.subarray(n,o));break e}c++}for(;;){if(t.pos=s.headerStartPos+s.totalSize,t.pos>=this.fileSize-Pt)return null;await t.reader.loadRange(t.pos,t.pos+tt);let f=t.readPageHeader();if(!f)return null;if(s=f,s.serialNumber===r.serialNumber)break}n=0,o=0,c=0}let d=u.reduce((h,f)=>h+f.length,0),l=new Uint8Array(d),p=0;for(let h=0;h<u.length;h++){let f=u[h];l.set(f,p),p+=f.length}return{data:l,endPage:s,endSegmentIndex:c}}async findNextPacketStart(t,r){if(m(this.fileSize!==null),r.endSegmentIndex<r.endPage.lacingValues.length-1)return{startPage:r.endPage,startSegmentIndex:r.endSegmentIndex+1};if(!!(r.endPage.headerType&4))return null;for(t.pos=r.endPage.headerStartPos+r.endPage.totalSize;;){if(t.pos>=this.fileSize-Pt)return null;await t.reader.loadRange(t.pos,t.pos+tt);let n=t.readPageHeader();if(!n)return null;if(n.serialNumber===r.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};t.pos=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let t=await Promise.all(this.tracks.map(r=>r.getCodecParameterString()));return ci({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)}},vn=class{constructor(e,t){this.bitstream=e;this.demuxer=t;this.encodedPacketToMetadata=new WeakMap;this.internalSampleRate=e.codecInfo.codec==="opus"?pt: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:n}=oi(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new M(r.metadataOnly?ae:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisBlockSize:n}),s}async getFirstPacket(e,t=!0){let r=t?await this.demuxer.readingMutex.acquire():null;try{m(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.demuxer.reader,this.bitstream.lastMetadataPacket);if(!a)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(this.demuxer.reader,a.startPage,a.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:null},e)}finally{r?.()}}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let a=this.encodedPacketToMetadata.get(e);if(!a)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(this.demuxer.reader,a.packet);if(!n)return null;let s=a.timestampInSamples+a.durationInSamples,o=await this.demuxer.readPacket(this.demuxer.reader,n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:s,vorbisLastBlocksize:a.vorbisBlockSize},t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{m(this.demuxer.fileSize!==null);let a=ut(e*this.internalSampleRate,14);if(a===0)return this.getFirstPacket(t,!1);if(a<0)return null;let n=this.demuxer.reader;m(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(n,this.bitstream.lastMetadataPacket);if(!s)return null;let o=s.startPage,c=this.demuxer.fileSize,u=[o];e:for(;o.headerStartPos+o.totalSize<c;){let x=o.headerStartPos,y=Math.floor((x+c)/2),T=y;for(;;){let S=Math.min(T+di,c-Pt);if(await n.reader.loadRange(T,S),n.pos=T,!n.findNextPageHeader(S)){c=y+Pt;continue e}await n.reader.loadRange(n.pos,n.pos+tt);let E=n.readPageHeader();m(E);let A=!1;if(E.serialNumber===this.bitstream.serialNumber)A=!0;else{await n.reader.loadRange(E.headerStartPos,E.headerStartPos+E.totalSize),n.pos=E.headerStartPos;let B=n.readBytes(E.totalSize);A=si(B)===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);){n.pos=l.headerStartPos+l.totalSize,await n.reader.loadRange(n.pos,n.pos+tt);let x=n.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:ae,endPage:g,endSegmentIndex:b};if(await this.demuxer.findNextPacketStart(n,x)){let T=Ya(p,l,h);m(T);let S=Xa(p,T.page,T.segmentIndex);S&&(l=S.page,h=S.segmentIndex)}else for(;;){let T=Ya(p,l,h);if(!T)break;let S=Xa(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(n,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(n,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)}},Xa=(i,e,t)=>{let r=e,a=t;e:for(;;){for(a--,a;a>=0;a--)if(r.lacingValues[a]<255){a++;break e}if(m(a===-1),!(r.headerType&1)){a=0;break}let s=Wi(i,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,a=r.lacingValues.length}if(m(a!==-1),a===r.lacingValues.length){let n=i[i.indexOf(r)+1];m(n),r=n,a=0}return{page:r,segmentIndex:a}},Ya=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let r=Wi(i,a=>a.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var ke=class{},Ut=class extends ke{async _getMajorBrand(e){if(await e._mainReader.source.getSize()<12)return null;let r=new Xe(e._mainReader);return r.pos=4,r.readAscii(4)!=="ftyp"?null:r.readAscii(4)}_createDemuxer(e){return new Ei(e)}},lr=class extends Ut{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}},mr=class extends Ut{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}};function jo(){return 5}var zt=class extends ke{async isSupportedEBMLOfDocType(e,t){if(await e._mainReader.source.getSize()<8)return!1;let a=new Ze(e._mainReader),n=a.readVarIntSize();if(n===null||(jo(),n<1||n>8)||a.readUnsignedInt(n)!==440786851)return!1;let o=a.readElementSize();if(o===null)return!1;let c=a.pos;for(;a.pos<=c+o-Oe;){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 Ai(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},fr=class extends zt{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},pr=class extends ke{async _canReadInput(e){let t=await e._mainReader.source.getSize();if(t<4)return!1;let r=new Vt(e._mainReader);r.fileSize=t;let a=r.readId3();a&&(r.pos+=a.size);let n=r.pos;await r.reader.loadRange(r.pos,r.pos+4096);let s=r.readNextFrameHeader(Math.min(n+4096,t));if(!s)return!1;if(a)return!0;r.pos=s.startPos+s.totalSize,await r.reader.loadRange(r.pos,r.pos+4);let o=r.readNextFrameHeader(r.pos+4);return!(!o||s.channel!==o.channel||s.sampleRate!==o.sampleRate)}_createDemuxer(e){return new Fi(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},hr=class extends ke{async _canReadInput(e){if(await e._mainReader.source.getSize()<12)return!1;let r=new it(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 fi(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},gr=class extends ke{async _canReadInput(e){return await e._mainReader.source.getSize()<4?!1:new vt(e._mainReader).readAscii(4)==="OggS"}_createDemuxer(e){return new Oi(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},Pn=new lr,In=new mr,En=new zt,_n=new fr,An=new pr,Rn=new hr,Fn=new gr,Za=[Pn,In,En,_n,Rn,Fn,An];var Wt=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 ke)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Pe))throw new TypeError("options.source must be a Source.");this._formats=e.formats,this._source=e.source,this._mainReader=new me(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 Ja=i=>{if(i!==void 0&&(!i||typeof i!="object"))throw new TypeError("options.video, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!$.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${$.join(", ")}.`);if(i?.bitrate!==void 0&&!(i.bitrate instanceof K)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(i?.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(i?.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(i?.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError('options.video.fit, when provided, must be one of "fill", "contain", or "cover".');if(i?.width!==void 0&&i.height!==void 0&&i.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(i?.rotate!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(i?.frameRate!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.")},es=i=>{if(i!==void 0&&(!i||typeof i!="object"))throw new TypeError("options.audio, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!X.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${X.join(", ")}.`);if(i?.bitrate!==void 0&&!(i.bitrate instanceof K)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(i?.numberOfChannels!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(i?.sampleRate!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.")},On=2,Mn=48e3,Mi=class i{constructor(e){this._addedCounts={video:0,audio:0,subtitle:0};this._totalTrackCount=0;this._trackPromises=[];this._executed=!1;this._synchronizer=new Bn;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 Wt))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Dt))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"&&Ja(e.video),typeof e.audio!="function"&&es(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 i(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),Ja(o),r++):o=this._options.video):s.isAudioTrack()?this._options.audio&&(typeof this._options.audio=="function"?(o=await this._options.audio(s,a),es(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 n=this.discardedTracks.filter(s=>s.reason!=="discarded_by_user");n.length>0&&console.warn("Some tracks had to be discarded from the conversion:",n)}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,n=De(e.rotation+(t.rotate??0)),s=this.output.format.supportsVideoRotationMetadata,[o,c]=n%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||n!==0&&!s,g=this.output.format.getSupportedVideoCodecs();if(!f&&!t.bitrate&&!k&&g.includes(r)&&(!t.codec||t.codec===r)){let b=new Ot(r);a=b,this._trackPromises.push((async()=>{await this._started;let w=new ge(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??jt,C=await Mr(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 Mt(x);a=y,k?this._trackPromises.push((async()=>{await this._started;let S=new _t(e,{width:u,height:d,fit:t.fit??"fill",rotation:n,poolSize:1}).canvases(this._startTimestamp,this._endTimestamp),v=t.frameRate,E=null,A=null,_=null,B=async N=>{m(E),m(v!==void 0);let Z=Math.round((N-A)*v);for(let we=1;we<Z;we++){let ot=new se(E,{timestamp:A+we/v,duration:1/v});await y.add(ot)}};for await(let{canvas:N,timestamp:Z,duration:we}of S){if(this._synchronizer.shouldWait(e.id,Z)&&await this._synchronizer.wait(Z),this._canceled)return;let ot=Math.max(Z-this._startTimestamp,0);if(_=Z+we,v!==void 0){let br=Math.floor(ot*v)/v;if(E!==null)if(br<=A){E=N,A=br;continue}else await B(br);ot=br}let Vn=new se(N,{timestamp:ot,duration:v!==void 0?1/v:we});await y.add(Vn),v!==void 0?(E=N,A=ot):Vn.close()}E&&(m(_!==null),m(v!==void 0),await B(Math.floor(_*v)/v)),y.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let T=new rt(e),S=t.frameRate,v=null,E=null,A=null,_=async B=>{m(v),m(S!==void 0);let N=Math.round((B-E)*S);for(let Z=1;Z<N;Z++)v.setTimestamp(E+Z/S),v.setDuration(1/S),await y.add(v);v.close()};for await(let B of T.samples(this._startTimestamp,this._endTimestamp)){if(this._synchronizer.shouldWait(e.id,B.timestamp)&&await this._synchronizer.wait(B.timestamp),this._canceled){v?.close();return}let N=Math.max(B.timestamp-this._startTimestamp,0);if(A=B.timestamp+B.duration,S!==void 0){let Z=Math.floor(N*S)/S;if(v!==null)if(Z<=E){v.close(),v=B,E=Z;continue}else await _(Z);N=Z,B.setDuration(1/S)}B.setTimestamp(N),await y.add(B),S!==void 0?(v=B,E=N):B.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:n}),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,n=e.numberOfChannels,s=e.sampleRate,o=await e.getFirstTimestamp(),c=t.numberOfChannels??n,u=t.sampleRate??s,d=c!==n||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 Bt(r);a=p,this._trackPromises.push((async()=>{await this._started;let h=new ge(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??jt,k=await ht(l,{numberOfChannels:c,sampleRate:u,bitrate:f});if(!k.some(g=>ye.includes(g))&&l.some(g=>ye.includes(g))&&(c!==On||u!==Mn)){let b=(await ht(l,{numberOfChannels:On,sampleRate:Mn,bitrate:f})).find(w=>ye.includes(w));b&&(d=!0,h=b,c=On,u=Mn)}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 at({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 He(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,n){let s=new at({codec:t,bitrate:n,onEncodedPacket:o=>this._reportProgress(e.id,o.timestamp+o.duration)});return this._trackPromises.push((async()=>{await this._started;let o=new Dn({sourceNumberOfChannels:e.numberOfChannels,sourceSampleRate:e.sampleRate,targetNumberOfChannels:r,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:d=>s.add(d)}),u=new He(e).samples(this._startTimestamp,this._endTimestamp);for await(let d of u){if(this._synchronizer.shouldWait(e.id,d.timestamp)&&await this._synchronizer.wait(d.timestamp),this._canceled)return;await o.add(d)}await o.finalize(),s.close(),this._synchronizer.closeTrack(e.id)})()),s}_reportProgress(e,t){if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)??-1/0));let r=0;for(let[,s]of this._maxTimestamps)r+=s;let a=r/this._totalTrackCount,n=G(a/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},ts=5,Bn=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<ts&&(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>=ts}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()}},Dn=class{constructor(e){this.sourceSampleRate=e.sourceSampleRate,this.targetSampleRate=e.targetSampleRate,this.sourceNumberOfChannels=e.sourceNumberOfChannels,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1,this.setupChannelMixer(),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels)}setupChannelMixer(){let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(r,a)=>r[a*e]:e===1&&t===4?this.channelMixer=(r,a,n)=>r[a*e]*+(n<2):e===1&&t===6?this.channelMixer=(r,a,n)=>r[a*e]*+(n===2):e===2&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .5*(r[n]+r[n+1])}:e===2&&t===4?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(r,a,n)=>r[a*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return .25*(r[n]+r[n+1]+r[n+2]+r[n+3])}:e===4&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return .5*(r[s+n]+r[s+n+2])}:e===4&&t===6?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]:n===2||n===3?0:r[s+n-2]}:e===6&&t===1?this.channelMixer=(r,a)=>{let n=a*e;return Math.SQRT1_2*(r[n]+r[n+1])+r[n+2]+.5*(r[n+4]+r[n+5])}:e===6&&t===2?this.channelMixer=(r,a,n)=>{let s=a*e;return r[s+n]+Math.SQRT1_2*(r[s+2]+r[s+n+4])}:e===6&&t===4?this.channelMixer=(r,a,n)=>{let s=a*e;return n<2?r[s+n]+Math.SQRT1_2*r[s+2]:r[s+n+2]}:this.channelMixer=(r,a,n)=>n<e?r[a*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let r=new Float32Array(t);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(e){if(!e||e._closed)return;let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(a,{planeIndex:0,format:"f32"});let n=e.timestamp-this.startTime,s=e.numberOfFrames/this.sourceSampleRate,o=Math.min(n+s,this.endTime-this.startTime),c=Math.floor(n*this.targetSampleRate),u=Math.ceil(o*this.targetSampleRate);for(let d=c;d<u;d++){if(d<this.bufferStartFrame)continue;for(;d>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=d-this.bufferStartFrame;m(l<this.bufferSizeInFrames);let f=(d/this.targetSampleRate-n)*this.sourceSampleRate,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 ie({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:t});await this.onSample(a),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};return os(Go);})();
if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Mediabunny)