=r)break;let f=Math.max(e,m.start);f>s&&this._throwDueToCacheMiss();let p=Math.min(r,m.end);fs&&this._throwDueToCacheMiss();let{promise:c,resolve:u,reject:l}=J();return this._pendingSlices.push({start:e,end:r,bytes:o,resolve:u,reject:l}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(d=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(m=>m.reject(d)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(d);else throw d})),c}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new ke);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel().catch(()=>{})}},mu={none:(i,t)=>({start:i,end:t}),fileSystem:(i,t)=>(i=Math.floor((i-65536)/65536)*65536,t=Math.ceil((t+65536)/65536)*65536,{start:i,end:t}),network:(i,t,e)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let n of e){let s=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(qa(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);t=Math.max(t,n.startPos+l)}}return t=Math.max(t,i+Rp),{start:i,end:t}}},fa=class{constructor(t){this.options=t;this.fileSize=null;this.nextAge=0;this.workers=[];this.cache=[];this.currentCacheSize=0;this.disposed=!1;this.queuedReads=[]}read(t,e,r,n){g(!this.disposed);let a=this.options.prefetchProfile(t,e,this.workers),s=Math.max(a.start,r),o=Math.min(a.end,this.fileSize??1/0,n);g(s<=t&&e<=o);let c=null,u=Q(this.cache,t,A=>A.start),l=u!==-1?this.cache[u]:null;l&&l.start<=t&&e<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});let d=Q(this.cache,s,A=>A.start),m=c?null:new Uint8Array(e-t),f=0,p=s,b=[];if(d!==-1){for(let A=d;A=o)break;if(x.end<=s)continue;let C=Math.max(s,x.start),P=Math.min(o,x.end);if(g(C<=P),p=m.length&&(c={bytes:m,view:N(m),offset:t}),b.length===0)return g(c),c;let{promise:h,resolve:y,reject:k}=J(),T=[];for(let A of b){let x=Math.max(t,A.start),C=Math.min(e,A.end);x===A.start&&C===A.end?T.push(A):xI.hole.start),S=P!==-1?this.queuedReads[P]:null;for(S&&A.start<=S.hole.end?(S.hole.end=Math.max(S.hole.end,A.end),S.strictTarget&&=x,w&&S.pendingSlices.push(w)):(P++,S={hole:{start:A.start,end:A.end},strictTarget:x,pendingSlices:w?[w]:[],age:this.nextAge++},this.queuedReads.splice(P,0,S));P+1S.hole.end)break;S.hole.end=Math.max(S.hole.end,I.hole.end),S.pendingSlices.push(...I.pendingSlices),S.strictTarget&&=I.strictTarget,S.age=Math.min(S.age,I.age),this.queuedReads.splice(P+1,1)}}}return c?h.catch(A=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(A);else throw A}):(g(m),c=h.then(A=>A&&{bytes:A,view:N(A),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(qa(e.start-131072,e.start,t.currentPos,t.targetPos)){t.targetPos=Math.max(t.targetPos,e.end);for(let a=0;a=this.options.maxWorkerCount){let a=null,s=null;for(let o=0;o{if(t.running=!1,t.pendingSlices.length>0)t.pendingSlices.forEach(r=>r.reject(e)),t.pendingSlices.length=0;else if(!t.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}).finally(()=>{if(!t.running&&this.queuedReads.length>0){let e=0;for(let a=1;at.targetPos&&(t.targetPos=t.currentPos,this.checkQueuedReadsAgainstWorker(t));for(let a=0;al.start&&(l.start=n),l.end<=l.start&&(s.holes.splice(u,1),u--)}s.holes.length===0&&(s.resolve(s.bytes),t.pendingSlices.splice(a,1),a--)}for(let a=0;at){n.resolve(null),e.pendingSlices.splice(r,1),r--;break}}}for(let e=0;e=t){for(let n of r.pendingSlices)n.resolve(null);this.queuedReads.splice(e,1),e--}else if(r.hole.end>t){r.hole.end=t,r.strictTarget=!0;for(let n=0;n=t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}}}}signalWorkerStoppedRunning(t){t.running=!1,t.aborted||(t.pendingSlices.length=0)}onWorkerFinished(t){let e=this.workers.indexOf(t);g(e!==-1),t.running=!1,this.workers.splice(e,1),this.options.onIdleWorkerRemoved?.(t),this.fileSize===null&&this.supplyFileSize(t.currentPos);for(let r of t.pendingSlices)r.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=Q(this.cache,t.start,r=>r.start)+1;if(e>0){let r=this.cache[e-1];if(r.end>=t.end)return;if(r.end>t.start){let n=new Uint8Array(t.end-r.start);n.set(r.bytes,0),n.set(t.bytes,t.start-r.start),this.currentCacheSize+=t.end-r.end,r.bytes=n,r.view=N(n),r.end=t.end,e--,t=r}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length;for(let r=e+1;r=n.end){this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length,r--;continue}let a=new Uint8Array(n.end-t.start);a.set(t.bytes,0),a.set(n.bytes,n.start-t.start),this.currentCacheSize-=t.end-n.start,t.bytes=a,t.view=N(a),t.end=n.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,n=this.cache[0];for(let a=1;athis._length)return null;let s=this._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+a),o=c=>c?(c.offset-=this._offset,c):null;return _(s)?s.then(o):o(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var Dp=/^0[xX][0-9a-fA-F]+$/,Vp=/^data:.*;base64,/i,pa=class extends Ys{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await zr(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,r=Math.max(0,1e3*this.refreshInterval-e);return r<=50?0:r}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){var A=[];try{let S=st(A,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let I=new ei(S.source);let E=await I.requestEntireFile();g(E);e=ro(E,E.length,{ignore:$s});S.source instanceof rt&&(this.rootPath=S.source.rootPath)}catch(x){var C=x,P=!0}finally{ot(A,C,P)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=new gn(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,u=null,l=0,d=null,m=null,f=null,p=null,b=null,h=null,y=!1,k=Z(this.segments)??null,T=S=>{let I=S.indexOf("@"),E=Number(I===-1?S:S.slice(0,I));if(!Number.isInteger(E)||E<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${S}'.`);let v=null;if(I!==-1&&(v=Number(S.slice(I+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${S}'.`);return{length:E,offset:v}},w=S=>{l=S,k&&(g(k.sequenceNumber!==null),k.sequenceNumber0&&h!==null&&(s=l*h),y=!0);let E=I.slice(la.length),v=E.indexOf(","),F=v===-1?E:E.slice(0,v),O=Number(F);if(!Number.isFinite(O)||O<0)throw new Error(`Invalid #EXTINF tag duration '${F}'.`);c=O}else if(I.startsWith(bn))n.define(I.slice(bn.length));else if(I.startsWith($c)){let E=new ir(I.slice($c.length),n),v=E.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let F=E.get("byterange"),O=null;if(F!==null&&(O=T(F)),O&&O.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!k){let U={path:we(this.rootPath,v),offset:O?.offset??0,length:O?.length??null};if(u?.method==="AES-128"&&!u.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");m={timestamp:s,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:U,duration:0,encryption:u,initSegment:null,lastProgramDateTimeSeconds:b}}c=null,p===null?f=null:p=null}else if(I.startsWith(Yc)){let E=new ir(I.slice(Yc.length),n),v=E.get("method");if(v==="NONE")u=null;else if(v==="AES-128"){let F=E.get("uri");if(!F)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let O=null,D=E.get("iv");if(D){if(!Dp.test(D))throw new Error(`Unsupported IV format '${D}'.`);let K=D.slice(2);K=K.padStart(2*Ot,"0"),K=K.slice(-2*Ot),O=new Uint8Array(Ot);for(let ie=0;ie=8&&K[4]===112&&K[5]===115&&K[6]===115&&K[7]===104){let ie=N(K).getUint32(0);D=ws(K.subarray(8,Math.min(ie,K.length)))}}u={method:v,psshBox:D}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(I.startsWith(Zc)){let E=I.slice(Zc.length),v=Number(E);if(!Number.isInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${E}'.`);w(v)}else if(I.startsWith(Jc)){let E=T(I.slice(Jc.length));if(E.offset===null){if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");E.offset=f}p=E,f=E.offset+E.length}else if(I.startsWith(eu)){if(k)continue;let E=I.slice(eu.length),v=Date.parse(E);if(!Number.isFinite(v))continue;let F=v/1e3;if(b===F)continue;if(b===null&&this.segments.length>0){let O=Z(this.segments),D=O.timestamp+O.duration,U=F-D;for(let K of this.segments)K.unixEpochTimestamp=K.timestamp+U,r&&(K.timestamp=K.unixEpochTimestamp)}b=F,o=F,r&&(s=F)}else if(I===sm)d=null;else if(I.startsWith(tu)){let E=I.slice(tu.length),v=Number(E);if(!Number.isFinite(v)||v<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${E}'.`);this.refreshInterval=v,h=v}else if(I===om){this.streamHasEnded=!0;break}else I.startsWith(ru)&&I.slice(ru.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&await this.runUpdateSegments();let n=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let a=Q(this.segments,e,o=>o.timestamp);if(a===-1)return null;if(a0;for(;;){if(au.segment===r);if(n)return n.age=this.nextInputCacheAge++,n.input;let a=null;(r.initSegment||r.firstSegment)&&(a=this.getInputForSegment(r.initSegment??r.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(u=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(m=>Ss(m,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},o=new Ri({source:new da(r.location.path,async u=>{g(u.isRoot);let l={...u,isRoot:!1},d,m=r.location.offset>0||r.location.length!==null;if(!r.encryption||r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(l),m){let p=d.source.slice(r.location.offset,r.location.length??void 0).ref();d.free(),d=p}}else if(r.encryption.method==="AES-128"){let f=r.encryption;g(f.iv);let p=await this.input._getSourceCached(l);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let b=new ei(p.source),h=vd(b,async()=>{var A=[];try{let y=st(A,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},fm));let k=new ei(y.source);let T=await k.requestSlice(0,Ot);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let w=V(T,Ot);return{key:w,iv:f.iv}}catch(x){var C=x,P=!0}finally{ot(A,C,P)}},()=>{p.free()});d=new yn(h).ref()}else g(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof kn)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=u=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!u._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let u=Xi(this.inputCache,l=>l.age);g(u!==-1),this.inputCache.splice(u,1)}return o}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var no=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{g(this.input._rootSource instanceof rt);let e=await this.input._reader.requestEntireFile();g(e);let r=ro(e,e.length,{ignore:$s}),{rootPath:n}=this.input._rootSource,a=new gn(n,null),s=[],o=[];for(let d=1;d{let f=[],p=d.attributes.get("codecs"),b;if(p)b=p.split(",").map(S=>S.trim());else{let I=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(I.map(async v=>({track:v,codec:await v.getCodec()})));b=await Promise.all(E.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(F=>F.codec)))}let h=d.attributes.get("video"),y=d.attributes.get("audio"),k=b.some(S=>le.includes(Ze(S))),T=b.some(S=>fe.includes(Ze(S)));if(h!==null&&!k){let S=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===h&&v.toLowerCase()==="video"});e:if(S){let I=S.attributes.get("uri");if(I===null)break e;let E=we(n,I),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(U=>U.getType()==="video");if(!O||await O.getCodec()===null)break e;let D=await O.getDecoderConfig().then(U=>U?.codec??null);g(D!==null),b.push(D)}}if(y!==null&&!T){let S=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===y&&v.toLowerCase()==="audio"});e:if(S){let I=S.attributes.get("uri");if(I===null)break e;let E=we(n,I),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(U=>U.getType()==="audio");if(!O||await O.getCodec()===null)break e;let D=await O.getDecoderConfig().then(U=>U?.codec??null);g(D!==null),b.push(D)}}b=[...new Set(b)];let w=null,A=null,x=d.attributes.getAsNumber("bandwidth");g(x!==null);let C=d.attributes.getAsNumber("average-bandwidth"),P=d.attributes.get("name");for(let S of b){let I=Ze(S);if(I!==null){if(le.includes(I)){if(w!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");w=S;let E=d.attributes.get("video");if(E===null){let v=d.attributes.get("resolution"),F=null,O=null;if(v){let D=v.match(/^(\d+)x(\d+)$/);D&&(F=Number(D[1]),O=Number(D[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:w,pairingMask:1n<0?F:null}})}else for(let v of o){let F=v.attributes.get("group-id"),O=v.attributes.get("type");if(F!==E||O.toLowerCase()!=="audio")continue;let D=v.attributes.get("channels")??d.attributes.get("channels"),U=D!==null?Number(D.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:io(v.attributes),autoselect:io(v.attributes)||pm(v.attributes),languageCode:hm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:A,pairingMask:1n<0?U:null}})}}}}return f})),u=[],l=d=>{let m=u.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);m?(m.pairingMask|=d.pairingMask,m.default||=d.default,m.autoselect||=d.autoselect,m.lineNumber=Math.min(m.lineNumber,d.lineNumber),d.peakBitrate!==null&&(m.peakBitrate=Math.max(m.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(m.averageBitrate=Math.max(m.averageBitrate??-1/0,d.averageBitrate)),m.languageCode===se&&(m.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(let d of c)for(let m of d)l(m);u.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of u)d.info.type==="video"?this.trackBackings.push(new so(d)):this.trackBackings.push(new oo(d));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),g(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let r=this.segmentedInputs.find(a=>a.path===e);if(r)return r;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),r=new pa(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return nr}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},ao=class{constructor(t){this.internalTrack=t;this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let t=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),e=null,n=(await t.getTrackBackings()).filter(a=>a.getType()===this.getType());if(n.length===1)e=n[0];else if(this instanceof so){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{g(this instanceof oo);for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}if(!e)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=e})()}delegate(t){return this.internalTrack.backingTrack?t():this.hydrate().then(t)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{..._e,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){g(this.internalTrack.demuxer.internalTracks);let t=this.internalTrack.info.type,e=0;for(let r of this.internalTrack.demuxer.internalTracks)if(r.info.type===t&&e++,r===this.internalTrack)break;return e}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(t){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(t))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(t){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(t)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(t){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(t)}async getPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(t,e)}async getKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(t,e)}async getNextPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(t,e)}async getNextKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(t,e)}},so=class extends ao{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ze(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},oo=class extends ao{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ze(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},io=i=>{let t=i.get("default");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},pm=i=>{let t=i.get("autoselect");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},hm=i=>{if(i===null)return se;let t=i.split("-")[0];return t||se};var it=class{constructor(){this._isIsobmff=!1}},ha=class extends it{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(_(r)&&(r=await r),!r)return null;r.skip(4);let n=oe(r,4);return n!=="ftyp"&&n!=="styp"?null:oe(r,4)}_createDemuxer(e){return new Cs(e)}},co=class extends ha{async _canReadInput(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt ";let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(_(a)&&(a=await a),!a)return!1;let s=M(a),o=8;if(s===1){let u=t._reader.requestSlice(r+8,8);if(_(u)&&(u=await u),!u)return!1;s=We(u),o=16}if(s8||G(r,n)!==440786851)return!1;let s=Mc(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(_(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-je;){let u=wt(o);if(!u)break;let{id:l,size:d}=u,m=o.filePos;if(d===void 0)return!1;switch(l){case 17030:if(G(o,d)!==1)return!1;break;case 17143:if(G(o,d)!==1)return!1;break;case 17026:if(Zr(o,d)!==e)return!1;break;case 17031:if(G(o,d)>4)return!1;break}o.filePos=m+d}return!0}_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"matroska")}_createDemuxer(t){return new Bs(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},lo=class extends ga{_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},mo=class extends it{async _canReadInput(t){let e=0;for(;;){let d=t._reader.requestSlice(e,Ue);if(_(d)&&(d=await d),!d)break;let m=Je(d);if(!m)break;e=d.filePos+m.size}let r=await na(t._reader,e,e+4096);if(!r)return!1;let n=r.header,a=Gr(n.mpegVersionId,n.channel),s=t._reader.requestSlice(r.startPos+a,4);if(_(s)&&(s=await s),!s)return!1;let o=M(s);if(o===Qr||o===en)return!0;e=r.startPos+r.header.totalSize;let u=await na(t._reader,e,e+4);if(!u)return!1;let l=u.header;return!(n.channel!==l.channel||n.sampleRate!==l.sampleRate)}_createDemuxer(t){return new Ds(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},fo=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,12);if(_(e)&&(e=await e),!e)return!1;let r=oe(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(e.skip(4),oe(e,4)==="WAVE")}_createDemuxer(t){return new Ls(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},po=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,4);return _(e)&&(e=await e),e?oe(e,4)==="OggS":!1}_createDemuxer(t){return new Ns(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},ho=class extends it{async _canReadInput(t){let e=0;for(;;){let n=t._reader.requestSlice(e,Ue);if(_(n)&&(n=await n),!n)break;let a=Je(n);if(!a)break;e=n.filePos+a.size}let r=t._reader.requestSlice(e,4);return _(r)&&(r=await r),r?oe(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(t){return new Qs(t)}},go=class extends it{async _canReadInput(t){let e=0;for(;;){let s=t._reader.requestSlice(e,Ue);if(_(s)&&(s=await s),!s)break;let o=Je(s);if(!o)break;e=s.filePos+o.size}let r=t._reader.requestSliceRange(e,Er,mt);if(_(r)&&(r=await r),!r)return!1;let n=et(r);if(!n||(e+=n.frameLength,r=t._reader.requestSliceRange(e,Er,mt),_(r)&&(r=await r),!r))return!1;let a=et(r);return a?n.objectType===a.objectType&&n.samplingFrequencyIndex===a.samplingFrequencyIndex&&n.channelConfiguration===a.channelConfiguration:!1}_createDemuxer(t){return new Ws(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},bo=class extends it{async _canReadInput(t){let e=205,r=t._reader.requestSlice(0,e);if(_(r)&&(r=await r),!r)return!1;let n=V(r,e);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(t){return new js(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},kn=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,7);if(_(e)&&(e=await e),!e||!(oe(e,7)==="#EXTM3U"))return!1;if(!(t._rootSource instanceof rt))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return t._rootSource._usedForHls=!0,!0}_createDemuxer(t){return new no(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return nr}},fu=new co,pu=new uo,gm=new ga,bm=new lo,hu=new mo,ym=new fo,km=new po,gu=new go,Tm=new ho,bu=new bo,yu=new kn,Up=[yu,fu,pu,gm,bm,ym,km,Tm,hu,gu,bu],zp=[yu,fu,pu,hu,gu,bu],wm=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(`${t}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(i.hls!==void 0){if(!i.hls||typeof i.hls!="object")throw new TypeError(`${t}.hls, when provided, must be an object.`);if(i.hls.offsetTimestampsByDateTime!==void 0&&typeof i.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var yo=new Map,ko=new Map,Np=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&Ze(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(t.description!==void 0&&!fr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Lp=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&Ze(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(t.description!==void 0&&!fr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Wp=i=>le.includes(i)?ku(i):fe.includes(i)?Tu(i):!1,ku=async(i,t={})=>{if(!le.includes(i))return!1;Np(i,t);let e={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??ms(i,1280,720,1e6,!1)};e.description??=kd(e);let r=JSON.stringify(e),n=yo.get(r);if(n)return n;let a=(async()=>ti.some(o=>o.supports(i,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0)();return yo.set(r,a),a},Tu=async(i,t={})=>{if(!fe.includes(i))return!1;Lp(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??hs(i,2,48e3)};if(e.description===void 0){let s=Td(e);if(s===!1)return!1;e.description=s}let r=JSON.stringify(e),n=ko.get(r);if(n)return n;let a=(async()=>ri.some(o=>o.supports(i,e))||ae.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return ko.set(r,a),a},Hp=async()=>{let[i,t]=await Promise.all([Sm(),Am()]);return[...i,...t]},Sm=async(i=le,t)=>{let e=await Promise.all(i.map(r=>ku(r,t)));return i.filter((r,n)=>e[n])},Am=async(i=fe,t)=>{let e=await Promise.all(i.map(r=>Tu(r,t)));return i.filter((r,n)=>e[n])};ji();var xm=-1/0,Cm=-1/0,Ta=null;typeof FinalizationRegistry<"u"&&(Ta=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-xm>=1e3&&(z._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),xm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-Cm>=1e3&&(z._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Cm=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var ar=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},wo=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],qp=new Set(wo),Xe=class i{constructor(t,e){this._closed=!1;if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!qp.has(e.format))throw new TypeError("init.format must be one of: "+wo.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let a of e.layout){if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(a.offset)||a.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(a.stride)||a.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=e.format,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0;let r=e.layout??Gp(e.format,e.codedWidth,e.codedHeight),n=e.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:e.visibleRect?.left??0,top:e.visibleRect?.top??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180===0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=e._doNotCopy?$(t):$(t).slice(),this._layout=r,this.colorSpace=new Tn(n)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if(e?.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e?.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(e?.timestamp!==void 0&&!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");e?.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=e?.rotation??0,this.flip=e?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=e?.timestamp??t.timestamp/1e6,this.duration=e?.duration??(t.duration??0)/1e6,this.colorSpace=new Tn(t.colorSpace)}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Kt),duration:Math.trunc((e.duration??0)*Kt)||void 0,visibleRect:e.visibleRect&&{x:e.visibleRect.left,y:e.visibleRect.top,width:e.visibleRect.width,height:e.visibleRect.height}}),e);let r=0,n=0;if("naturalWidth"in t?(r=t.naturalWidth,n=t.naturalHeight):"videoWidth"in t?(r=t.videoWidth,n=t.videoHeight):"width"in t&&(r=Number(t.width),n=Number(t.height)),!r||!n)throw new TypeError("Could not determine dimensions.");let a=e.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(a.width,a.height),o=s.getContext("2d",{alpha:yi(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(t,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new Tn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof ar){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!wo.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=Gt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ta?.register(this,{type:"video",data:this._data},this)}get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Kt*this.timestamp)}get microsecondDuration(){return Math.trunc(Kt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof ar?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):ya(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(g(this._layout),new i(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Ta?.unregister(this),this._data instanceof ar?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ya(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Em(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ya(this._data)?this._data.allocationSize(t):vm(this,t).allocationSize}async copyTo(t,e={}){if(!fr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Em(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),ya(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format))if(this._data instanceof ar){var u=[];try{let f=st(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},e.colorSpace??"srgb"));if(!(f instanceof i))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(f.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${f.format}' instead.`);return await f.copyTo(t,e)}catch(l){var d=l,m=!0}finally{ot(u,d,m)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let f=this.toVideoFrame(),p=await f.copyTo(t,e);return f.close(),p}let r=vm(this,e);g(this.format);let n=$(t);if(n.byteLength!(p.data instanceof Uint8Array)||!Number.isInteger(p.stride)||p.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=f}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===a.length),s=this._layout.map((f,p)=>{let b=Math.ceil(this.codedHeight/a[p].heightDivisor);return{data:this._data.subarray(f.offset,f.offset+f.stride*b),stride:f.stride}});else{let p=this._data.getContext("2d");g(p);let b=p.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:$(b.data),stride:4*this.codedWidth}]}let o=[],c=a.length;for(let f=0;fh.byteLength)throw new Error("Source buffer OOB read.");if(k+T>n.byteLength)throw new Error("Destination buffer OOB write.");let x=h.subarray(y,y+T);n.set(x,k),y+=b,k+=p.destinationStride}o.push(w)}if(e.format!==void 0){let f=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),p=this.format.includes("X")&&e.format.includes("A");if(f||p)for(let b=0;bs+o.data.byteLength,0),r=new Uint8Array(e),n=0,a=[];for(let s of t)r.set(s.data,n),a.push(n),n+=s.data.byteLength;return new VideoFrame(r,{format:this.format,layout:t.map((s,o)=>({offset:a[o],stride:s.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ya(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(g(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,u){let l=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,b=0,h=this.displayWidth,y=this.displayHeight;if(s!==void 0?(l=e,d=r,m=n,f=a,p=s,b=o,c!==void 0?(h=c,y=u):(h=m,y=f)):(p=e,b=r,n!==void 0&&(h=n,y=a)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(l,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let T=p+h/2,w=b+y/2;t.translate(T,w),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let A=this.rotation%180===0?1:h/y;t.scale(1/A,A),t.drawImage(k,l,d,m,f,-h/2,-y/2,h,y),t.restore()}drawWithFit(t,e){if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");e.crop!==void 0&&ni(e.crop,"options.");let r=t.canvas.width,n=t.canvas.height,a=e.rotation??this.rotation,s=e.flip??this.flip,[o,c]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],u=e.crop;u&&(u=wn(u,o,c));let l,d,m,f,{sx:p,sy:b,sWidth:h,sHeight:y}=this._unmapSourceRegion(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??c,a,s);if(e.fit==="fill")l=0,d=0,m=r,f=n;else{let[T,w]=e.crop?[e.crop.width,e.crop.height]:[o,c],A=e.fit==="contain"?Math.min(r/T,n/w):Math.max(r/T,n/w);m=T*A,f=w*A,l=(r-m)/2,d=(n-f)/2}t.save();let k=a%180===0?1:m/f;t.translate(r/2,n/2),s&&t.scale(-1,1),t.rotate(a*Math.PI/180),t.scale(1/k,k),t.translate(-r/2,-n/2),t.drawImage(this.toCanvasImageSource(),p,b,h,y,l,d,m,f),t.restore()}_unmapSourceRegion(t,e,r,n,a,s){return s&&(t=(a%180===0?this.squarePixelWidth:this.squarePixelHeight)-t-r),a===90?[t,e,r,n]=[e,this.squarePixelHeight-t-r,n,r]:a===180?[t,e]=[this.squarePixelWidth-t-r,this.squarePixelHeight-e-n]:a===270&&([t,e,r,n]=[this.squarePixelWidth-e-n,t,n,r]),{sx:t,sy:e,sWidth:r,sHeight:n}}_drawWithFitAndMipmapping(t,e,r){let n=t.width,a=t.height,[s,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:s,u=r.crop?r.crop.height:o,l=0;2*n0?Im(d,m):{canvas:t,context:e,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,m)):b||p.clearRect(0,0,d,m),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),p.globalCompositeOperation="copy";for(let h=l;h>1;h--){let y=n*2**h,k=a*2**h;p.drawImage(f,0,0,y,k,0,0,y/2,k/2)}p.globalCompositeOperation="source-over",l>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(f,0,0,2*n,2*a,0,0,n,a),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof ar||this._data instanceof Uint8Array){let t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}else return this._data}async transform(t){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 provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, 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.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&ni(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let{rotation:e,flip:r}=Ua(this.rotation,this.flip,t.rotate??0,t.flip??!1),[n,a]=e%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&(s=wn(s,n,a));let o=s?s.width:n,c=s?s.height:a,u=o/c,l,d;t.width!==void 0&&t.height===void 0?(l=t.width,d=l/u):t.width===void 0&&t.height!==void 0?(d=t.height,l=d*u):t.width!==void 0&&t.height!==void 0?(l=t.width,d=t.height):(l=o,d=c),l=La(l,t.roundDimensionsTo??1),d=La(d,t.roundDimensionsTo??1);let m={width:l,height:d,fit:t.fit??"fill",rotation:e,flip:r,crop:s??{left:0,top:0,width:n,height:a},alpha:t.alpha??"keep"};for(let h of wu){let y=h(this,m);if(_(y)&&(y=await y),y!==null)return y}let{canvas:f,context:p,isNew:b}=Im(m.width,m.height);return this._drawWithFitAndMipmapping(f,p,{fit:m.fit,rotation:m.rotation,flip:m.flip,crop:m.crop,targetIsFresh:b,fillBlack:m.alpha==="discard"}),new i(f,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setFlip(t){if(typeof t!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||typeof t!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},wu=[],Kp=i=>{wu.includes(i)||wu.push(i)},Qp=3,ba=[],Pm=0,Im=(i,t)=>{for(let n of ba)if(n.canvas.width===i&&n.canvas.height===t)return n.age=Pm++,{canvas:n.canvas,context:n.context,isNew:!1};let e;if(typeof OffscreenCanvas<"u")e=new OffscreenCanvas(i,t);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");e=document.createElement("canvas"),e.width=i,e.height=t}let r=e.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return ba.length>=Qp&&ba.splice(Xi(ba,n=>n.age),1),ba.push({canvas:e,context:r,age:Pm++}),{canvas:e,context:r,isNew:!0}},Tn=class{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let e=Object.keys(Pt);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);let r=Object.keys(It);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(Et);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},ya=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,wn=(i,t,e)=>{let r=Math.min(i.left,t),n=Math.min(i.top,e),a=Math.min(i.width,t-r),s=Math.min(i.height,e-n);return g(a>=0),g(s>=0),{left:r,top:n,width:a,height:s}},ni=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Em=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let t of i.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Gp=(i,t,e)=>{let r=So(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),u=o*s.sampleBytes,l=u*c;n.push({offset:a,stride:u}),a+=l}return n},So=i=>{let t=(e,r,n,a,s)=>{let o=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:n,heightDivisor:a},{sampleBytes:r,widthDivisor:n,heightDivisor:a}];return s&&o.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),o};switch(i){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ne(i),g(!1)}},vm=(i,t)=>{let e={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=t.rect,n=jp(e,r,i.codedWidth,i.codedHeight,i.format),a=t.layout,s;if(!t.format||t.format===i.format)s=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(t.format))s=t.format;else throw new Error("NotSupportedError: Invalid destination format.");return $p(n,s,a)},jp=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(t.width===0||t.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Xp(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Xp=(i,t)=>{if(i===null)return!0;let e=So(i);for(let r=0;r{let r=So(t),n=r.length;if(e!==void 0&&e.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let a=0,s=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(b),a=Math.max(a,b);for(let h=0;h 0.");if(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp must be a number.");let e=t.data.byteLength/(sr(t.format)*t.numberOfChannels);if(!Number.isInteger(e))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=e,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp,this.duration=e/t.sampleRate;let r;if(t.data instanceof ArrayBuffer)r=new Uint8Array(t.data);else if(ArrayBuffer.isView(t.data))r=new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*sr(this.format);if(r.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=t.frameCount!==void 0?t.frameCount:this.numberOfFrames-r;if(n>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let a=sr(e),s=Fi(e);if(s&&t.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&t.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?n:n*this.numberOfChannels)*a}copyTo(t,e){if(!fr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");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&&!To.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{format:r,frameCount:n,frameOffset:a}=e,{planeIndex:s}=e,o=this.format,c=r??this.format;if(!c)throw new Error("Destination format not determined");let u=this.numberOfFrames,l=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:u-d;if(m>u-d)throw new RangeError("frameCount out of range");let f=sr(c),p=Fi(c);if(p&&s>=l)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let h=(p?m:m*l)*f;if(t.byteLength2&&c!==o){Yp(this._data,y,o,c,l,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(P){if(c==="f32-planar")throw P;o="f32-planar"}let T=_m(o),w=sr(o),A=Fi(o),x;if(this._data instanceof ii){let P=S=>{let I=this._data.getDataPlane(S);if(!(I instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=u*w*(A?1:l);if(I.byteLength!==E)throw new TypeError(`Data plane ${S} has invalid size. Expected exactly ${E} bytes, got ${I.byteLength} bytes.`);return I};if(A)if(p)x=P(s),s=0;else{x=new Uint8Array(u*w*l);for(let S=0;Sthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(e>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(e0)for(let o=0;o0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new i({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate})}close(){this._closed||(Ta?.unregister(this),this._data instanceof ii?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ka(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof ii?this._createAudioDataFromData():ka(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Fi(this.format)){let t=this.allocationSize({planeIndex:0,format:this.format}),e=new ArrayBuffer(t*this.numberOfChannels);for(let r=0;r0;){let l=Math.min(o,u),d=new Float32Array(n*l);for(let m=0;m0;){let d=Math.min(o,u),m=new Float32Array(n*d);for(let p=0;p{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")}},Fi=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_m=i=>{switch(i){case"u8":case"u8-planar":return(t,e)=>(t.getUint8(e)-128)/128;case"s16":case"s16-planar":return(t,e)=>t.getInt16(e,!0)/32768;case"s32":case"s32-planar":return(t,e)=>t.getInt32(e,!0)/2147483648;case"f32":case"f32-planar":return(t,e)=>t.getFloat32(e,!0)}},Rm=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,ee(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,ee(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,ee(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},ka=i=>typeof AudioData<"u"&&i instanceof AudioData,Fm=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},Yp=(i,t,e,r,n,a,s,o)=>{let c=_m(e),u=Rm(r),l=sr(e),d=sr(r),m=Fi(e);if(Fi(r))if(m){let p=new ArrayBuffer(o*l),b=N(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let h=0;h{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ce({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration})};var Ao=new Map,xo=new Map,Co=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!le.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${le.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0)throw new TypeError("config.quality must be provided.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");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.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.flip!==void 0&&typeof i.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(i.transform.crop!==void 0&&ni(i.transform.crop,"config.transform."),i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, 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.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Dm(i.codec,i)},Dm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&Ze(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Au=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??ms(i.codec,i.width,i.height,o,i.alpha==="keep"),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:a,bitrateMode:s,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...Sd(i.codec)}),n=[];return e.quantizer!==null&&n.push({config:r(void 0,"quantizer",e.bitrate),quantizer:e.quantizer}),e.bitrateMode!=="quantizer"&&n.push({config:r(e.bitrate,e.bitrateMode,e.bitrate),quantizer:null}),g(n.length>0),n},Po=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!fe.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${fe.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(ae.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, 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.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Vm(i.codec,i)},Vm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&Ze(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},xu=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??hs(i.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec),bitrateMode:i.quality?._bitrateMode??t,...Ad(i.codec)}},ce=class{constructor(t){if((typeof t=="number"||typeof t=="string")&&(t={quality:t}),!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if(typeof t.quality=="string"?!(t.quality in Bm):typeof t.quality!="number"||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(t.preferBitrate!==void 0&&typeof t.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof t.quality=="string"?Bm[t.quality]:t.quality,this._preferBitrate=t.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(t.bitrate!==void 0&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(t.quantizer!==void 0&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(t.bitrate===void 0&&t.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=t.bitrate,this._quantizer=t.quantizer}this._bitrateMode=t.bitrateMode}_toVideoRateControl(t,e,r,n){let a=Zp[t],s=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(a)if(this._quantizera.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${t}'; must be between ${a.min} and ${a.max}.`)}else s=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(g(this._quality!==void 0),s=ee(Math.round(Ol(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(g(s!==null&&a),u=ee((s-a.worst)/(a.best-a.worst),0,1)),c=Om(t,e,r,Su(u))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(g(this._quality!==void 0),Om(t,e,r,Su(this._quality)))}_toAudioBitrate(t){if(ae.includes(t)||t==="flac")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");let e=Su(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!n)throw new Error(`Unhandled codec: ${t}`);let a=n*e;return t==="aac"?a=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-a)Math.abs(c-a).3*Math.exp(2.5538*i),Om=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*u[i]*r;return Math.ceil(d/1e3)*1e3},Cu=(i,t)=>{if(i==="avc")return{avc:{quantizer:t}};if(i==="hevc")return{hevc:{quantizer:t}};if(i==="vp9")return{vp9:{quantizer:t}};if(i==="av1")return{av1:{quantizer:t}};g(!1)},Jp=new ce("very-low"),eh=new ce("low"),th=new ce("medium"),rh=new ce("high"),ih=new ce("very-high"),nh=i=>{if(le.includes(i))return Io(i);if(fe.includes(i))return Eo(i);if(Ye.includes(i))return vo(i);throw new TypeError(`Unknown codec '${i}'.`)},Io=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!le.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof ce))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ce)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Dm(i,o);let c=ai(n,a)??new ce("medium"),u;try{u=Au({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let l=JSON.stringify(u),d=Ao.get(l);if(d)return d;let m=(async()=>{for(let{config:p}of u)if(Sn.some(b=>b.supports(i,p)))return!0;if(typeof VideoEncoder>"u"||(e%2===1||r%2===1)&&(i==="avc"||i==="hevc"))return!1;for(let{config:p,quantizer:b}of u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!yi()||await new Promise(async y=>{try{let k=new VideoEncoder({output:()=>{},error:()=>y(!1)});k.configure(p);let T=new Uint8Array(e*r*4),w=new VideoFrame(T,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(w,b!==null?Cu(i,b):void 0),w.close(),await k.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return Ao.set(l,m),m},Eo=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!fe.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof ce))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ce)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Vm(i,s);let o=ai(n,a)??new ce("medium"),c=xu({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),u=JSON.stringify(c),l=xo.get(u);if(l)return l;let d=(async()=>{if(An.some(m=>m.supports(i,c))||ae.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return xo.set(u,d),d},ai=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof ce?t:new ce({bitrate:t})},vo=async i=>!!Ye.includes(i),ah=async()=>{let[i,t,e]=await Promise.all([Um(),wa(),zm()]);return[...i,...t,...e]},Um=async(i=le,t)=>{let e=await Promise.all(i.map(r=>Io(r,t)));return i.filter((r,n)=>e[n])},wa=async(i=fe,t)=>{let e=await Promise.all(i.map(r=>Eo(r,t)));return i.filter((r,n)=>e[n])},zm=async(i=Ye)=>{let t=await Promise.all(i.map(vo));return i.filter((e,r)=>t[r])},Pu=async(i,t)=>{for(let e of i)if(await Io(e,t))return e;return null},sh=async(i,t)=>{for(let e of i)if(await Eo(e,t))return e;return null},oh=async i=>{for(let t of i)if(await vo(t))return t;return null};var _o=class{static supports(t,e){return!1}},Ro=class{static supports(t,e){return!1}},Fo=class{static supports(t,e){return!1}},Mo=class{static supports(t,e){return!1}},ti=[],ri=[],Sn=[],An=[],ch=i=>{if(i.prototype instanceof _o){let t=i;if(ti.includes(t)){z._warn("Video decoder already registered.");return}ti.push(t),yo.clear()}else if(i.prototype instanceof Ro){let t=i;if(ri.includes(t)){z._warn("Audio decoder already registered.");return}ri.push(t),ko.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},uh=i=>{if(i.prototype instanceof Fo){let t=i;if(Sn.includes(t)){z._warn("Video encoder already registered.");return}Sn.push(t),Ao.clear()}else if(i.prototype instanceof Mo){let t=i;if(An.includes(t)){z._warn("Audio encoder already registered.");return}An.push(t),xo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var Nm=i=>{let r=i>>2,n=4096,a=0,s=12,o=0;for(r<0&&(r=-r,a=128),r+=33,r>8191&&(r=8191);(r&n)!==n&&s>=5;)n>>=1,s--;return o=r>>s-4&15,~(a|s-5<<4|o)&255},Lm=i=>{let e=0,r=0,n=~i;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+5;let a=(1<{let e=2048,r=0,n=11,a=0,s=i>>3;for(s<0?s=-s-1:r=128,s>4095&&(s=4095);(s&e)!==e&&n>=5;)e>>=1,n--;return a=s>>(n===4?1:n-4)&15,(r|n-4<<4|a)^85},Hm=i=>{let t=0,e=0,r=i^85;r&128&&(r&=-129,t=-1),e=((r&240)>>4)+4;let n=0;return e!==4?n=1<{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.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},vr=i=>{if(!ve(i))throw new TypeError("timestamp must be a number.")},Iu=(i,t,e)=>e.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;let n=await i.determinePacketType(r);return n&&(r.type=n),r}):t,ft=class{constructor(t){if(!(t instanceof Oi))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Mi(t),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Mi(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(vr(t),Mi(e),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Mi(e),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(vr(t),Mi(e),this._track.input._disposed)throw new ke;if(!e.verifyKeyPackets)return this._track._backing.getKeyPacket(t,e);let r=await this._track._backing.getKeyPacket(t,e);return r&&(g(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),e):r)}async getNextKeyPacket(t,e={}){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Mi(e),this._track.input._disposed)throw new ke;if(!e.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,e);let r=await this._track._backing.getNextKeyPacket(t,e);return r&&(g(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,e):r)}packets(t,e,r={}){if(t!==void 0&&!(t instanceof X))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(e!==void 0&&!(e instanceof X))throw new TypeError("endPacket must be an EncodedPacket.");if(Mi(r),this._track.input._disposed)throw new ke;let n=[],{promise:a,resolve:s}=J(),{promise:o,resolve:c}=J(),u=!1,l=!1,d=null,m=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let h=t??await this.getFirstPacket(r);for(;h&&!l&&!this._track.input._disposed&&!(e&&h.sequenceNumber>=e?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=J()),await o;continue}n.push(h),s(),{promise:a,resolve:s}=J(),h=await this.getNextPacket(h,r)}u=!0,s()})().catch(h=>{m||(d=h,m=!0,s())});let b=this._track;return{async next(){for(;;){if(b.input._disposed)throw new ke;if(l)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let h=n.shift(),y=performance.now();for(f.push(y);f.length>0&&y-f[0]>=1e3;)f.shift();return c(),{value:h,done:!1}}else{if(u)return{value:void 0,done:!0};await a}}},async return(){return l=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},Sa=class{constructor(t,e){this.onSample=t;this.onError=e}},Aa=class{mediaSamplesInRange(t=-1/0,e=1/0,r){vr(t),vr(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=J(),{promise:u,resolve:l}=J(),d=!1,m=!1,f=!1,p=null,b=null,h=!1,y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(S=>{if(l(),S.timestamp>=e&&(m=!0),m){S.close();return}s&&(S.timestamp>t?(n.push(s),a=!0):s.close()),S.timestamp>=t&&(n.push(S),a=!0),s=a?null:S,n.length>0&&(c(),{promise:o,resolve:c}=J())},S=>{h||(b=S,h=!0,c())});let w=this._createPacketSink(),A=await w.getKeyPacket(t,y)??await w.getFirstKeyPacket(y),x=A,P=w.packets(A??void 0,void 0,y);for(await P.next();x&&!m&&!this._track.input._disposed;){let S=qm(n.length);if(n.length+p.getDecodeQueueSize()>S){({promise:u,resolve:l}=J()),await u;continue}p.decode(x);let I=await P.next();if(I.done)break;x=I.value}await P.return(),!f&&!this._track.input._disposed&&await p.flush(),!a&&s&&n.push(s),d=!0,c()})().catch(w=>{h||(b=w,h=!0,c())}).finally(()=>{p?.close()});let k=this._track,T=()=>{s?.close();for(let w of n)w.close()};return{async next(){for(;;){if(k.input._disposed)throw f=!0,m=!0,T(),new ke;if(f)return{value:void 0,done:!0};if(h)throw f=!0,m=!0,T(),b;if(n.length>0){let w=n.shift();return l(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,m=!0,l(),c(),T(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){Rl(t);let r=_l(t),n=[],a=[],{promise:s,resolve:o}=J(),{promise:c,resolve:u}=J(),l=!1,d=!1,m=null,f=null,p=!1,b=T=>{a.push(T),o(),{promise:s,resolve:o}=J()},h={...e,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(S=>{if(u(),d){S.close();return}let I=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let E=0;E{p||(f=S,p=!0,o())});let T=this._createPacketSink(),w=null,A=null,x=-1,C=async()=>{g(A),g(m);let S=A;for(m.decode(S);S.sequenceNumberI&&!d;)({promise:c,resolve:u}=J()),await c;if(d)break;let E=await T.getNextPacket(S,h);g(E),m.decode(E),S=E}x=-1},P=async()=>{g(m),await m.flush();for(let S=0;S{p||(f=T,p=!0,o())}).finally(()=>{m?.close()});let y=this._track,k=()=>{for(let T of a)T?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,k(),new ke;if(d)return{value:void 0,done:!0};if(p)throw d=!0,k(),f;if(a.length>0){let T=a.shift();return g(T!==void 0),u(),{value:T,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),k(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}},qm=i=>i===0?40:8,vu=class extends Sa{constructor(e,r,n,a,s,o,c){super(e,r);this.codec=n;this.decoderConfig=a;this.rotation=s;this.flip=o;this.timeResolution=c;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Or;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];let u=ti.find(l=>l.supports(n,a));if(u)this.customDecoder=new u,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Xe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=m=>{if(this.alphaQueue.length>0){let f=this.alphaQueue.shift();g(f!==void 0),this.mergeAlpha(m,f)}else this.colorQueue.push(m)};if(Nn()){if(n==="avc"&&this.decoderConfig.description){let m=Wr($(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=Jt(m.sequenceParameterSets[0]);f&&(f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),f.maxDecFrameBuffering!==0&&f.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[0]=Cc(f),this.decoderConfig={...this.decoderConfig,description:es(m)}))}}Ki(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let d=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:m=>{try{l(m)}catch(f){this.onError(f)}},error:m=>{m.stack=d,this.onError(m)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>this.customDecoderQueueSize--);else{if(g(this.decoder),Qt()||mc(this.inputTimestamps,e.timestamp,r=>r),Nn()&&this.currentPacketIndex===0){if(this.codec==="avc"){let r=[],n=!1;for(let s of xc(e.data,this.decoderConfig)){let o=Yt(e.data[s.offset]);if(n||=o>=1&&o<=5,o===9){if(n)break;r.length=0}o>=20&&o<=31||r.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s{if(this.colorQueue.length>0){let o=this.colorQueue.shift();g(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();g(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},a=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(o){this.onError(o)}},error:s=>{s.stack=a,this.onError(s)}}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}let r=qr(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of Wn(e,this.decoderConfig)){let n=_t(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(Qt()){if(this.sampleQueue.length>0&&e.timestamp>=Z(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}mc(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();g(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,r){let n=J();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new Xe(e);else{g(this.merger);let s=await this.merger.merge(e,r);a.sample=new Xe(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Qi(this.finalSamples,a),this.onError(s)}finally{Qi(this.mergeAlphaPromises,n.promise),n.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Qt()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Eu=null,_u=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){if(!Eu){let o=new Blob([`(${lh.toString()})()`],{type:"application/javascript"});Eu=URL.createObjectURL(o)}let s=ee(navigator.hardwareConcurrency,1,4);for(let o=0;o{let l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{let l=new Error(u.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=J();this.pendingRequests.set(r,n);let a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:r,color:t,alpha:e},{transfer:[t,e]}),n.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let t=new Error("Color/alpha merger closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},lh=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:u,color:l,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(l,d);self.postMessage({id:u,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:u,error:m.message})}finally{l.close(),d.close()}})});let r=async(c,u)=>{let l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=l.includes("P10"),f=l.includes("P12"),p=d.includes("P10"),b=d.includes("P12");if(p!==m||b!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await n(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await a(c,u,l);if(l==="NV12")return await s(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},n=async(c,u,l)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=d*m,p=new Uint8Array(f*4);await c.copyTo(p);let b=await o(u,d,m,1);for(let k=0,T=3;k{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=l.includes("P10"),p=l.includes("P12"),b=f||p?2:1,h,y;l.startsWith("I420")?(h=Math.ceil(d/2),y=Math.ceil(m/2)):l.startsWith("I422")?(h=Math.ceil(d/2),y=m):(h=d,y=m);let k=d*m,T=h*y,w=k*b,A=T*b,x=k*b,C=w+2*A+x,P=new Uint8Array(C);await c.copyTo(P);let S=await o(u,d,m,b),I=w+2*A;P.set(S,I);let v={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[P.buffer]};return new VideoFrame(P,v)},s=async(c,u)=>{let l=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=l*d,f=Math.ceil(l/2),p=Math.ceil(d/2),b=f*p,h=c.allocationSize();(!t||t.byteLength!==h)&&(t=new Uint8Array(h)),await c.copyTo(t);let y=new Uint8Array(m+2*b+m);y.set(t.subarray(0,m),0);let k=m,T=m+b,w=m;for(let C=0;C{let m=c.allocationSize();(!i||i.byteLength!==m)&&(i=new Uint8Array(m)),await c.copyTo(i);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,b=u*l;for(let h=0;h{if(!i||typeof i!="object")throw new TypeError("decoderOptions must be an object.");if(i.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i.optimizeForLatency!==void 0&&typeof i.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},Bi=class extends Aa{constructor(t,e={}){if(!(t instanceof _r))throw new TypeError("videoTrack must be an InputVideoTrack.");Km(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Gi("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getRotation(),a=await this._track.getFlip(),s=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return g(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new vu(t,e,r,s,n,a,o)}_createPacketSink(){return new ft(this._track)}async getSample(t,e={}){vr(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},Ru=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof _r))throw new TypeError("videoTrack must be an InputVideoTrack.");if(e&&typeof e!="object")throw new TypeError("options must be an object.");if(e.alpha!==void 0&&typeof e.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&ni(e.crop,"options."),e.poolSize!==void 0&&(typeof e.poolSize!="number"||!Number.isInteger(e.poolSize)||e.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");e.decoderOptions!==void 0&&Km(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new Bi(t,e.decoderOptions),this._canvasPool=Array.from({length:e.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let t=this._options,e=this._videoTrack,r=t.rotation??await e.getRotation(),n=t.flip??await e.getFlip(),a=await e.getSquarePixelWidth(),s=await e.getSquarePixelHeight(),[o,c]=r%180===0?[a,s]:[s,a],u=t.crop;u&&(u=wn(u,o,c));let[l,d]=u?[u.width,u.height]:[o,c],m=l/d;t.width!==void 0&&t.height===void 0?(l=t.width,d=Math.round(l/m)):t.width===void 0&&t.height!==void 0?(d=t.height,l=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(l=t.width,d=t.height),this._width=l,this._height=d,this._rotation=r,this._flip=n,this._crop=u})()}_videoSampleToWrappedCanvas(t){let e=this._width,r=this._height,n=this._canvasPool[this._nextCanvasIndex],a=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=e,n.height=r):n=new OffscreenCanvas(e,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=n.getContext("2d",{alpha:this._alpha||yi()});g(s),t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&yi()});let o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,e){vr(t),await this._ensureInit();let r=await this._videoSampleSink.getSample(t,e);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,e,r){await this._ensureInit(),yield*zn(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*zn(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},Fu=class extends Sa{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Or;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;let s=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=u);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let d=a.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ri.find(c=>c.supports(n,a));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=c=>{if(!(c instanceof Ce))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoder.onError=c=>{r(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>r(c));else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{s(new Ce(u))}catch(l){this.onError(l)}},error:u=>{u.stack=c,this.onError(u)}}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},Mu=class extends Sa{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;g(ae.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Re(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:a==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):a==="ulaw"?this.readInputValue=(c,u)=>Lm(c.getUint8(u)):a==="alaw"?this.readInputValue=(c,u)=>Hm(c.getUint8(u)):g(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:a==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):g(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,u)=>gi(c,u,o)-2**23:a==="signed"?this.readInputValue=(c,u)=>Fl(c,u,o):g(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:a==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):a==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):g(!1);break;case 8:a==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):g(!1);break;default:ne(s),g(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,l)=>c.setUint8(u,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0);break;default:ne(s),g(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=N(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let d=0;d=c)&&(this.currentTimestamp=e.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let l=new Ce({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:u});this.onSample(l)}async flush(){}close(){}},xn=class extends Aa{constructor(t){if(!(t instanceof Rr))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=t}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(Gi("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getDecoderConfig();return g(r&&n),ae.includes(n.codec)?new Mu(t,e,n):new Fu(t,e,r,n)}_createPacketSink(){return new ft(this._track)}async getSample(t,e={}){vr(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},Bu=class{constructor(t){if(!(t instanceof Rr))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new xn(t)}_audioSampleToWrappedArrayBuffer(t){let e={buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration};return t.close(),e}async getBuffer(t,e){vr(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return zn(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return zn(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var Oi=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof _r}isAudioTrack(){return this instanceof Rr}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ge(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ge(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ge(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ge(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(t){return this._backing.getUnixTimeForTimestamp(t)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return ge(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t}),r=(e?.timestamp??0)+(e?.duration??0);return qt(r,await this.getTimeResolution())}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new ft(this),n=1/0,a=-1/0,s=0,o=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&c.timestamp>=a)break;n=Math.min(n,c.timestamp),a=Math.max(a,c.timestamp+c.duration),s++,o+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-n)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(a-n)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an InputTrack.");return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(t){return this.input.getTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(si({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(si({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=Ou(t);let e=await this.input.getTracks();for(let r of e)if(this.canBePairedWith(r)&&(!t||await t(r)))return!0;return!1}hasPairableVideoTrack(t){return t&&=Ou(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=Ou(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},ge=(i,t,e)=>{if(_(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},Ou=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},r=i(t);return _(r)?r.then(e):e(r)}:void 0},_r=class extends Oi{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ge(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return ge(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ge(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return fi(await this._backing.getTransformationMatrix())}get rotation(){return fi(ge(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return uc(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ge(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ge(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Gt({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Gt({num:ge(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ge(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ge(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ge(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let a=ge(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=fi(ge(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ge(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let a=ge(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=fi(ge(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ge(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=await this._backing.getCodec();return g(r!==null),ti.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return z._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let r=await this.getCodec();if(r===null)return null;let n=await this.getDecoderConfig();return g(n),qr(r,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!ve(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");let r=await this.getTimeResolution(),n=e.targetPacketCount??256,a=new ft(this),s=[],o=-1/0,c=0;for await(let E of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&E.timestamp>=o)break;s.push(E.timestamp),o=Math.max(o,E.timestamp),c++}let u=new Float64Array(s.length);for(let E=0;EE-v),A=T-1>>1,x=T>>1,C=0,P=0,S=0;for(let E of w)if(S+=b.get(E),C===0&&S>A&&(C=E),S>x){P=E;break}let I=(f/C+f/P)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:fh(I),minFrameRate:f/y,maxFrameRate:f/h,averageFrameRate:f*T/k,medianFrameRate:I,frameRateIsConstant:m!==null&&h===1&&y===1,probedPacketCount:c}}},Rr=class extends Oi{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ge(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ge(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ge(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let t=await this._backing.getMetadataCodecParameterString?.();return t??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return g(e!==null),ri.some(r=>r.supports(e,t))||ae.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return z._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}},dh=i=>i??1/0,Bo=i=>-(i??-1/0),Di=i=>-i,Cn=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},r=i.filter(t);return _(r)?r.then(e):e(r)}:void 0,sortBy:i.sortBy?t=>{let e=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(a=>typeof a=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},r=i.sortBy(t);return _(r)?r.then(e):e(r)}:void 0}},si=(i,t)=>({filter:i?.filter||t?.filter?e=>{let r=i?.filter?.(e)??!0,n=a=>a===!1?!1:t?.filter?.(e)??!0;return _(r)?r.then(n):n(r)}:void 0,sortBy:i?.sortBy||t?.sortBy?e=>{let r=i?.sortBy?.(e)??[],n=t?.sortBy?.(e)??[],a=(s,o)=>[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]];return _(r)||_(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),Oo=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>_(c))){let c=await Promise.all(s);e=i.filter((u,l)=>c[l])}else e=i.filter((c,u)=>s[u])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>_(s))?await Promise.all(r):r;return e.map((s,o)=>({track:s,sortValue:a[o]})).sort((s,o)=>{let c=Array.isArray(s.sortValue)?s.sortValue:[s.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;ds.track)},mh=(i,t)=>{let n=1.000000001,a=1e3,s=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(i.length<2)return null;let o=new Float64Array(i.length-1);for(let C=1;C0))return null;o[C-1]=P}let c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let C=0;C<6;C++){let P=0,S=0;for(let E of o){let v=Math.max(1,Math.round(E/u));Math.abs(E-v*u)>=n||(P+=E,S+=v)}if(S===0)return null;let I=P/S;if(Math.abs(I-u)<=1e-12*Math.max(1,u)){u=I;break}u=I}let l=0,d=0,m=0;for(let C of o){let P=Math.max(1,Math.round(C/u));Math.abs(C-P*u)>=n||(l++,d+=C,m+=P)}if(l/o.length<.98)return null;u=d/m;let f=1/Math.min(m,a),p=Math.max(Number.EPSILON,u-f),b=u+f,h=t/b,y=t/p,k=t/u,T=null,w=1/0;for(let C of s){if(Cy)continue;let P=Math.abs(C/k-1);P{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r{let t=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],e=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,n=.025;for(let o of t)if(Math.abs(o/i-1)<=r)return o;let a=i,s=1/0;for(let o of e){let c=Math.abs(o/i-1);c<=n&&c!(r instanceof it)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof qe||e.source instanceof _i))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof qe&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof i))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&wm(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof qe?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){g(this._rootSource instanceof rt);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=ph){let n=this._sourceCache.find(o=>o.cacheGroup===r&&du(o.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&du(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o=await this._getSourceUncached(e);if(wi(this._sourceCache,m=>m.cacheGroup===r&&m.sourceRef.source._refCount===1)>=4){let m=Xi(this._sourceCache,p=>p.cacheGroup===r&&p.sourceRef.source._refCount===1?p.age:1/0);g(m!==-1);let f=this._sourceCache[m];this._sourceCache.splice(m,1),f.sourceRef.free(),Qi(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(o);let l=this._sourceCachePromises.findIndex(m=>m.request===e);return g(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:o,age:this._nextSourceCacheAge++,cacheGroup:r}})();return this._sourceCachePromises.push({request:e,cacheGroup:r,promise:s}),s.then(o=>{let c=o.sourceRef.source.ref();return this._sourceCache.push(o),c})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new ei(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new xa})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),g(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof xa)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let r=e.filter(s=>s!==null);if(r.length===0)return 0;let n=await Promise.all(r.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),a=Math.min(...n.map(s=>s?.timestamp??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(s=>s.computeDuration(r)));return Math.max(...a)}async getDurationFromMetadata(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null),s=(await Promise.all(n.map(o=>o.getDurationFromMetadata(r)))).filter(o=>o!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=Cn(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return Oo(n,e)}async getVideoTracks(e){e&&=Cn(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return Oo(n,e)}async getAudioTracks(e){e&&=Cn(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return Oo(n,e)}async getPrimaryVideoTrack(e){e&&=Cn(e);let r=si(e,{sortBy:async a=>[Di((await a.getDisposition()).default),Di(await a.hasPairableAudioTrack()),Di(!await a.hasOnlyKeyPackets()),Bo(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=Cn(e);let r=await this.getPrimaryVideoTrack(),n=si(e,{sortBy:async s=>[Di(!r||s.canBePairedWith(r)),Di((await s.getDisposition()).default),Bo(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let r=this._backingToTrack.get(e);if(r)return r;let a=e.getType()==="video"?new _r(this,e):new Rr(this,e);return this._backingToTrack.set(e,a),a}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},xa=class extends Error{constructor(t="Input has an unsupported or unrecognizable format."){super(t),this.name="UnsupportedInputFormatError"}},ke=class extends Error{constructor(t="Input has been disposed."){super(t),this.name="InputDisposedError"}};var ei=class{constructor(t){this.source=t}get fileSize(){let t=this.source._getFileSize();if(t===void 0)throw new Error("Reading file size too early; read required first.");return t}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(t,e){if(this.source._disposed)throw new ke;if(t<0||this.fileSizeNonStrict!==null&&t+e>this.fileSizeNonStrict)return null;if(e===0){let a=new Uint8Array(0);return new xe(a,N(a),0,t,t)}let r=t+e,n=this.source._read(t,r,uu,lu);return _(n)?n.then(a=>a?new xe(a.bytes,a.view,a.offset,t,r):null):n?new xe(n.bytes,n.view,n.offset,t,r):null}requestSliceRange(t,e,r){if(this.source._disposed)throw new ke;if(t<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(t,ee(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(g(this.fileSizeNonStrict!==null),this.requestSlice(t,ee(this.fileSizeNonStrict-t,e,r)));return _(n)?n.then(a):a(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let t=1024;return(async()=>{let e=[],r=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let s=this.requestSliceRange(r,0,t);if(_(s)&&(s=await s),!s||s.length===0)break;let o=V(s,s.length);e.push(o),r+=s.length}let n=new Uint8Array(r),a=0;for(let s of e)n.set(s,a),a+=s.length;return new xe(n,N(n),0,0,r)})()}},xe=class i{constructor(t,e,r,n,a){this.bytes=t;this.view=e;this.offset=r;this.start=n;this.end=a;this.bufferPos=n-r}static tempFromBytes(t){return new i(t,N(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(t,e=this.end-t){if(tthis.end)throw new RangeError("Slicing outside of original slice.");return new i(this.bytes,this.view,this.offset,t,t+e)}},nt=(i,t)=>{if(i.filePosi.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+t}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},V=(i,t)=>{nt(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},L=i=>(nt(i,1),i.view.getUint8(i.bufferPos++)),fn=(i,t)=>{nt(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},he=i=>{nt(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},Dt=i=>{nt(i,3);let t=gi(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},ta=i=>{nt(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Ir=(i,t)=>{nt(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},M=i=>{nt(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},Pi=i=>{nt(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Ar=i=>{nt(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},hh=i=>{nt(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},Lc=(i,t)=>{let e,r;return t?(e=Ir(i,!0),r=Ir(i,!0)):(r=Ir(i,!1),e=Ir(i,!1)),r*4294967296+e},We=i=>{let t=M(i),e=M(i);return t*4294967296+e},zd=i=>{let t=Ar(i),e=M(i);return t*4294967296+e},$d=i=>{let t=Pi(i);return hh(i)*4294967296+t},qd=i=>{nt(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},vs=i=>{nt(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},oe=(i,t)=>{nt(i,t);let e="";for(let r=0;rye.decode(V(i,t)).split(`
+`).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var aa=128,Ue=10,In=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Gd=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=V(i,aa-3),i.filePos=e;let r=Pn(i,30);r&&(t.title??=r);let n=Pn(i,30);n&&(t.artist??=n);let a=Pn(i,30);a&&(t.album??=a);let s=Pn(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let c=V(i,30),u;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),u=Pn(i,28),i.skip(2)}else i.skip(-30),u=Pn(i,30);u&&(t.comment??=u);let l=L(i);l{let e=V(i,t),r=ki(e.indexOf(0),e.length),n=e.subarray(0,r),a="";for(let s=0;s{let t=i.filePos,e=oe(i,3),r=L(i),n=L(i),a=L(i),s=M(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=ks(s);return a&16&&(o+=Ue),{majorVersion:r,revision:n,flags:a,size:o}},Jr=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){z._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&16?t.size-Ue:t.size,n=V(i,r),a=new Du(t,n);if(t.flags&128&&t.majorVersion===3&&a.ununsynchronizeAll(),t.flags&64){let s=a.readU32();t.majorVersion===3?a.pos+=s:a.pos+=s-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let s=a.readId3V2Frame();if(!s)break;let o=a.pos,c=a.pos+s.size,u=!1,l=!1,d=!1;if(t.majorVersion===3?(u=!!(s.flags&64),l=!!(s.flags&128)):t.majorVersion===4&&(u=!!(s.flags&4),l=!!(s.flags&8),d=!!(s.flags&2)||!!(t.flags&128)),u){z._warn(`Skipping encrypted ID3v2 frame ${s.id}`),a.pos=c;continue}if(l){z._warn(`Skipping compressed ID3v2 frame ${s.id}`),a.pos=c;continue}if(d&&a.ununsynchronizeRegion(a.pos,c),e.raw??={},s.id==="TXXX"){let m=e.raw.TXXX??={},f=a.readId3V2TextEncoding(),p=a.readId3V2Text(f,c),b=a.readId3V2Text(f,c);m[p]??=b}else s.id[0]==="T"?e.raw[s.id]??=a.readId3V2EncodingAndText(c):e.raw[s.id]??=a.readBytes(s.size);switch(a.pos=o,s.id){case"TIT2":case"TT2":e.title??=a.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":e.description??=a.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":e.artist??=a.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":e.album??=a.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":e.albumArtist??=a.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let f=a.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),b&&Number.isInteger(b)&&b>0&&(e.tracksTotal??=b)}break;case"TPOS":case"TPA":{let f=a.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),b&&Number.isInteger(b)&&b>0&&(e.discsTotal??=b)}break;case"TCON":case"TCO":{let m=a.readId3V2EncodingAndText(c),f=/^\((\d+)\)/.exec(m);if(f){let p=Number.parseInt(f[1]);if(In[p]!==void 0){e.genre??=In[p];break}}if(f=/^\d+$/.exec(m),f){let p=Number.parseInt(f[0]);if(In[p]!==void 0){e.genre??=In[p];break}}e.genre??=m}break;case"TDRC":case"TDAT":{let m=a.readId3V2EncodingAndText(c),f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"TYER":case"TYE":{let m=a.readId3V2EncodingAndText(c),f=Number.parseInt(m,10);Number.isInteger(f)&&(e.date??=new Date(String(f)))}break;case"TBPM":case"TBP":{let m=a.readId3V2EncodingAndText(c),f=Number.parseInt(m,10);Number.isInteger(f)&&(e.beatsPerMinute??=f)}break;case"USLT":case"ULT":{let m=a.readU8();a.pos+=3,a.readId3V2Text(m,c),e.lyrics??=a.readId3V2Text(m,c)}break;case"COMM":case"COM":{let m=a.readU8();a.pos+=3,a.readId3V2Text(m,c),e.comment??=a.readId3V2Text(m,c)}break;case"APIC":case"PIC":{let m=a.readId3V2TextEncoding(),f;if(t.majorVersion===2){let y=a.readAscii(3);f=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else f=a.readId3V2Text(m,c);let p=a.readU8(),b=a.readId3V2Text(m,c).trimEnd(),h=c-a.pos;if(h>=0){let y=a.readBytes(h);e.images||(e.images=[]),e.images.push({data:y,mimeType:f,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:b})}}break;default:a.pos+=s.size;break}a.pos=c}},Du=class{constructor(t,e){this.header=t;this.bytes=e;this.pos=0;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let t=[];for(let e=0;e{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!s(r)){let o=this.header.majorVersion===4?e:ks(e);s(o)&&(r=o)}return this.pos=a,{id:t,size:r,flags:n}}}readId3V2TextEncoding(){let t=this.readU8();if(t>3)throw new Error(`Unsupported text encoding: ${t}`);return t}readId3V2Text(t,e){let r=this.pos,n=this.readBytes(e-this.pos);switch(t){case 0:{let a="";for(let s=0;so===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else if(n[0]===254&&n[1]===255){let a=new hi("utf-16be"),s=ki(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else{let a=ki(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),ye.decode(n.subarray(0,a))}case 2:{let a=new hi("utf-16be"),s=ki(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(0,s))}case 3:{let a=ki(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),ye.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},oi=class{constructor(t){this.helper=new Uint8Array(8);this.helperView=N(this.helper);this.writer=t}writeId3V2Tag(t){let e=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let r=this.writer.getPos(),n=new Set;for(let{key:o,value:c}of vt(t))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{let u=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),n.add("TRCK")}break;case"discNumber":{let u=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{let u={coverFront:3,coverBack:4,unknown:0};for(let l of c){let d=u[l.kind]??0,m=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,m,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ne(o)}if(t.raw)for(let o in t.raw){let c=t.raw[o];if(c==null||o.length!==4||n.has(o))continue;let u;if(typeof c=="string")if(Ct(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let d=0;d=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");m.writeBits(4,0),m.writeBits(32,u),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),a=0,s=N(n);s.setUint32(a,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),a+=4,s.setUint32(a,e.mimeType.length),a+=4,n.set(Y.encode(e.mimeType),8),a+=e.mimeType.length,s.setUint32(a,e.description?.length??0),a+=4,n.set(Y.encode(e.description??""),a),a+=e.description?.length??0,a+=16,s.setUint32(a,e.data.length),a+=4,n.set(e.data,a),a+=e.data.length,g(a===r);let o=new H(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,6),o.writeBits(24,r),this.writer.write(o.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(gh+Gm.byteLength),br(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=Qn(new Uint8Array(0),this.output._metadataTags,!1),n=new H(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,4),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null&&(Se(n,e.source._codec),g(n),g(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xe.tempFromBytes(r.data);s.skip(2);let o=V(s,2),c=new H(o),u=Hs(c.readBits(4));if(u===null)throw new Error("Invalid FLAC frame: Invalid block size.");qs(s);let l=Ks(s,u);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(r.data.length));let d=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,d),await this.writer.flush()}finally{a()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let r=1/0,n=0,a=1/0,s=0,o=0;for(let c=0;c\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,yh=/^WEBVTT(.|\n)*?\n{2}/,En=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Uo=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r
+`,`
+`).replaceAll("\r",`
+`),Ca.lastIndex=0;let e;if(!this.preambleText){if(!yh.test(t))throw new Error("WebVTT preamble incorrect.");e=Ca.exec(t);let r=t.slice(0,e?.index??t.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,e&&(t=t.slice(e.index),Ca.lastIndex=0)}for(;e=Ca.exec(t);){let r=t.slice(0,e.index),n=e[1],a=e.index+e[0].length,s=t.indexOf(`
+`,a)+1,o=t.slice(a,s).trim(),c=t.indexOf(`
+
+`,a);c===-1&&(c=t.length);let u=zo(e[2]),d=zo(e[3])-u,m=t.slice(s,c).trim();t=t.slice(c).trimStart(),Ca.lastIndex=0;let f={timestamp:u/1e3,duration:d/1e3,text:m,identifier:n,settings:o,notes:r},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}},kh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,zo=i=>{let t=kh.exec(i);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},No=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),n=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Vi=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e[(i%256+256)%256],q=i=>(At.setUint16(0,i,!1),[j[0],j[1]]),Nu=i=>(At.setInt16(0,i,!1),[j[0],j[1]]),Ym=i=>(At.setUint32(0,i,!1),[j[1],j[2],j[3]]),R=i=>(At.setUint32(0,i,!1),[j[0],j[1],j[2],j[3]]),ur=i=>(At.setInt32(0,i,!1),[j[0],j[1],j[2],j[3]]),zt=i=>(At.setUint32(0,Math.floor(i/2**32),!1),At.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),jm=i=>(At.setInt32(0,Math.floor(i/2**32),!1),At.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),Zm=i=>(At.setInt16(0,2**8*i,!1),[j[0],j[1]]),St=i=>(At.setInt32(0,2**16*i,!1),[j[0],j[1],j[2],j[3]]),Vu=i=>(At.setInt32(0,2**30*i,!1),[j[0],j[1],j[2],j[3]]),Uu=(i,t)=>{let e=[],r=i;do{let n=r&127;r>>=7,e.length>0&&(n|=128),e.push(n),t!==void 0&&t--}while(r>0||t);return e.reverse()},ue=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},Jm=i=>[St(i[0]),St(i[1]),Vu(i[2]),St(i[3]),St(i[4]),Vu(i[5]),St(i[6]),St(i[7]),Vu(i[8])],W=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),te=(i,t,e,r,n)=>W(i,[be(t),Ym(e),r??[]],n),ef=i=>i.isQuickTime?W("ftyp",[ue("qt "),R(512),ue("qt ")]):i.fragmented?i.cmaf?W("ftyp",[ue("iso5"),R(512),ue("iso5"),ue("iso6"),ue("mp41"),ue("cmfc"),ue("dash")]):W("ftyp",[ue("iso5"),R(512),ue("iso5"),ue("iso6"),ue("mp41")]):W("ftyp",[ue("isom"),R(512),ue("isom"),i.holdsAvc?ue("avc1"):[],ue("mp41")]),Lu=()=>W("styp",[ue("iso5"),R(0),ue("iso5"),ue("iso6"),ue("mp41"),ue("cmfc"),ue("dash")]),Wu=(i,t)=>{let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);return Number.isFinite(r)||(r=0),te("sidx",1,0,[R(1),R(at),zt(de(e,at)),zt(0),q(0),q(1),R(t&2147483647),R(de(r,at)),R(0)])},Pa=i=>({type:"mdat",largeSize:i}),tf=i=>({type:"free",size:i}),vn=i=>W("moov",void 0,[Th(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>wh(t,i.creationTime)),i.isFragmented?og(i.trackDatas):null,gg(i)]),Th=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,de(Ui(s),at)+de(s.startTimestampOffset??0,at)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!Wt(i)||!Wt(e),a=n?zt:R;return te("mvhd",+n,0,[a(i),a(i),R(at),a(e),St(1),Zm(1),Array(10).fill(0),Jm(Dr),Array(24).fill(0),R(r)])},wh=(i,t)=>{let e=df(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return W("trak",void 0,[Sh(i,t),r?Ah(i):null,xh(i,t),e.name!==void 0?W("udta",void 0,[W("name",[...Y.encode(e.name)])]):null])},Sh=(i,t)=>{let e=Math.max(0,de(Ui(i),at)+de(i.startTimestampOffset??0,at)),r=!Wt(t)||!Wt(e),n=r?zt:R,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:u}=i.track.metadata,l=Lt(qi(c??0),Va(u?-1:1,1));a=Da(l,i.info.width,i.info.height)}else a=Dr;let s=2;i.track.metadata.disposition?.default!==!1&&(s|=1);let o=i.type==="video"?0:i.type==="audio"?1:i.type==="subtitle"?2:ne(i);return te("tkhd",+r,s,[n(t),n(t),R(i.track.id),R(0),n(e),Array(8).fill(0),q(0),q(o),Zm(i.type==="audio"?1:0),q(0),Jm(a),St(i.type==="video"?i.info.width:0),St(i.type==="video"?i.info.height:0)])},Ah=i=>{let t=i.startTimestampOffset;if(g(t!==null),t>0){let e=de(t,at),r=de(Ui(i),at),n=!Wt(e)||!Wt(r),a=n?zt:R,s=n?jm:ur;return W("edts",void 0,[te("elst",n?1:0,0,[R(2),a(e),s(-1),St(1),a(r),s(0),St(1)])])}else{let e=de(-t,i.timescale),r=Math.max(0,de(Ui(i),at)+de(t,at)),n=!Pl(e)||!Wt(r),a=n?zt:R,s=n?jm:ur;return W("edts",void 0,[te("elst",n?1:0,0,[R(1),a(r),s(e),St(1)])])}},xh=(i,t)=>W("mdia",void 0,[Ch(i,t),Hu(!0,Ph[i.type],Ih[i.type]),Eh(i)]),Ch=(i,t)=>{let e=de(Ui(i),i.timescale),r=!Wt(t)||!Wt(e),n=r?zt:R;return te("mdhd",+r,0,[n(t),n(t),R(i.timescale),n(e),q(lf(i.track.metadata.languageCode??se)),q(0)])},Ph={video:"vide",audio:"soun",subtitle:"text"},Ih={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Hu=(i,t,e,r="\0\0\0\0")=>te("hdlr",0,0,[i?ue("mhlr"):R(0),ue(t),ue(r),R(0),R(0),ue(e,!0)]),Eh=i=>W("minf",void 0,[Fh[i.type](),Mh(),Dh(i)]),vh=()=>te("vmhd",0,1,[q(0),q(0),q(0),q(0)]),_h=()=>te("smhd",0,0,[q(0),q(0)]),Rh=()=>te("nmhd",0,0),Fh={video:vh,audio:_h,subtitle:Rh},Mh=()=>W("dinf",void 0,[Bh()]),Bh=()=>te("dref",0,0,[R(1)],[Oh()]),Oh=()=>te("url ",0,1),Dh=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return W("stbl",void 0,[Vh(i),eg(i),t?ag(i):null,t?sg(i):null,rg(i),ig(i),ng(i),tg(i)])},Vh=i=>{let t;if(i.type==="video")t=Uh(Tg(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=uf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);g(e),t=qh(e,i)}else i.type==="subtitle"&&(t=Zh(Ag[i.track.source._codec],i));return g(t),te("stsd",0,0,[R(1)],[t])},Uh=(i,t)=>W(i,[Array(6).fill(0),q(1),q(0),q(0),Array(12).fill(0),q(t.info.width),q(t.info.height),R(4718592),R(4718592),R(0),q(1),be(yr.length),ue(yr),Array(31-yr.length).fill(0),q(t.info.hasAlphaChannel?32:24),Nu(65535)],[wg[t.track.source._codec]?.(t)??null,zh(t),za(t.info.decoderConfig.colorSpace)?null:Nh(t),qu(t)]),qu=i=>i.avgBitrate===0&&i.maxBitrate===0?null:W("btrt",[R(0),R(i.maxBitrate),R(i.avgBitrate)]),zh=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:W("pasp",[R(i.info.pixelAspectRatio.num),R(i.info.pixelAspectRatio.den)]),Nh=i=>{let t=i.info.decoderConfig.colorSpace;return W("colr",[ue(i.muxer.isQuickTime?"nclc":"nclx"),q(t?.primaries!=null?Pt[t.primaries]:2),q(t?.transfer!=null?It[t.transfer]:2),q(t?.matrix!=null?Et[t.matrix]:2),i.muxer.isQuickTime?[]:be((t?.fullRange?1:0)<<7)])},Lh=i=>i.info.decoderConfig&&W("avcC",[...$(i.info.decoderConfig.description)]),Wh=i=>i.info.decoderConfig&&W("hvcC",[...$(i.info.decoderConfig.description)]),Xm=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),n=Number(e[2]),a=Number(e[3]),s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,u=e[5]?Number(e[5]):t.colorSpace?.primaries?Pt[t.colorSpace.primaries]:1,l=e[6]?Number(e[6]):t.colorSpace?.transfer?It[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?Et[t.colorSpace.matrix]:1;return te("vpcC",1,0,[be(r),be(n),be(c),be(u),be(l),be(d),q(0)])},Hh=i=>W("av1C",fs(i.info.decoderConfig.codec)),qh=(i,t)=>{let e=0,r,n=16,a=ae.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Re(s);n=8*o,n>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),q(1),q(e),q(0),R(0),q(t.info.numberOfChannels),q(n),q(0),q(0),q(t.info.sampleRate<2**16?t.info.sampleRate:0),q(0)];else{let s=a?0:-2;r=[Array(6).fill(0),q(1),q(e),q(0),R(0),q(t.info.numberOfChannels),q(Math.min(n,16)),Nu(s),q(0),q(t.info.sampleRate<2**16?t.info.sampleRate:0),q(0),a?[R(1),R(n/8),R(t.info.numberOfChannels*n/8)]:[R(0),R(0),R(0)],R(2)]}return W(i,r,[Sg(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,qu(t)])},zu=i=>{let t;switch(i.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let e=[...be(t),...be(21),...Ym(0),...R(i.maxBitrate),...R(i.avgBitrate)];if(i.info.decoderConfig.description){let r=$(i.info.decoderConfig.description);e=[...e,...be(5),...Uu(r.byteLength),...r]}return e=[...q(1),...be(0),...be(4),...Uu(e.length),...e,...be(6),...be(1),...be(2)],e=[...be(3),...Uu(e.length),...e],te("esds",0,0,e)},ci=i=>W("wave",void 0,[Kh(i),Qh(i),W("\0\0\0\0")]),Kh=i=>W("frma",[ue(uf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),Qh=i=>{let{littleEndian:t}=Re(i.track.source._codec);return W("enda",[q(+t)])},Gh=i=>{let t=i.info.numberOfChannels,e=3840,r=i.info.sampleRate,n=0,a=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){g(o.byteLength>=18);let c=$(o),u=Hr(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,n=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return W("dOps",[be(0),be(t),q(e),R(r),Nu(n),be(a),...s])},jh=i=>{let t=i.info.decoderConfig?.description;g(t);let e=$(t);return te("dfLa",0,0,[...e.subarray(4)])},or=i=>{let{littleEndian:t,sampleSize:e}=Re(i.track.source._codec),r=+t;return te("pcmC",0,0,[be(r),be(8*e)])},Xh=i=>{g(i.info.primingPacket);let t=ns(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let e=new Uint8Array(3),r=new H(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),W("dac3",[...e])},$h=i=>{g(i.info.primingPacket);let t=as(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let e=16;for(let s of t.substreams)e+=23,s.numDepSub>0?e+=9:e+=1;let r=Math.ceil(e/8),n=new Uint8Array(r),a=new H(n);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let s of t.substreams)a.writeBits(2,s.fscod),a.writeBits(5,s.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,s.bsmod),a.writeBits(3,s.acmod),a.writeBits(1,s.lfeon),a.writeBits(3,0),a.writeBits(4,s.numDepSub),s.numDepSub>0?a.writeBits(9,s.chanLoc):a.writeBits(1,0);return W("dec3",[...n])},Yh=i=>{g(i.info.primingPacket);let t=Yn(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return W("ddts",[...fd(t)])},Zh=(i,t)=>W(i,[Array(6).fill(0),q(1)],[xg[t.track.source._codec](t),qu(t)]),Jh=i=>W("vttC",[...Y.encode(i.info.config.description)]);var eg=i=>te("stts",0,0,[R(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[R(t.sampleCount),R(t.sampleDelta)])]),tg=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return te("stss",0,0,[R(t.length),t.map(([e])=>R(e+1))])},rg=i=>te("stsc",0,0,[R(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[R(t.firstChunk),R(t.samplesPerChunk),R(1)])]),ig=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Re(i.track.source._codec);return te("stsz",0,0,[R(t*i.info.numberOfChannels),R(i.samples.reduce((e,r)=>e+de(r.duration,i.timescale),0))])}return te("stsz",0,0,[R(0),R(i.samples.length),i.samples.map(t=>R(t.size))])},ng=i=>i.finalizedChunks.length>0&&Z(i.finalizedChunks).offset>=2**32?te("co64",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>zt(t.offset))]):te("stco",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>R(t.offset))]),ag=i=>te("ctts",1,0,[R(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[R(t.sampleCount),ur(t.sampleCompositionTimeOffset)])]),sg=i=>{let t=1/0,e=-1/0,r=1/0,n=-1/0;g(i.compositionTimeOffsetTable.length>0),g(i.samples.length>0);for(let s=0;s=2**31?null:te("cslg",0,0,[ur(a),ur(t),ur(e),ur(r),ur(n)])},og=i=>W("mvex",void 0,i.map(cg)),cg=i=>te("trex",0,0,[R(i.track.id),R(1),R(0),R(0),R(0)]),Ku=(i,t)=>W("moof",void 0,[ug(i),...t.map(lg)]),ug=i=>te("mfhd",0,0,[R(i)]),rf=i=>{let t=0,e=0,r=0,n=0,a=i.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|n},lg=i=>W("traf",void 0,[dg(i),mg(i),fg(i)]),dg=i=>{g(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:rf(e)};return te("tfhd",0,t,[R(i.track.id),R(r.duration),R(r.size),R(r.flags)])},mg=i=>(g(i.currentChunk),te("tfdt",1,0,[zt(de(i.currentChunk.startTimestamp,i.timescale))])),fg=i=>{g(i.currentChunk);let t=i.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(b=>b.size),r=i.currentChunk.samples.map(rf),n=i.currentChunk.samples.map(b=>de(b.timestamp-b.decodeTimestamp,i.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(n),u=o.size===2&&r[0]!==r[1],l=a.size>1,d=s.size>1,m=!u&&o.size>1,f=c.size>1||[...c].some(b=>b!==0),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+d,p|=1024*+m,p|=2048*+f,te("trun",1,p,[R(i.currentChunk.samples.length),R(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?R(r[0]):[],i.currentChunk.samples.map((b,h)=>[l?R(t[h]):[],d?R(e[h]):[],m?R(r[h]):[],f?ur(n[h]):[]])])},nf=i=>W("mfra",void 0,[...i.map(pg),hg()]),pg=i=>te("tfra",1,0,[R(i.track.id),R(63),R(i.finalizedChunks.length),i.finalizedChunks.map(e=>[zt(de(e.samples[0].timestamp,i.timescale)),zt(e.moofOffset),R(e.trafIndex+1),R(1),R(1)])]),hg=()=>te("mfro",0,0,[R(0)]),af=()=>W("vtte"),sf=(i,t,e,r,n)=>W("vttc",void 0,[n!==null?W("vsid",[ur(n)]):null,e!==null?W("iden",[...Y.encode(e)]):null,t!==null?W("ctim",[...Y.encode(No(t))]):null,r!==null?W("sttg",[...Y.encode(r)]):null,W("payl",[...Y.encode(i)])]),of=i=>W("vtta",[...Y.encode(i)]),gg=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=yg(r);n&&t.push(n)}else if(e==="mdta"){let n=kg(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&bg(t,i.output._metadataTags);return t.length===0?null:W("udta",void 0,t)},bg=(i,t)=>{for(let{key:e,value:r}of vt(t))switch(e){case"title":i.push(cr("\xA9nam",r));break;case"description":i.push(cr("\xA9des",r));break;case"artist":i.push(cr("\xA9ART",r));break;case"album":i.push(cr("\xA9alb",r));break;case"albumArtist":i.push(cr("albr",r));break;case"genre":i.push(cr("\xA9gen",r));break;case"date":i.push(cr("\xA9day",r.toISOString().slice(0,10)));break;case"comment":i.push(cr("\xA9cmt",r));break;case"lyrics":i.push(cr("\xA9lyr",r));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:ne(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||i.some(n=>n.type===e)||(typeof r=="string"?i.push(cr(e,r)):r instanceof Uint8Array&&i.push(W(e,Array.from(r))))}},cr=(i,t)=>{let e=Y.encode(t);return W(i,[q(e.length),q(lf("und")),Array.from(e)])},$m={"image/jpeg":13,"image/png":14,"image/bmp":27},cf=(i,t)=>{let e=[];for(let{key:r,value:n}of vt(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:Ut(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:Ut(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:Ut(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:Ut(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:Ut(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:Ut(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:Ut(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:W("data",[R(21),R(0),q(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:Ut(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:Ut(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:W("data",[R($m[a.mimeType]??0),R(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();e.push({key:"track",value:Ut(a)})}else e.push({key:"trkn",value:W("data",[R(0),R(0),q(0),q(n),q(i.tracksTotal??0),q(0)])});break;case"discNumber":t||e.push({key:"disc",value:W("data",[R(0),R(0),q(0),q(n),q(i.discsTotal??0),q(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ne(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:Ut(n)}):n instanceof Uint8Array?e.push({key:r,value:W("data",[R(0),R(0),Array.from(n)])}):n instanceof yt&&e.push({key:r,value:W("data",[R($m[n.mimeType]??0),R(0),Array.from(n.data)])}))}return e},yg=i=>{let t=cf(i,!1);return t.length===0?null:te("meta",0,0,void 0,[Hu(!1,"mdir","","appl"),W("ilst",void 0,t.map(e=>W(e.key,void 0,[e.value])))])},kg=i=>{let t=cf(i,!0);return t.length===0?null:W("meta",void 0,[Hu(!1,"mdta",""),te("keys",0,0,[R(t.length)],t.map(e=>W("mdta",[...Y.encode(e.key)]))),W("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...R(r+1));return W(n,void 0,[e.value])}))])},Ut=i=>W("data",[R(1),R(0),...Y.encode(i)]),Tg=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},wg={avc:Lh,hevc:Wh,vp8:Xm,vp9:Xm,av1:Hh,prores:null},uf=(i,t,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";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return t}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"}},Sg=(i,t)=>{switch(i){case"aac":return zu;case"mp3":return zu;case"opus":return Gh;case"vorbis":return zu;case"flac":return jh;case"ac3":return Xh;case"eac3":return $h;case"dts":return Yh}if(t)switch(i){case"pcm-s24":return ci;case"pcm-s24be":return ci;case"pcm-s32":return ci;case"pcm-s32be":return ci;case"pcm-f32":return ci;case"pcm-f32be":return ci;case"pcm-f64":return ci;case"pcm-f64be":return ci}else switch(i){case"pcm-s16":return or;case"pcm-s16be":return or;case"pcm-s24":return or;case"pcm-s24be":return or;case"pcm-s32":return or;case"pcm-s32be":return or;case"pcm-f32":return or;case"pcm-f32be":return or;case"pcm-f64":return or;case"pcm-f64be":return or}return null},Ag={webvtt:"wvtt"},xg={webvtt:Jh},lf=i=>{g(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};var lr=class{constructor(t,e){this.finalized=!1;this.started=!1;this.pos=0;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1;if(t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(t){g(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(eGu)throw new Error(`ArrayBuffer exceeded maximum size of ${Gu} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this._bytes,0),this._buffer=n,this._bytes=a}}}_start(){}_write(e,r){this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return this._bytes.slice(e,r)}},Cg=2**24,Pg=2,Ia=class extends ze{constructor(e,r={}){super();this._sections=[];this._lastWriteEnd=0;this._lastFlushEnd=0;this._streamWriter=null;this._writeError=null;this._chunks=[];if(!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??Cg}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let n=r-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(g(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((n,a)=>n.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n{this._writeError??=a}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){let n=this._chunks.findIndex(u=>u.start<=r&&rPg){for(let u=0;u=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((a,s)=>a.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){g(this._streamWriter);for(let r=0;r{this._writeError??=u}),this._lastFlushEnd=n.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;g(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}},ju=class extends ze{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new Ia(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:r=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return g(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,g(this._writer),this._writer.write(r.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Xu=class extends ze{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!ff.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let n=new WritableStream({start:async()=>{this._fileHandle=await ff.fs.open(e,"w")},write:async a=>{g(this._fileHandle),await this._fileHandle.write(a.data,0,a.data.byteLength,a.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new Ia(n,{chunked:!0,...r})}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Ni=class extends ze{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},Lo=class extends ze{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},pt=class{constructor(t,e){this.rootPath=t;this.getTarget=e;if(typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}};var at=57600,Ig=2082844800,df=i=>{let t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},de=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},Ui=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;re&&(e=n.timestamp+n.duration)}return t===1/0?0:e-t},Wo=class extends Pe{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new zi;this.auxWriter=new lr(this.auxTarget,!1);this.auxBoxWriter=new Vi(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=J();this.creationTime=Math.floor(Date.now()/1e3)+Ig;this.finalizedChunks=[];this.wroteFragmentedHeader=!1;this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.minWrittenTimestamp=1/0;this.maxWrittenEndTimestamp=-1/0;this.segmentHeaderSize=null;this.format=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof Rn,this.isCmaf=r instanceof _n,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof _n?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof zi),this.boxWriter=new Vi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof zi?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),a=new lr(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new Vi(a)}let r=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(g(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(ef({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:a,start:s}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(a,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output.tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Pa(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ts({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(p=>p.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig};g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");let p=Zt(r.data);if(!p)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=es(p),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");let p=er(r.data);if(!p)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=rd(p),o=!0}let c=Vl(1/(e.metadata.frameRate??at),1e6).den,u=s.displayAspectWidth,l=s.displayAspectHeight,d=u===void 0||l===void 0?{num:1,den:1}:Gt({num:u*s.codedHeight,den:l*s.codedWidth}),m=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:m},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((p,b)=>p.track.id-b.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let u=et(xe.tempFromBytes(r.data));if(!u)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=kt[u.samplingFrequencyIndex],d=Xt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=$i({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ae.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;gs(r),g(r),g(r.config);let a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(s.info.requiresAnnexBTransformation){let u=[...Lr(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(u.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Ja(u,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let d=et(xe.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");let m=d.crcCheck===null?Er:mt;o=o.subarray(m)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=r.timestamp,u=r.duration;if(s.info.requiresPcmTransformation){let m=Re(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(u=o.byteLength/m/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let f=c-s.info.expectedNextPcmPacketTimestamp;if(f<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+p}}s.info.expectedNextPcmPacketTimestamp=c+u}let l=this.createSampleForTrack(s,o,c,u,r.type);await this.registerSample(s,l)}finally{a()}}async padWithSilence(e,r,n){let a=de(n,e.timescale);if(n=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Re(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(s*c).fill(o),l=this.createSampleForTrack(e,new Uint8Array(u.buffer),r,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let l of e.cueQueue)g(l.timestamp<=r),g(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let a=[...n].sort((l,d)=>l-d),s=a[0],o=a[1]??s;if(r=o)break;En.lastIndex=0;let m=En.test(d.text),f=d.timestamp+d.duration,p=e.cueToSourceId.get(d);if(p===void 0&&oa.timestamp).sort((a,s)=>a-s);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let a=0;a=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=Z(e.timeToSampleTable);if(g(d),d.sampleCount===1){d.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===c?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let m=Z(e.compositionTimeOffsetTable);g(m),m.sampleCompositionTimeOffset===o?m.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=de(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,g(e.lastSample),g(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){g(r.type==="key");let a=de(r.timestamp,e.timescale,!1),s=Math.round(a-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let a=e.track.metadata.maximumPacketCount;if(g(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),g(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(g(!this.isFragmented),g(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,a)=>n+de(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Z(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)g(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(g(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestampp.currentChunk);if(r.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,a=Ku(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Mt,u=1/0;for(let p=0;p=2**32;if(d)for(let p of r)p.currentChunk.offset+=wr-Mt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=Ku(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:b}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,b,u)}g(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=Pa(d);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(d?wr:Mt));for(let p of r)for(let b of p.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.formatOptions.onMdat){let{data:p,start:b}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(p,b)}for(let p of r)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,r)):e.sampleQueue.push(r)}async createFastStartReserveMdat(){g(this.writer),g(this.boxWriter),this.ensureOneEnabledTrack();let e=vn(this),n=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Pa(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let s of a.sampleQueue)await this.addSampleToTrack(a,s);a.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;g(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(a=>a.type===e);if(r.length===0)continue;if(!r.some(a=>a.track.metadata.disposition?.default!==!1)){let a=r[0];a.track.metadata.disposition={...a.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){g(this.isFragmented);let e=await this.mutex.acquire();try{for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas){await this.finalizeCurrentChunk(r);let n=Ui(r);if(n>0){let c=0;for(let u of r.samples)c+=u.size;r.avgBitrate=Math.round(8*c/n)}else r.avgBitrate=0;let a=0,s=0,o=0;for(let c=0;c=1;)s-=r.samples[a].size,a++;o=Math.max(o,s)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let c=0;c=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let n=vn(this);if(this.boxWriter.writeBox(n),this.formatOptions.onMoov){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(a,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let a of this.finalizedChunks)for(let s of a.samples)g(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(a,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Lu()),this.boxWriter.writeBox(Wu(this,r))}else{let r=this.writer.getPos(),n=nf(this.trackDatas);this.boxWriter.writeBox(n);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{g(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);g(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}let a=vn(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(tf(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var Eg=-(2**15),vg=2**15-1,pf=6,hf=5,_g={video:1,audio:2,subtitle:17},Ho=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.allTracksKnown=J();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.startTimestamp=1/0;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new _s(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let r of this.output.tracks)r.isVideoTrack()&&r.metadata.decoderConfig?this.getVideoTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig}):r.isAudioTrack()&&r.metadata.decoderConfig&&this.getAudioTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={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 Li?"webm":"matroska"},{id:17031,data:4},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),c={id:290298740,data:[{id:19899,data:[{id:21419,data:n},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:o},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=c}createSegmentInfo(){let e={id:17545,data:new sn(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:yr},{id:22337,data:yr},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=Ve[r.track.source._codec];g(n),r.type==="audio"&&r.track.source._codec==="dts"&&(r.info.decoderConfig.codec==="dtse"?n="A_DTS/EXPRESS":r.info.decoderConfig.codec==="dtsl"&&(n="A_DTS/LOSSLESS"));let a=0;if(r.type==="audio"&&r.track.source._codec==="opus"){a=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=$(s),c=Hr(o);a=Math.round(1e9*(c.preSkip/Ft))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:_g[r.type]},r.track.metadata.disposition?.default===!1?{id:136,data:0}:null,r.track.metadata.disposition?.forced?{id:21930,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,r.track.metadata.disposition?.original?{id:21934,data:1}:null,r.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??se},{id:134,data:n},r.codecPrivate?{id:25506,data:$(r.codecPrivate)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Vt(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,transformationMatrix:n}=e.track.metadata,a=[r?{id:2352003,data:1e9/r}:null],s,o,c;if(n){s=fi(n);let b=Lt(qi(-s),n);o=Math.sign(b[0]),c=Math.sign(b[4]),c===-1&&(c=1,o=-o,s=mr(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let u=s?mr(o===-1?s:-s):0,l=Math.round(Math.acos(o)*Oa),d=Math.round(Math.acos(c)*Oa),m=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,p={id:224,data:[{id:176,data:e.info.width},{id:186,data:e.info.height},m?{id:21680,data:e.info.aspectRatio.num}:null,m?{id:21690,data:e.info.aspectRatio.den}:null,m?{id:21682,data:3}:null,e.info.alphaMode?{id:21440,data:1}:null,za(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?Et[f.matrix]:2},{id:21946,data:f?.transfer!=null?It[f.transfer]:2},{id:21947,data:f?.primaries!=null?Pt[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},u||l||d?{id:30320,data:[{id:30321,data:0},l?{id:30323,data:new Yr(l)}:null,d?{id:30324,data:new Yr(d)}:null,u?{id:30325,data:new Yr((u+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=ae.includes(e.track.source._codec)?Re(e.track.source._codec):null;return[{id:225,data:[{id:181,data:new Yr(e.info.sampleRate)},{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new Vt(s)},typeof o=="string"?{id:17543,data:new Vt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of vt(n))switch(s){case"title":r("TITLE",o),a.add("TITLE");break;case"description":r("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":r("ARTIST",o),a.add("ARTIST");break;case"album":r("ALBUM",o),a.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":r("GENRE",o),a.add("GENRE");break;case"beatsPerMinute":r("BPM",o.toString()),a.add("BPM");break;case"comment":r("COMMENT",o),a.add("COMMENT");break;case"lyrics":r("LYRICS",o),a.add("LYRICS");break;case"date":r("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${o}/${n.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${o}/${n.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ne(s)}if(n.raw)for(let s in n.raw){let o=n.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&r(s,o)}e.length!==0&&(this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,a=e.images??[];for(let s of a){let o=s.name;o===void 0&&(o=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(zl(s.mimeType)??""));let c;for(;;){c=0n;for(let u=0;u<8;u++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new Vt(s.description)}:null,{id:18030,data:new Vt(o)},{id:18016,data:s.mimeType},{id:18012,data:s.data},{id:18094,data:c}]})}for(let[s,o]of Object.entries(e.raw??{}))!(o instanceof Nr)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&Ka(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Vt(o.description)}:null,{id:18030,data:new Vt(o.name??"")},{id:18016,data:o.mimeType??""},{id:18012,data:o.data},{id:18094,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:423732329,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:408125543,size:this.format._options.appendOnly?-1:pf,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return g(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ms({isWebM:this.format instanceof Li,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n.decoderConfig),g(n.decoderConfig.codedWidth!==void 0),g(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,o=n.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:Gt({num:s,den:o}),u={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:e.metadata.canBeTransparent||(r?!!r.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?u.codecPrivate=new Uint8Array(yd(u.info.decoderConfig.codec)):e.source._codec==="av1"?u.codecPrivate=new Uint8Array(fs(u.info.decoderConfig.codec)):e.source._codec==="prores"&&(u.codecPrivate=Y.encode(n.decoderConfig.codec)),this.trackDatas.push(u),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let u=et(xe.tempFromBytes(r.data));if(!u)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=kt[u.samplingFrequencyIndex],d=Xt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=$i({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;gs(r),g(r),g(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Y.encode(r.config.description),closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n);s.info.alphaMode??=!!r.sideData.alpha;let o=r.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=r.timestamp,l=r.duration;e.metadata.frameRate!==void 0&&(u=qt(u,e.metadata.frameRate),l=qt(l,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,u,l,r.type,d);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,m),s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let l=et(xe.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let d=l.crcCheck===null?Er:mt;o=o.subarray(d)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=this.createInternalChunk(o,r.timestamp,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);En.lastIndex=0,o=o.replace(En,m=>{let p=zo(m.slice(1,-1))-c;return`<${No(p)}>`});let u=Y.encode(o),l=`${r.settings??""}
+${r.identifier??""}
+${r.notes??""}`,d=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?Y.encode(l):null);s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp=2&&n.skipBits(1);let d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];Il(r.data,n.pos,n.pos+3,d)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let f=m.chunkQueue[0];return f?f.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{g(this.currentClusterStartMsTimestamp!==null),g(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>vg}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:hf,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(g(this.currentCluster),!this.format._options.appendOnly){let a=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(a,hf),this.writer.seek(s)}if(this.format._options.onCluster){g(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)g(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,a)},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),g(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,pf);let n=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new sn(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),g(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var qo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,n=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let h=0;h<16;h++){let y=bs[u+h];if(ys(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=h;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,d=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=n,this.helper[2]=l,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let m=Gr(t.mpegVersionId,t.channel);this.writer.seek(e+m),this.writeU32(Qr);let f=0;t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writer.write(t.toc??new Uint8Array(100));let p=bs[u+c],b=ys(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+b-this.writer.getPos()))}};var Ko=class extends Pe{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new qo(this.writer),br(this.output._metadataTags)||new oi(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,r){let n=await this.mutex.acquire();try{if(!this.xingFrameData&&this.writeXingHeader){let a=N(r.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=a.getUint32(0,!1),o=jr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");let c=Gr(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===Qr||u===en)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,r.timestamp,r.type==="key"),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");let n=this.output.tracks[0];g(n?.isAudioTrack());let a=n.metadata.primingPacket;if(a){let s=N(a.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");let o=s.getUint32(0,!1),c=jr(o,null).header;if(!c)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],u=null,l=-1;for(let d=0;d0){let s=new Uint8Array(100);for(let o=0;o<100;o++){let c=Math.floor(this.framePositions.length*(o/100)),u=this.framePositions[c]-this.xingFramePos;s[o]=256*(u/a)}this.xingFrameData.toc=s}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}}e()}};var Rg=8192,Qo=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(zs);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0);for(let r of this.output.tracks)g(r.isAudioTrack()),r.metadata.decoderConfig&&this.getTrackData(r,{decoderConfig:r.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,Us({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));g(e.source._codec==="vorbis"||e.source._codec==="opus"),Se(r,e.source._codec),g(r),g(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?Ft:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startTimestampInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(g(r.decoderConfig),e.track.source._codec==="vorbis"){g(r.decoderConfig.description);let n=$(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let h=0;for(;;){let y=n[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(h+=y,y<255)return h}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=n.subarray(a,a+=o);a+=c;let d=n.subarray(a),m=new Uint8Array(7);m[0]=3,m[1]=118,m[2]=111,m[3]=114,m[4]=98,m[5]=105,m[6]=115;let f=Qn(m,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});let b=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:is(d).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=$(r.decoderConfig.description),a=new Uint8Array(8),s=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=Qn(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Hr(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),s.startTimestampInSamples===null){let m=Math.round(r.timestamp*s.internalSampleRate),f=s.codecInfo.opusInfo?.preSkip??0;s.startTimestampInSamples=m>0?m+f:0,s.currentTimestampInSamples=s.startTimestampInSamples}let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=oa(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u;let l=r.duration>0?ee(Math.round(r.duration*s.internalSampleRate),0,c):c,d=s.startTimestampInSamples>0&&s.audioPacketCount===1;s.audioPacketCount++,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,trimmedDurationInSamples:l,forcePageFlush:d}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;let d=s<255;if(e.currentLacingValues.length===255){let m=r.data.subarray(o,c);if(o=c,e.currentPageData.push(m),e.currentPageSize+=m.length,this.writePage(e,n&&d),d)return}if(d)break;s-=255}let u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Rg||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,sa,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Bl(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=Vs(o);if(this.pageView.setUint32(22,c,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var Fg=0,Tf=4096,gf=256,Mg=224,bf=192,yf=new Uint8Array([9,240]),kf=new Uint8Array([70,1]),Go=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(this.packetBuffer);this.allTracksKnown=J();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Gs(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;tr(r,e.source._codec),g(r?.decoderConfig);let a=e.source._codec;g(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=gf+this.trackDatas.length,c=Mg+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;Se(r,e.source._codec),g(r?.decoderConfig);let a=e.source._codec;g(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3"||a==="dts");let s,o;switch(a){case"aac":s=15,o=bf+this.audioTrackIndex++;break;case"mp3":s=3,o=bf+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break;case"dts":s=130,o=189;break}let c=gf+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=$(s);a==="avc"?e.avcDecoderConfig=Wr(o):e.hevcDecoderConfig=Yi(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of Lr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Yt(o[0])===9:_t(o[0])===35)||n.push(o)}let a=r==="avc"?yf:kf;return n.unshift(a),qn(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Ya(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Yt(l[0])===9:_t(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===33)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===32)for(let d of l.nalUnits)o.unshift(d)}let c=n==="avc"?yf:kf;return o.unshift(c),qn(o)}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3"||a==="dts")return r.data;if(e.inputIsAdts===null){let u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=$t($(u)),d=ja(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return r.data;g(e.adtsHeader),g(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;Xa(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a0&&s.packetQueue[0].presentationTimestamp0){let E=this.adaptationFieldBuffer;w===1?E[0]=0:(E[0]=w-1,E[1]=Number(k)<<7|Number(y)<<6,E.fill(255,2,w)),A=E.subarray(0,w)}let x=Math.min(184-w,h),C=this.payloadBuffer.subarray(0,x),P=0;if(f0,c=n?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let u=4;n&&(this.packetBuffer.set(n,u),u+=n.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},Bg=79764919,wf=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Bg:t<<1;wf[i]=t>>>0&4294967295}var Sf=i=>{let t=4294967295;for(let e=0;e>>24^r])>>>0}return t},Wi=new Uint8Array(16);{let i=N(Wi);Wi[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),Wi[5]=193,Wi[6]=0,Wi[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|Tf&8191,!1),i.setUint32(12,Sf(Wi.subarray(0,12)),!1)}var Og=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=jn.length:c.streamType===135&&(t+=Xn.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=N(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of i)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|jn.length,!1),a+=2,r.set(jn,a),a+=jn.length):c.streamType===135?(n.setUint16(a,61440|Xn.length,!1),a+=2,r.set(Xn,a),a+=Xn.length):(n.setUint16(a,61440,!1),a+=2);let s=Sf(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var jo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(Y.encode(t))}};var Xo=class extends Pe{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new jo(this.writer);let r=this.output.tracks[0];g(r?.isAudioTrack()),r.metadata.decoderConfig&&(Se({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Se(n,e.source._codec),g(n),g(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,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{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,a=e.source._codec,s=Re(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=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.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!br(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ne(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:d}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,d)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let n=new Set,a=(c,u)=>{if(!Ct(u)){z._warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,d=new Uint8Array(l);for(let m=0;mr[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===2&&e===6?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;g(l=0&&p=0&&b=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}};var Fn=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1;this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},Fr=class extends Fn{constructor(t){if(super(),!le.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${le.join(", ")}.`);this._codec=t}},Ju=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},ui=class extends Fr{constructor(t){super(t)}add(t,e){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Ju(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},Ea=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.encoderConfig=null;this.encodersReclaimed=!1;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.emittedEncoderPackets=0;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new Or;this.customEncoderQueueSize=0;this.defaultEncodeOptions={};this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let d=a.transform?.width,m=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(s!=="deny"),d=this.outputWidth,m=this.outputHeight,f=s);let p=await t.transform({width:d,height:m,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let d=t.timestamp+t.duration,m=hc(t.timestamp,l);if(this.frameRateLastSample!==null)if(m<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(m,r);t===n&&(t=t.clone(),e=!0),t.setTimestamp(m),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=m,this.frameRateLastEndTimestamp=d}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(_(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof Xe?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new Xe(o)):s.push(new Xe(o,{timestamp:t.timestamp,duration:t.duration}))}catch(o){for(let c of s)c!==t&&c.close();for(let c of a)(c instanceof Xe&&c!==t||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}n=s}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...this.defaultEncodeOptions,...a.encodeOptions,...e},u={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let l=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await d}else{g(this.encoder);let l=a.toVideoFrame(),d=Q(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===l.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(l,u)}finally{l.close()}}else{this.splitter||(this.splitter=new el);let{colorFrame:p,alphaFrame:b}=await this.splitter.split(l);this.alphaFrameQueue.push(b);try{this.encoder.encode(p,u)}finally{p.close()}}else try{this.encoder.encode(l,u)}finally{l.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let u=1;u{let e=ai(this.encodingConfig.quality,this.encodingConfig.bitrate);g(e!==void 0);let r=Au({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),n=null,a;for(let o of r){let c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),a=Sn.find(l=>l.supports(this.encodingConfig.codec,c)),a){n=o;break}if(typeof VideoEncoder>"u")continue;if(c.alpha="discard",this.encodingConfig.alpha==="keep"&&(c.latencyMode="quality"),(c.width%2===1||c.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${c.width}x${c.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(c)).supported){n=o;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(Gi("VideoEncoder"));let o=r[0].config,c=r.map(({config:u,quantizer:l})=>l!==null?`quantizer ${l}`:`${u.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let s=n.config;n.quantizer!==null?this.defaultEncodeOptions=Cu(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=s.bitrate??null,a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof X))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.");Ju(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.createWebCodecsEncoders()),g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let t=this.encoderConfig;g(t);let e=[],r=[],n=0,a=0,s=(c,u)=>{if(Ul(c)){this.encodersReclaimed=!0;return}c.stack=u,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){this.addPacket(c,null,u);return}let l=this.alphaFrameQueue.shift();g(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,l.close(),e.push({chunk:c,meta:u})):a===0?this.addPacket(c,null,u):(r.push(n+a),e.push({chunk:c,meta:u}))},error:c=>s(c,o)}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let c=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(u,l)=>{a--;let d=e.shift();for(g(d!==void 0),this.addPacket(d.chunk,u,d.meta),n++;r.length>0&&r[0]===n;){r.shift();let m=e.shift();g(m!==void 0),this.addPacket(m.chunk,null,m.meta)}},error:u=>s(u,c)}),this.alphaEncoder.configure(t)}}addPacket(t,e,r){let n={};if(e){let l=new Uint8Array(e.byteLength);e.copyTo(l),n.alpha=l}let a=X.fromEncodedChunk(t,n),s=this.encoderConfig;g(s),r?.decoderConfig&&(r.decoderConfig.codec=Kr({width:s.width,height:s.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?$(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:s.codec.includes("avc1.")?1:s.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?Zt(a.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?er(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?Zi(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?Ci(a.data):null,proresFormat:null}));let o=Q(this.preciseTimings,t.timestamp,l=>l.microsecondTimestamp),c=o!==-1?this.preciseTimings[o]:null,u=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(u=qr(this.encodingConfig.codec,r.decoderConfig,a.data)),(c&&c.microsecondTimestamp===t.timestamp||u!==null)&&(a=a.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:u??void 0})),Ju(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(l=>{this.setError(l)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){g(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,r=hc(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await zr(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},$u=null,el=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!$u){let n=new Blob([`(${Dg.toString()})()`],{type:"application/javascript"});$u=URL.createObjectURL(n)}this.worker=new Worker($u),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()})}let e=this.nextRequestId++,r=J();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Dg=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=c*u,d=Math.ceil(c/2),m=Math.ceil(u/2),f=l+d*m*2,p=new Uint8Array(f);for(let k=0,T=3;k{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),d=s.includes("P12"),m=l||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let b=c*u,h=f*p,y=b*m,k=h*m,T=b*m,w=y+k*2,A=s.replace("A",""),x=Math.ceil(c/2),C=Math.ceil(u/2),P=x*C,S=P*m,I=T+2*S,E=new Uint8Array(I),v=w;E.set(a.subarray(v,v+T),0);let F=T,O=l?512:d?2048:128;m===1?E.fill(O,F):new Uint16Array(E.buffer,F,2*P).fill(O);let D=l?"I420P10":d?"I420P12":"I420",U=new VideoFrame(a.subarray(0,w),{format:A,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),K={format:D,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[E.buffer]},ie=new VideoFrame(E,K);return{colorFrame:U,alphaFrame:ie}}},Mn=class extends Fr{constructor(t){Co(t),super(t.codec),this._encoder=new Ea(this,t)}add(t,e){if(!(t instanceof Xe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},tl=class extends Fr{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Co(e),super(e.codec),this._encoder=new Ea(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");let n=new Xe(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},rl=class extends Fr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(Co(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new Ea(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||z._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=0,s=!1,o=null,c=0,u=()=>{if(g(e!==null),!this._lastVideoFrame)return;g(n!==null),g(r!==null);let m=performance.now();for(;m-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});d(p,m)}};e!==null&&(this._timerHandle=Kl(u,4));let l=m=>{if(e===null)d(m);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=m):(d(m.clone(),f),n=f,this._lastVideoFrame=m)}},d=(m,f=performance.now())=>{if(s){m.close();return}a++;let p=m.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}m.close();return}if(r===null){r=p;let h,y=this._options.timestampBase??"synced-zero";if(y==="unix")h=Date.now()/1e3;else if(y==="zero")h=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,h=0):h=f/1e3-k._firstMediaStreamTimestamp}c=h-r}if(o=p,this._encoder.getQueueSize()>=8){m.close();return}let b=new Xe(m,{timestamp:p+c});this._encoder.add(b,!0).catch(h=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(h),this._workerTrackId!==null&&Zu({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let m=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});m.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await Ng())this._workerTrackId=Ug++,Zu({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},xt.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&Ql(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(g(this._workerListener),Zu({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(g(this._workerListener),xt.removeEventListener("message",this._workerListener),xt.removeEventListener("message",n),r())};xt.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},Mr=class extends Fn{constructor(t){if(super(),!fe.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${fe.join(", ")}.`);this._codec=t}},li=class extends Mr{constructor(t){super(t)}add(t,e){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},va=class{constructor(t,e){this.source=t;this.encodingConfig=e;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 Or;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new $o({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Fm(t.format)!==r.transform.sampleFormat){let n=Mm(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process)try{let n=r.transform.process(t);if(_(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ce))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(let a of n)await this.encodeSample(a,!0)}finally{for(let a of n)a instanceof Ce&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=new Ce({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{g(this.encoder);let r=t.toAudioData();this.encoder.encode(r),r.close(),e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){g(this.outputSampleSize),g(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t,o=2048,c=[];for(let b=0;b{let{numberOfChannels:e,sampleRate:r}=t,n=ai(this.encodingConfig.quality,this.encodingConfig.bitrate),a=xu({numberOfChannels:e,sampleRate:r,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let s=An.find(o=>o.supports(this.encodingConfig.codec,a));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof X))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.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(ae.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(Gi("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{o=!1}if(!o)throw new Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let m=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?m=!0:m=$t($(l.decoderConfig.description)).objectType===0,m){let f=Number(Z(a.codec.split(".")));l.decoderConfig.description=$i({objectType:f,outputNumberOfChannels:l.decoderConfig.numberOfChannels,outputSampleRate:l.decoderConfig.sampleRate})}}let d=X.fromEncodedChunk(u);d=d.clone({timestamp:qt(d.timestamp,a.sampleRate),duration:u.duration!=null?qt(d.duration,a.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).catch(m=>{this.setError(m)})},error:u=>{u.stack=c,this.setError(u)}}),this.encoder.configure(a)}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Re(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ee(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ee(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ee(Math.round(o*32768),-32768,32767);a.setUint8(s,Nm(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ee(Math.round(o*32768),-32768,32767);a.setUint8(s,Wm(c))}:g(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ee(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ee(Math.round(o*32768),-32768,32767),n):g(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>bi(a,s,ee(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Ml(a,s,ee(Math.round(o*8388608),-8388608,8388607),n):g(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ee(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ee(Math.round(o*2147483648),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):g(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):g(!1);break;default:ne(r),g(!1)}}async flushAndClose(t){try{t||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},_a=class extends Mr{constructor(t){Po(t),super(t.codec),this._encoder=new va(this,t)}add(t){if(!(t instanceof Ce))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},il=class extends Mr{constructor(t,e={}){if(Po(t),typeof e!="object"||!e)throw new TypeError("options must be an object.");if(e.startTimestamp!==void 0&&!Number.isFinite(e.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(t.codec),this._encoder=new va(this,t),this._accumulatedTime=e.startTimestamp??0}async add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let e=Ce._fromAudioBuffer(t,this._accumulatedTime);this._accumulatedTime+=t.duration;for(let r of e)await this._encoder.add(r,!0)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},nl=class extends Mr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Po(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new va(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||z._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-d._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new Ce(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let u=0;this._scriptProcessorNode.onaudioprocess=l=>{let d=Ce._fromAudioBuffer(l.inputBuffer,u);u+=l.inputBuffer.duration;for(let m of d)s(m)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(g(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}},Vg=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:ne(n)}})},Ug=0,xt=null,zg=()=>{let i=new Blob([`(${Vg.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);xt=new Worker(t)},Yu=null,Ng=async()=>Yu!==null?Yu:(xt||zg(),new Promise(i=>{g(xt);let t=e=>{let r=e.data;r.type==="support"&&(Yu=r.supported,xt.removeEventListener("message",t),i(r.supported))};xt.addEventListener("message",t)})),Zu=(i,t)=>{g(xt),t?xt.postMessage(i,t):xt.postMessage(i)},Bn=class extends Fn{constructor(t){if(super(),!Ye.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Ye.join(", ")}.`);this._codec=t}},al=class extends Bn{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new Uo({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var Af=i=>i==="opus"?"Opus":i,Zo=class extends Pe{constructor(e,r){if(!(e._target instanceof pt))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),r=this.output.tracks.some(y=>y.metadata.isRelativeToUnixEpoch),n=this.output.tracks.some(y=>!y.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,u=!1;for(let y of this.output.tracks){y.type==="video"&&(o=!0);let k=new Map;for(let T of this.output.tracks){if(y===T||!y.canBePairedWith(T))continue;if(y.type===T.type){c||(z._warn(`Illegal pairing of two ${y.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(y.isVideoTrack()&&y.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){u||(z._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let w=k.get(T.source._codec);w||k.set(T.source._codec,w=[]),w.push(T)}for(let[,T]of k){let w=T.map(C=>C.id).join("-");s.find(C=>C.key===w)||s.push({name:T[0].type+"-"+(s.length+1),key:w,tracks:T,needsEmit:!1,firstNoUri:!1});let x=a.get(y);x||a.set(y,x=[]),x.push(w)}}let l=o?"video":"audio",d=[],m=[],f=[];for(let y of this.output.tracks){let k=a.get(y);if(k){if(g(k.length>0),y.type!==l)continue;for(let T of k){let w=s.find(A=>A.key===T);if(g(w),k.length===1&&w.tracks.length===1){let A=a.get(w.tracks[0]);if(g(A!==void 0),A.length===1){let x=s.find(C=>C.key===A[0]);if(x.tracks.length===1){g(x.tracks[0]===y),d.push({tracks:[y,w.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[y],linkedGroup:w}),w.needsEmit=!0}}else y.type==="video"?m.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??se}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(m.length>0)if(new Set(m.map(p)).size>1){let k={key:m.map(T=>T.id).join("-"),name:"video-"+(s.length+1),tracks:m,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[m[0]],linkedGroup:k})}else for(let k of m)d.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)d.push({tracks:[k],linkedGroup:null});let b=y=>{let k=[],T=0,w=0,A=!1,x=null,C=-1/0;for(let P of y)P.isVideoTrack()?(T++,A||=(P.metadata.rotation??0)!==0||!!P.metadata.flip||!!P.metadata.transformationMatrix):P.isAudioTrack()&&w++,k.push(P.source._codec);for(let P of jt(this.format._options.segmentFormat)){let S=P.getSupportedCodecs(),I=P.getSupportedTrackCounts();if(k.some(v=>!S.includes(v))||TI.video.max||wI.audio.max)continue;let E=0;A&&P.supportsVideoTransformationMetadata&&E++,E>C&&(x=P,C=E)}return g(x),x},h=async y=>{if(y.some(x=>this.playlists.some(C=>C.tracks.includes(x))))throw new Error("Internal error: track is already registered in a playlist.");let k=b(y),T=this.playlists.length+1,w=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});Lg(w);let A={id:this.playlists.length+1,path:w,tracks:y,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Le};return this.playlists.push(A),A};for(let y of s)if(y.needsEmit)for(let k=0;kA.tracks[0].id===T.id);w??=await h([T]),this.playlistDeclarations.push({playlist:w,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of d){let k=this.playlists.find(T=>T.tracks[0].id===y.tracks[0].id);k??=await h(y.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:y.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===y.linkedGroup.name):[]})}for(let y of this.output.tracks)y.isVideoTrack()&&y.metadata.decoderConfig?this.getVideoTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig}):y.isAudioTrack()&&y.metadata.decoderConfig&&this.getAudioTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig});e()}async getMimeType(){return nr}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));g(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return g(s.length===1),a={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}getAudioTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return g(s.length===1),a={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(g(!e.done),!this.allTracksAreKnown(e))return;let r=this.trackDatas.filter(s=>e.tracks.includes(s.track));if(e.currentSegmentStartTimestamp===null){r.every(s=>s.closed)&&await this.onPlaylistDone(e);return}let n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let x=n.packets.every(S=>S.timestamps)break;S>0&&I.type==="key"&&(C=I,P=S)}if(P!==null){if(o=P,a){let S=a.packets.findIndex(I=>I.timestamp>=C.timestamp);if(S!==-1)c=S;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let S=Wl(n.packets,E=>E.timestamp),I=n.packets[S];if(g(I),a)if(I.timestampv.timestamp>=s);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}else{let E=a.packets.findIndex(v=>v.timestamp>I.timestamp);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(C=>C.timestampP.timestamp<=s);c=Math.max(C,1)}if(o===0&&c===0){r.every(C=>C.closed)&&await this.onPlaylistDone(e);return}let u=null,l,d;g(this.output._target instanceof pt);let m=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Yo(e)};l=await this.getSegmentPath(x),xf(l),d=we(we(m.rootPath,e.path),l);let C=await this.output._getTarget({path:d,isRoot:!1,mimeType:e.segmentFormat.mimeType}),P=null;if(e.segmentFormat._isFragmentedIsobmff()){P={output:new Br({format:e.segmentFormat,target:C}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},C.on("write",({end:E})=>{P.currentFileSize=Math.max(P.currentFileSize,E)});let S=P.output._muxer;S.minimumFragmentDuration=1/0;let I=S.formatOptions.onMoof;S.formatOptions.onMoof=(E,v,F)=>{P.firstMoofPosition=v,I?.(E,v,F),S.formatOptions.onMoof=I},n&&(P.videoSource=new ui(n.track.source._codec),P.output.addVideoTrack(P.videoSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(P.audioSource=new li(a.track.source._codec),P.output.addAudioTrack(P.audioSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await P.output.start()}else C._start();e.singleFile={target:C,path:l,nextOffset:0,info:x,fragmentedIsobmffOutput:P}}else l=e.singleFile.path,d=we(we(m.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Yo(e)},l=await this.getSegmentPath(u),xf(l),d=we(we(m.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,b=-1/0,h=null,y=null,k=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,y=e.singleFile.fragmentedIsobmffOutput.videoSource,k=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new Br({format:e.segmentFormat,target:new pt(d,async x=>{let C={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:S})=>f=Math.max(f,S)),P}else{let P=await this.output._getTarget(C);return p=P,P.on("write",({end:S})=>f=Math.max(f,S)),P}return this.output._getTarget(C)}),initTarget:async()=>{if(e.initSegment)return new Ni;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let x=e.singleFile.target.slice(e.singleFile.nextOffset);return x.on("write",({end:C})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,C)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=Yo(e),C=await this.getInitPath(x);Wg(C),e.initSegment={path:C,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let P=we(we(m.rootPath,e.path),C),S=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return S.on("write",({end:I})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,I)}),S.on("finalized",()=>{this.format._options.onInit?.(S,x)}),S}}}),n&&(y=new ui(n.track.source._codec),h.addVideoTrack(y,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(k=new li(a.track.source._codec),h.addAudioTrack(k,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await h.start()),n){g(y);let x={decoderConfig:n.info.decoderConfig};for(let C=0;C0&&(g(n),n.packets.splice(0,o)),c>0&&(g(a),a.packets.splice(0,c));let T=1/0;n&&n.packets.length>0&&(T=n.packets[0].timestamp),a&&a.packets.length>0&&(T=Math.min(T,a.packets[0].timestamp));let w=T<1/0?T:b;g(Number.isFinite(w));let A=w-e.currentSegmentStartTimestamp;if(g(A>=0),e.writtenSegments.push({path:l,duration:A,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,A),e.currentSegmentStartTimestamp=w,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let x=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(g(x.info),this.format._options.onSegmentPopped?.(x.path,x.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){g(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let c=0;c=.5*this.globalTargetDuration&&l<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*u/l)),!(l>1.5*this.globalTargetDuration));d++);}if(n===0)for(let c of r){let u=c.duration||1;n=Math.max(n,8*c.byteSize/u)}for(let c of r)a+=8*c.byteSize;let o=a/(s||1);if(r.length===0)for(let c of e.tracks){let u=this.trackDatas.find(d=>d.track===c),l=c.source._nominalBitrate??c.metadata.bitrate??0;if(o+=c.source._nominalBitrate??c.metadata.averageBitrate??0,l===0){let d=new ce("medium");if(c.isVideoTrack()){let m=u?.info.decoderConfig;l=d._toVideoBitrate(c.source._codec,m?.codedWidth??1920,m?.codedHeight??1080)}else c.isAudioTrack()&&(l=d._toAudioBitrate(c.source._codec)??0)}n+=l}e.peakBitrate=n,e.averageBitrate=o}async writePlaylist(e){g(this.output._target instanceof pt);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let m of e.writtenSegments)n||=m.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=we(r.rootPath,e.path),u=`#EXTM3U
+#EXT-X-VERSION:${s}
+`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
+`)+`#EXT-X-TARGETDURATION:${Math.ceil(o)}
+`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
+`:"")+`#EXT-X-INDEPENDENT-SEGMENTS
+`+(a?`#EXT-X-I-FRAMES-ONLY
+`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
+`:"")+`
+`+e.writtenSegments.map(m=>`#EXTINF:${+m.duration.toFixed(12)},
+`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*m.timestamp).toISOString()}
+`:"")+(m.byteOffset!==null?`#EXT-X-BYTERANGE:${m.byteSize}@${m.byteOffset}
+`:"")+`${m.path}
+`).join("")+(e.done?(e.writtenSegments.length>0?`
+`:"")+`#EXT-X-ENDLIST
+`:"");this.format._options.onPlaylist?.(u,Yo(e));let l=await this.output._getTarget({path:c,isRoot:!1,mimeType:nr}),d=new lr(l,!0);d.start(),d.write(Y.encode(u)),await d.flush(),await d.finalize()}async writeMasterPlaylist(){g(this.output._target instanceof pt);let e=this.output._target,r=`#EXTM3U
+`,n=!1,a=null,s=0,o=!1;for(let u of this.playlistDeclarations)if(u.groupId===null){let l=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,d=[];for(let y of u.playlist.tracks){let T=this.trackDatas.find(w=>w.track===y)?.info.decoderConfig.codec??y.source._codec;d.push(Af(T))}let m=0,f=0;if(u.references.length>0){let k=u.references[0].playlist.tracks[0],w=this.trackDatas.find(A=>A.track===k)?.info.decoderConfig.codec??k.source._codec;d.push(Af(w));for(let A of u.references)g(A.playlist.peakBitrate!==null),m=Math.max(m,A.playlist.peakBitrate),f=Math.max(f,A.playlist.averageBitrate??0)}g(u.playlist.peakBitrate!==null);let p=u.playlist.peakBitrate+m,b=(u.playlist.averageBitrate??0)+f;n||(r+=`
+`,n=!0),l?r+="#EXT-X-I-FRAME-STREAM-INF:":r+="#EXT-X-STREAM-INF:",r+=`BANDWIDTH=${Math.ceil(p)}`,b>0&&(r+=`,AVERAGE-BANDWIDTH=${Math.ceil(b)}`),r+=`,CODECS="${d.join(",")}"`;let h=u.playlist.tracks.find(y=>y.isVideoTrack());if(h?.isVideoTrack()){let k=this.trackDatas.find(T=>T.track===h)?.info.decoderConfig;if(k){let T=k.displayAspectWidth??k.codedWidth,w=k.displayAspectHeight??k.codedHeight;T!==void 0&&w!==void 0&&(h.metadata.rotation!==void 0&&h.metadata.rotation%180===90&&([T,w]=[w,T]),r+=`,RESOLUTION=${T}x${w}`)}!l&&h.metadata.frameRate!==void 0&&(r+=`,FRAME-RATE=${+h.metadata.frameRate.toFixed(3)}`)}if(!l){let y=new Map;for(let k of u.references){g(k.groupId!==null);let T=k.playlist.tracks[0].type;y.set(T,k.groupId)}for(let[k,T]of y)r+=`,${k.toUpperCase()}="${T}"`}l?(r+=`,URI="${u.playlist.path}"`,r+=`
+`):(r+=`
+`,r+=`${u.playlist.path}
+`)}else{g(u.playlist.tracks.length===1);let l=u.playlist.tracks[0],d=l.type,m=l.metadata.name??null,f=l.metadata.languageCode,p=l.metadata.disposition;(a===null||u.groupId!==a)&&(s=0,r+=`
+`,o=!1),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${d.toUpperCase()},GROUP-ID="${u.groupId}"`,m!==null&&/[\n\r"]/.test(m)&&(z._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),m=null),m??=`${f??u.groupId}-${s}`,r+=`,NAME="${m}"`,f!==void 0&&(r+=`,LANGUAGE="${f}"`);let b=p?.primary??!1,h=p?.default??!0,y=p?.forced??!1;if(b&&!o&&(r+=",DEFAULT=YES",o=!0),(b||h)&&(r+=",AUTOSELECT=YES"),y&&(r+=",FORCED=YES"),d==="audio"){let T=this.trackDatas.find(w=>w.track===l)?.info.decoderConfig;T&&(r+=`,CHANNELS="${T.numberOfChannels}"`)}u.noUri||(r+=`,URI="${u.playlist.path}"`),r+=`
+`}this.format._options.onMaster?.(r);let c=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{let l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:nr});u=new lr(l,!0),u.start()}u.write(Y.encode(r)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{c()}}async tryWriteMasterPlaylist(){g(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(r=>r.mutex.acquire()))).forEach(r=>r());for(let r of this.trackDatas)r.closed=!0;await Promise.all(this.playlists.map(r=>r.done?Promise.resolve():this.advancePlaylist(r))),this.isLive||await this.writeMasterPlaylist()}},Lg=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},xf=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},Wg=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Yo=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});var Ke=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>le.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>fe.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Ye.includes(t))}_codecUnsupportedHint(t){return""}_isFragmentedIsobmff(){return!1}},On=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!ve(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}_createMuxer(t){return new Wo(t,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},Dn=class extends On{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Rt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}_codecUnsupportedHint(t){return new Rn().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},_n=class extends On{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Rt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}},Rn=class extends On{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...le,...fe]}_codecUnsupportedHint(t){return new Dn().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Ra=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!ve(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Ho(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...le,...Rt,...ae.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Ye]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Li=class extends Ra{constructor(t){super(t)}getSupportedCodecs(){return[...le.filter(t=>["vp8","vp9","av1"].includes(t)),...fe.filter(t=>["opus","vorbis"].includes(t)),...Ye]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new Ra().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},sl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.xingHeader!==void 0&&typeof t.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(t.onXingFrame!==void 0&&typeof t.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Ko(t,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 supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ol=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.large!==void 0&&typeof t.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(t.metadataFormat!==void 0&&!["info","id3"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(t.onHeader!==void 0&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Xo(t,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[...ae.filter(t=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},cl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maximumPageDuration!==void 0&&(!ve(t.maximumPageDuration)||t.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(t.onPage!==void 0&&typeof t.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Qo(t,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...fe.filter(t=>["vorbis","opus"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},ul=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Do(t,this)}get _name(){return"ADTS"}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".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ll=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=t}_createMuxer(t){return new Vo(t,this)}get _name(){return"FLAC"}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".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},dl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onPacket!==void 0&&typeof t.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Go(t,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...le.filter(t=>["avc","hevc"].includes(t)),...fe.filter(t=>["aac","mp3","ac3","eac3","dts"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ml=class extends Ke{constructor(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.segmentFormat instanceof Ke)&&(!Array.isArray(t.segmentFormat)||t.segmentFormat.length===0||!t.segmentFormat.every(e=>e instanceof Ke)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(t.targetDuration!==void 0&&(typeof t.targetDuration!="number"||t.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(t.singleFilePerPlaylist!==void 0&&typeof t.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(t.live!==void 0&&typeof t.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(t.maxLiveSegmentCount!==void 0&&(typeof t.maxLiveSegmentCount!="number"||t.maxLiveSegmentCount<1||Number.isFinite(t.maxLiveSegmentCount)&&!Number.isInteger(t.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(t.getPlaylistPath!==void 0&&typeof t.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(t.getSegmentPath!==void 0&&typeof t.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(t.getInitPath!==void 0&&typeof t.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(t.onMaster!==void 0&&typeof t.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(t.onPlaylist!==void 0&&typeof t.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(t.onSegment!==void 0&&typeof t.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(t.onInit!==void 0&&typeof t.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(t.onSegmentPopped!==void 0&&typeof t.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Zo(t,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return nr}getSupportedCodecs(){return[...new Set(jt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let t=!1,e=!1,r=!1;for(let n of jt(this._options.segmentFormat)){let a=n.getSupportedTrackCounts();t||=a.video.max>0,e||=a.audio.max>0,r||=a.subtitle.max>0}return{video:{min:0,max:t?1/0:0},audio:{min:0,max:e?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return jt(this._options.segmentFormat).some(t=>t.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let t=jt(this._options.segmentFormat);return t.some(e=>e.negativeTimestampSupport==="none")?"none":t.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":t.some(e=>e.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(t){return" Using different segment formats may grant support for this codec."}};var pl=["video","audio","subtitle"],Vn=class i{constructor(t,e,r,n,a){this.id=t,this.output=e,this.type=r,this.source=n,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;let e=jt(this.metadata.group),r=jt(t.metadata.group);for(let n of e)if(this.type!==t.type&&r.some(o=>n===o)||r.some(o=>n._pairedGroups.has(o)))return!0;return!1}},Jo=class extends Vn{constructor(t,e,r,n){super(t,e,"video",r,n)}},ec=class extends Vn{constructor(t,e,r,n){super(t,e,"audio",r,n)}},tc=class extends Vn{constructor(t,e,r,n){super(t,e,"subtitle",r,n)}},ht=class i{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}},fl=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!gr(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&jl(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.bitrate!==void 0&&(!Number.isFinite(i.bitrate)||i.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(i.averageBitrate!==void 0&&(!Number.isFinite(i.averageBitrate)||i.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(i.group!==void 0&&!(i.group instanceof ht)&&(!Array.isArray(i.group)||i.group.some(t=>!(t instanceof ht))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},Br=class extends ct{constructor(e){super();this.state="pending";this.defaultTrackGroup=new ht;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new Le;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ke))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ze||e.target instanceof pt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ze&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ze)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ze&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let r=this._getRootTarget();if(_(r))throw new TypeError(e);return r}_getTargetValidated(e){g(this._target instanceof pt);let r=this._target.getTarget(e),n=a=>{if(!(a instanceof ze))throw new TypeError("getTarget must return a Target.");return a};return _(r)?r.then(n):n(r)}async _getTarget(e){g(this._target instanceof pt);let r=await this._getTargetValidated(e);return this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this.state==="canceled"?await r._close():this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof ze)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof ze)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),n=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:e,isRoot:!0}),this._rootTarget=a,a);return _(r)?this._rootTargetPromise=r.then(n):n(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),n=new lr(r,typeof e=="boolean"?e:e(r));return n.start(),n})()}addVideoTrack(e,r={}){if(!(e instanceof Fr))throw new TypeError("source must be a VideoSource.");if(fl(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&tr({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof X))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new Jo(this.tracks.length+1,this,e,n))}addAudioTrack(e,r={}){if(!(e instanceof Mr))throw new TypeError("source must be an AudioSource.");if(fl(r),r.decoderConfig!==void 0&&Se({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof X))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ec(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,r={}){if(!(e instanceof Bn))throw new TypeError("source must be a SubtitleSource.");fl(r);let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new tc(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Ln(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let r=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((o,c)=>o+(c.type===e.type?1:0),0),a=r[e.type].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${a} ${e.type} track${a===1?"":"s"}.`);let s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let n of pl){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(ao+(c.type===n?1:0),0),s=e[n].min;if(a{this.state="started";let n=this._mutex.acquire();try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await n)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&z._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(z._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",r}finally{await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var rc=i=>{if(!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&&!le.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${le.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=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?.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(i?.allowTransformationMetadata!==void 0&&typeof i.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(i?.allowRotationMetadata!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(i?.crop!==void 0&&ni(i.crop,"options.video."),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.");if(i?.alpha!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(i?.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(i?.processedWidth!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(i?.processedHeight!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(i?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i?.group!==void 0&&!(i.group instanceof ht||Array.isArray(i.group)&&i.group.every(e=>e instanceof ht)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},ic=i=>{if(!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&&!fe.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${fe.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=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.");if(i?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(i?.processedNumberOfChannels!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(i?.processedSampleRate!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(i?.group!==void 0&&!(i.group instanceof ht||Array.isArray(i.group)&&i.group.every(e=>e instanceof ht)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},hl=2,gl=48e3,bl=class i{constructor(t){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._pauseRequested=!1;this._synchronizer=new yl(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.input instanceof Ri))throw new TypeError("options.input must be an Input.");if(!(t.output instanceof Br))throw new TypeError("options.output must be an Output.");if(t.tracks!==void 0&&t.tracks!=="all"&&t.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(t.composable!==void 0&&typeof t.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(t.copy!==void 0&&t.copy!==!1){if(!t.copy||typeof t.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(t.copy.mode!==void 0&&!["forced","preferred"].includes(t.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(t.copy.shiftTolerance!==void 0&&(!ve(t.copy.shiftTolerance)||t.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(t.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(t.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(t.copy.boundaryTolerance!==void 0&&(!ve(t.copy.boundaryTolerance)||t.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let e=t.composable??!1;if(e){if(t.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(t.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(t.output.tracks.length>0||Object.keys(t.output._metadataTags).length>0||t.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(t.video!==void 0&&typeof t.video!="function")if(Array.isArray(t.video))for(let r of t.video)rc(r);else rc(t.video);if(t.audio!==void 0&&typeof t.audio!="function")if(Array.isArray(t.audio))for(let r of t.audio)ic(r);else ic(t.audio);if(t.trim!==void 0&&(!t.trim||typeof t.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(t.trim?.start!==void 0&&!Number.isFinite(t.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(t.trim?.end!==void 0&&!ve(t.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(t.trim?.start!==void 0&&t.trim.end!==void 0&&t.trim.start>=t.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(t.tags!==void 0&&(typeof t.tags!="object"||!t.tags)&&typeof t.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof t.tags=="object"&&Ln(t.tags),t.showWarnings!==void 0&&typeof t.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=t,this._copyMode=t.copy===!1?!1:t.copy?.mode??"preferred",this._copyTimestampShiftTolerance=t.copy===!1?0:t.copy?.shiftTolerance??0,this._copyBoundaryPolicy=t.copy===!1?"expand":t.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=t.copy===!1?1/0:t.copy?.boundaryTolerance??1/0,this._composable=e,this.input=t.input,this.output=t.output}get state(){return this._state}static async init(t){let e=new i(t);return await e._init(),e}async _init(){let t=await this.input.getFormat(),e,r=this._options.tracks;if(r===void 0&&(r=t.name.includes("(HLS)")?"primary":"all"),r==="all")e=await this.input.getTracks();else if(r==="primary"){let u=await this.input.getPrimaryVideoTrack(),l=await this.input.getPrimaryAudioTrack();e=[u,l].filter(d=>d!==null)}else ne(r),g(!1);let n=this.output.format.getSupportedTrackCounts(),a=1,s=1,o=[],c=[];for(let u of e){let l;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let f=await this._options.video(u,a)??{};if(Array.isArray(f))for(let p of f)rc(p);else rc(f);l=Array.isArray(f)?f:[f],a++}else l=Array.isArray(this._options.video)?this._options.video:[this._options.video];else l=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let f=await this._options.audio(u,s)??{};if(Array.isArray(f))for(let p of f)ic(p);else ic(f);l=Array.isArray(f)?f:[f],s++}else l=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else l=[{}];else g(!1);let d=l.filter(f=>f.discard);for(let f of d)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:f});if(l.length===d.length){l.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}let m=l.filter(f=>!f.discard);o.push(u),c.push(m)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;ub+(h.type===l.type?1:0),0)===n[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached",trackOptions:m});continue}let p=this._nextOutputTrackId++;l.isVideoTrack()?await this._processVideoTrack(l,m,p):l.isAudioTrack()?await this._processAudioTrack(l,m,p):g(!1)}}for(let u=0;u0,this._options.showWarnings??!0){let u=[],l=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");l.length>0&&u.push("Some tracks had to be discarded from the conversion:",l),this.isValid||(u.length>0&&u.push(`
+
+`),u.push(this._getInvalidityExplanation().join(""))),u.length>0&&z._warn(...u)}}_getInvalidityExplanation(){let t=[];if(this.discardedTracks.length===0)t.push("Due to missing tracks, this conversion cannot be executed.");else{let e=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(t.push("Due to discarded tracks, this conversion cannot be executed."),e){let r=this.discardedTracks.flatMap(a=>{if(a.reason==="discarded_by_user")return[];let s;return a.track.type==="video"?s=this.output.format.getSupportedVideoCodecs():a.track.type==="audio"?s=this.output.format.getSupportedAudioCodecs():s=this.output.format.getSupportedSubtitleCodecs(),s.filter(o=>!a.trackOptions.codec||o===a.trackOptions.codec)}),n=[...new Set(r)];n.length===1?t.push(`
+Tracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):t.push(`
+Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(a=>`'${a}'`).join(", ")} with the provided parameters.`),n.includes("mp3")&&t.push(`
+The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes("aac")&&t.push(`
+The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes("ac3")||n.includes("eac3"))&&t.push(`
+The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&t.push(`
+The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else t.push(`
+Check the discardedTracks field for more info.`)}return t}async execute(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.until!==void 0&&(typeof t.until!="number"||Number.isNaN(t.until)))throw new TypeError("options.until, when provided, must be a number.");if(t.pauseSignal!==void 0&&!(t.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
+`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new Fa;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=t.until??1/0,this._pauseRequested=t.pauseSignal?.aborted??!1;let e=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};t.pauseSignal?.addEventListener("abort",e);for(let n of this._trackPumps)n.done||(n.resolvers=J());if(this._executed)for(let n of this._trackPumps)n.wake?.();else{this._executed=!0;for(let n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){let a=[...new Set(this.utilizedTracks)].map(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),s=Math.max(0,...await Promise.all(a));this._computeProgress=!0,this._totalDuration=Math.min(s-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let n of this._trackPumps)n.start()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this._state!=="canceled"&&this.cancel(),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new Fa;let r=this._trackPumps.every(n=>n.done);if(this._state=r?"done":"idle",r&&(this._composable||await this.output.finalize(),this._computeProgress)){let n=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,n)}}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){z._warn("Conversion already canceled.");return}this._state="canceled";for(let t of this._trackPumps)t.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:u}=Ua(s,o,e.rotate??0,e.flip??!1),l=c,d=u,m=e.rotate||e.flip?null:await t.getTransformationMatrix(),f=this.output.format.supportsVideoTransformationMetadata&&(e.allowTransformationMetadata??e.allowRotationMetadata??!0),p=await t.getSquarePixelWidth(),b=await t.getSquarePixelHeight(),[h,y]=c%180===0?[p,b]:[b,p],k=e.crop;k&&(k=wn(k,h,y));let[T,w]=k?[k.width,k.height]:[h,y],A=T,x=w,C=A/x;e.width!==void 0&&e.height===void 0?(A=Si(e.width),x=Si(Math.round(A/C))):e.width===void 0&&e.height!==void 0?(x=Si(e.height),A=Si(Math.round(x*C))):e.width!==void 0&&e.height!==void 0&&(A=Si(e.width),x=Si(e.height));let P=this.output.format.getSupportedVideoCodecs(),S=e.alpha??"discard",I=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!P.includes(n)||e.codec&&e.codec!==n||A!==T||x!==w||c!==0&&!f||u&&!f||!!k,E=null;if(!I){let Qe=new ft(t),Fe=await Qe.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Qe.getFirstKeyPacket({verifyKeyPackets:!0});if(Fe&&Fe.timestampthis._copyBoundaryTolerance)I=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&Ne=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+Me):I=!0}}else if(this._timestampOffsetAdjusted)Ne+this._timestampOffset===0||(I=!0);else{let Me=ee(this._startTimestamp-Ne,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);Ne+Me===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+Me,this._timestampOffsetAdjusted=!0):I=!0}}}if(I&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(I){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(P=P.filter(me=>me===e.codec));let Fe=ai(e.quality,e.bitrate)??new ce("high"),Ne=await Pu(P,{width:e.process&&e.processedWidth?e.processedWidth:A,height:e.process&&e.processedHeight?e.processedHeight:x,quality:Fe});if(!Ne){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let re={codec:Ne,quality:Fe,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:S,hardwareAcceleration:e.hardwareAcceleration,transform:{}};g(re.transform);let Me=A!==T||x!==w||c!==0&&(!f||e.process!==void 0)||u&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||b!==await t.getCodedHeight();if(!Me){var pe=[];try{let me=new Br({format:new Dn,target:new Ni});let Oe=new Mn(re);me.addVideoTrack(Oe);await me.start();let di=new Bi(t);let Ge=st(pe,await di.getSample(await t.getFirstTimestamp()));if(Ge)try{await Oe.add(Ge),Ge.close(),await me.finalize()}catch(dr){z._warn("An error occurred when probing encoder support. Falling back to rerender path.",dr),me.cancel(),Me=!0,re.transform.force=!0}else await me.cancel()}catch(Ie){var Nt=Ie,gt=!0}finally{ot(pe,Nt,gt)}}e.frameRate&&(re.transform.frameRate=e.frameRate),e.process&&(re.transform.process=e.process),Me&&(l=0,d=!1,m=null,re.transform.width=A,re.transform.height=x,re.transform.fit=e.fit??"fill",re.transform.rotate=e.rotate,re.transform.flip=e.flip,re.transform.crop=k,re.transform.alpha=S);let Be=null;re.onEncodedSample=me=>{Be=me.timestamp};let Ee=new Mn(re);a=Ee,this._registerTrackPump(async me=>{let Oe=new Bi(t);for await(var di of Oe.samples(this._startTimestamp,this._endTimestamp)){var Ge=[];try{let bt=st(Ge,di);if(this._state==="canceled")break;let mi=Math.max(this._startTimestamp,bt.timestamp),kl=Math.min(this._endTimestamp,bt.timestamp+bt.duration);mi>=kl||(bt.setTimestamp(mi+this._timestampOffset),bt.setDuration(kl-mi),this._reportProgress(r,bt.timestamp+bt.duration),await Ee.add(bt),bt.close(),Be!==null&&(this._synchronizer.shouldWait(r,Be)&&await this._synchronizer.wait(Be),await this._checkpoint(me,Be)))}catch(dr){var Hi=dr,nc=!0}finally{ot(Ge,Hi,nc)}}Ee.close(),this._synchronizer.closeTrack(r)})}else{let Qe=new ui(n);a=Qe,this._registerTrackPump(async Fe=>{let Ne=new ft(t),Me={decoderConfig:await t.getDecoderConfig()??void 0},Be=null;if(E)for await(let Ee of Ne.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Ee.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let dr=Ee,Hi=!1,nc=6;for(let bt=0;btthis._copyBoundaryTolerance)d=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&w.timestamp=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+C):d=!0}}else if(this._timestampOffsetAdjusted)w.timestamp+this._timestampOffset===0||(d=!0);else{let C=ee(this._startTimestamp-w.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);w.timestamp+C===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+C,this._timestampOffsetAdjusted=!0):d=!0}}if(d&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(d){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let w=null;e.codec&&(l=l.filter(I=>I===e.codec));let A=ai(e.quality,e.bitrate)??new ce("high"),x=await wa(l,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:u,quality:A});if(!x.some(I=>Rt.includes(I))&&l.some(I=>Rt.includes(I))&&(c!==hl||u!==gl)){let E=(await wa(l,{numberOfChannels:hl,sampleRate:gl,quality:A})).find(v=>Rt.includes(v));E&&(w=E,c=hl,u=gl)}else w=x[0]??null;if(w===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let C={codec:w,quality:A,transform:{sampleFormat:e.sampleFormat,process:e.process}};g(C.transform),c!==s&&(C.transform.numberOfChannels=c),u!==o&&(C.transform.sampleRate=u);let P=null;C.onEncodedSample=I=>{P=I.timestamp};let S=new _a(C);a=S,this._registerTrackPump(async I=>{let E=null,v=new xn(t);for await(var Nt of v.samples(this._startTimestamp,this._endTimestamp)){var gt=[];try{let re=st(gt,Nt);var K=[];try{if(this._state==="canceled")break;let Me=0;let Be=re.numberOfFrames;re.timestampthis._endTimestamp&&(Be=Math.round((this._endTimestamp-re.timestamp)*re.sampleRate));if(Me>=Be){re.close();continue}let Ee;if(Me>0||Be0&&!this.output.format.supportsTimestampedMediaData);if(E){var F=[];try{let Oe=me.timestamp;let di=Math.round(Oe*o);let Ge=sr(re.format);let dr=new Uint8Array(Ge*di*s);(re.format==="u8"||re.format==="u8-planar")&&dr.fill(2**7);let Hi=st(F,new Ce({data:dr,format:re.format,numberOfChannels:s,sampleRate:o,timestamp:0}));await this._registerAudioSample(I,Hi,S,r,()=>P);E=!1}catch(O){var D=O,U=!0}finally{ot(F,D,U)}}await this._registerAudioSample(I,me,S,r,()=>P)}catch(ie){var pe=ie,Ie=!0}finally{ot(K,pe,Ie)}}catch(Qe){var Fe=Qe,Ne=!0}finally{ot(gt,Fe,Ne)}}S.close(),this._synchronizer.closeTrack(r)})}else{let T=new li(n);a=T,this._registerTrackPump(async w=>{let A=new ft(t),C={decoderConfig:await t.getDecoderConfig()??void 0},P=null;if(m)for await(let S of A.packets(m)){if(this._state==="canceled"||S.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&S.timestamp+S.duration>this._endTimestamp)break;let I=S.timestamp+this._timestampOffset;if(P!==null&&I