@mediafox/core 1.2.7 → 1.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compositor.d.ts","sourceRoot":"","sources":["../../src/compositor/compositor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG5C,OAAO,KAAK,EAEV,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAElB,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,cAAc,EACf,MAAM,SAAS,CAAC;AAkBjB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,GAAG,CAA6E;IACxF,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,YAAY,CAAuC;IAC3D,OAAO,CAAC,YAAY,CAAuC;IAC3D,OAAO,CAAC,aAAa,CAAuC;IAC5D,OAAO,CAAC,kBAAkB,CAAuC;IACjE,OAAO,CAAC,OAAO,CAAmC;IAClD,OAAO,CAAC,KAAK,CAAkB;IAC/B,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,QAAQ,CAAS;IAGzB,OAAO,CAAC,aAAa,CAA4E;IACjG,OAAO,CAAC,kBAAkB,CAAK;IAC/B,OAAO,CAAC,oBAAoB,CAAO;IACnC,OAAO,CAAC,aAAa,CAAS;IAG9B,OAAO,CAAC,oBAAoB,CAAqB;IACjD,OAAO,CAAC,YAAY,CAIlB;IACF,OAAO,CAAC,sBAAsB,CAAqB;IAEnD;;;OAGG;gBACS,OAAO,EAAE,iBAAiB;
|
|
1
|
+
{"version":3,"file":"compositor.d.ts","sourceRoot":"","sources":["../../src/compositor/compositor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG5C,OAAO,KAAK,EAEV,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAElB,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,cAAc,EACf,MAAM,SAAS,CAAC;AAkBjB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,MAAM,CAAsC;IACpD,OAAO,CAAC,GAAG,CAA6E;IACxF,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,YAAY,CAAuC;IAC3D,OAAO,CAAC,YAAY,CAAuC;IAC3D,OAAO,CAAC,aAAa,CAAuC;IAC5D,OAAO,CAAC,kBAAkB,CAAuC;IACjE,OAAO,CAAC,OAAO,CAAmC;IAClD,OAAO,CAAC,KAAK,CAAkB;IAC/B,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAA+B;IACrD,OAAO,CAAC,QAAQ,CAAS;IAGzB,OAAO,CAAC,aAAa,CAA4E;IACjG,OAAO,CAAC,kBAAkB,CAAK;IAC/B,OAAO,CAAC,oBAAoB,CAAO;IACnC,OAAO,CAAC,aAAa,CAAS;IAG9B,OAAO,CAAC,oBAAoB,CAAqB;IACjD,OAAO,CAAC,YAAY,CAIlB;IACF,OAAO,CAAC,sBAAsB,CAAqB;IAEnD;;;OAGG;gBACS,OAAO,EAAE,iBAAiB;IAyEtC;;;;;OAKG;IACG,UAAU,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAqBnG;;;;OAIG;IACG,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAcxE;;;;;OAKG;IACG,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAqBlG;;;;OAIG;IACH,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAwBjC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAW3B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IA2C1B;;;;OAIG;IACH,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS;IAOnD;;;OAGG;IACH,aAAa,IAAI,gBAAgB,EAAE;IASnC;;;;;OAKG;IACG,MAAM,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;IAqEvD,OAAO,CAAC,WAAW;IA4DnB,OAAO,CAAC,kBAAkB;YAyBZ,eAAe;IAgB7B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,oBAAoB;IA4B5B;;OAEG;IACH,KAAK,IAAI,IAAI;IAYb;;;;OAIG;IACH,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI;IAQtC;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB3B;;OAEG;IACH,KAAK,IAAI,IAAI;IAYb;;;OAGG;IACG,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAwBvC,OAAO,CAAC,eAAe;IAgEvB,OAAO,CAAC,cAAc;IAStB;;;;;OAKG;IACG,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAiCvF,wCAAwC;IACxC,IAAI,WAAW,IAAI,MAAM,CAExB;IAED,4DAA4D;IAC5D,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,mDAAmD;IACnD,IAAI,OAAO,IAAI,OAAO,CAErB;IAED,kDAAkD;IAClD,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,mDAAmD;IACnD,IAAI,OAAO,IAAI,OAAO,CAErB;IAED;;;OAGG;IACH,QAAQ,IAAI,MAAM;IAIlB;;;OAGG;IACH,SAAS,IAAI,MAAM;IAInB;;;;OAIG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAe3C;;;;;OAKG;IACH,EAAE,CAAC,CAAC,SAAS,MAAM,kBAAkB,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI;IAIlG;;;;;OAKG;IACH,IAAI,CAAC,CAAC,SAAS,MAAM,kBAAkB,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI;IAIpG;;;;OAIG;IACH,GAAG,CAAC,CAAC,SAAS,MAAM,kBAAkB,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,IAAI;IAM9F;;;OAGG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAI9B;;;OAGG;IACH,eAAe,IAAI,YAAY;IAS/B,OAAO,CAAC,aAAa;IAMrB;;;OAGG;IACH,OAAO,IAAI,IAAI;CAoBhB"}
|
|
@@ -1 +1,227 @@
|
|
|
1
|
-
class O{events=new Map;maxListeners;captureRejections;emitCache=[];constructor(o={}){this.maxListeners=o.maxListeners??10,this.captureRejections=o.captureRejections??!1}on(o,C){if(!this.events.has(o))this.events.set(o,new Set);let W=this.events.get(o);if(!W)return()=>{};if(W.size>=this.maxListeners)console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${W.size} ${String(o)} listeners added. Use emitter.setMaxListeners() to increase limit`);let w=C;return W.add(w),()=>{W.delete(w)}}once(o,C){let W=(w)=>{this.off(o,W),C(w)};return this.on(o,W)}off(o,C){let W=this.events.get(o);if(!W)return;if(C){let w=C;W.delete(w)}else W.clear()}emit(o,C){let W=this.events.get(o);if(!W||W.size===0)return;let w=this.emitCache;w.length=0;for(let k of W)w.push(k);for(let k=0;k<w.length;k++){let P=w[k];try{let r=P(C);if(this.captureRejections&&N(r))this.handlePromiseRejection(r)}catch(r){if(this.captureRejections&&this.events.has("error"))this.emit("error",r);else throw r}}}handlePromiseRejection(o){o.catch((C)=>{if(this.events.has("error"))this.emit("error",C);else throw C})}removeAllListeners(o){if(o)this.events.delete(o);else this.events.clear()}setMaxListeners(o){this.maxListeners=o}getMaxListeners(){return this.maxListeners}listeners(o){let C=this.events.get(o);return C?Array.from(C):[]}listenerCount(o){let C=this.events.get(o);return C?C.size:0}eventNames(){return Array.from(this.events.keys())}}function N(o){if(!o||typeof o!=="object"&&typeof o!=="function")return!1;let C=o;return typeof C.then==="function"&&typeof C.catch==="function"}class J{audioContext;masterGain;activeSources=new Map;activeSourceIdsScratch=new Set;playing=!1;disposed=!1;playbackId=0;startContextTime=0;startMediaTime=0;pauseTime=0;masterVolume=1;masterMuted=!1;constructor(o={}){if(o.audioContext)this.audioContext=o.audioContext;else{let C=globalThis,W=C.AudioContext||C.webkitAudioContext;if(!W)throw Error("AudioContext is not supported in this environment");this.audioContext=new W}this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination)}registerSource(o,C){if(this.disposed)return;let W=this.audioContext.createGain(),w=this.audioContext.createStereoPanner();W.connect(w),w.connect(this.masterGain),this.activeSources.set(o.id,{sourceId:o.id,bufferSink:C,iterator:null,gainNode:W,panNode:w,queuedNodes:new Set,volume:1,pan:0,muted:!1,startSourceTime:0,currentSourceTime:0,iteratorStartTime:0,lastScheduledTime:0})}unregisterSource(o){let C=this.activeSources.get(o);if(!C)return;this.stopSourceAudio(C),C.gainNode.disconnect(),C.panNode.disconnect(),this.activeSources.delete(o)}hasSource(o){return this.activeSources.has(o)}processAudioLayers(o,C){if(this.disposed||!this.playing)return;let W=this.activeSourceIdsScratch;W.clear();for(let w of o){let k=w.source.id;W.add(k);let P=this.activeSources.get(k);if(!P)continue;let r=w.volume??1,p=w.pan??0,n=w.muted??!1,t=w.sourceTime??C;if(P.volume!==r||P.muted!==n)P.volume=r,P.muted=n,P.gainNode.gain.value=n?0:r*r;if(P.pan!==p)P.pan=p,P.panNode.pan.value=Math.max(-1,Math.min(1,p));if(Math.abs(t-P.currentSourceTime)>0.5&&P.iterator!==null)this.restartSourceIterator(P,t);P.currentSourceTime=t}for(let[w,k]of this.activeSources)if(!W.has(w)&&k.iterator!==null)this.stopSourceAudio(k)}async play(o=this.pauseTime){if(this.playing||this.disposed)return;if(this.audioContext.state==="suspended")await this.audioContext.resume();this.playbackId++,this.playing=!0,this.startContextTime=this.audioContext.currentTime,this.startMediaTime=o,this.pauseTime=o}startSourcePlayback(o,C){let W=this.activeSources.get(o);if(!W||W.iterator!==null)return;this.restartSourceIterator(W,C)}restartSourceIterator(o,C){this.stopSourceAudio(o),o.startSourceTime=C,o.currentSourceTime=C,o.iteratorStartTime=this.audioContext.currentTime,o.iterator=o.bufferSink.buffers(C),o.lastScheduledTime=C,this.scheduleSourceBuffers(o,this.playbackId)}async scheduleSourceBuffers(o,C){let W=o.iterator;if(!W)return;try{for await(let{buffer:w,timestamp:k}of W){if(C!==this.playbackId||this.disposed||!this.playing)break;let P=this.audioContext.createBufferSource();P.buffer=w,P.connect(o.gainNode);let r=k-o.startSourceTime,p=o.iteratorStartTime+r;if(p>=this.audioContext.currentTime)P.start(p);else{let E=this.audioContext.currentTime-p;if(E<w.duration)P.start(this.audioContext.currentTime,E);else continue}o.queuedNodes.add(P),P.onended=()=>{o.queuedNodes.delete(P)},o.lastScheduledTime=k;let n=this.audioContext.currentTime-o.iteratorStartTime;if(k-o.startSourceTime-n>1)await this.waitForCatchup(o,k)}}catch{}}async waitForCatchup(o,C){return new Promise((W)=>{let w=setInterval(()=>{if(!this.playing||this.disposed){clearInterval(w),W();return}let k=this.audioContext.currentTime-o.iteratorStartTime;if(C-o.startSourceTime-k<1)clearInterval(w),W()},100)})}pause(){if(!this.playing)return;this.pauseTime=this.getCurrentTime(),this.playing=!1;for(let o of this.activeSources.values())this.stopSourceAudio(o)}stop(){this.pause(),this.pauseTime=0,this.startContextTime=0,this.startMediaTime=0}async seek(o){let C=this.playing;if(this.pause(),this.pauseTime=o,this.startMediaTime=o,C)await this.play(o)}stopSourceAudio(o){for(let C of o.queuedNodes)try{C.stop()}catch{}if(o.queuedNodes.clear(),o.iterator)o.iterator.return(),o.iterator=null}getCurrentTime(){if(this.playing)return this.startMediaTime+(this.audioContext.currentTime-this.startContextTime);return this.pauseTime}setMasterVolume(o){this.masterVolume=Math.max(0,Math.min(1,o)),this.updateMasterGain()}setMasterMuted(o){this.masterMuted=o,this.updateMasterGain()}updateMasterGain(){let o=this.masterMuted?0:this.masterVolume;this.masterGain.gain.value=o*o}getAudioContext(){return this.audioContext}isPlaying(){return this.playing}dispose(){if(this.disposed)return;this.disposed=!0,this.playbackId++,this.stop();for(let o of this.activeSources.values())this.stopSourceAudio(o),o.gainNode.disconnect(),o.panNode.disconnect();if(this.activeSources.clear(),this.masterGain.disconnect(),this.audioContext.state!=="closed")this.audioContext.close()}}import{ALL_FORMATS as X,AudioBufferSink as Z,BlobSource as Y,BufferSource as j,CanvasSink as L,FilePathSource as A,Input as I,ReadableStreamSource as a,UrlSource as S}from"mediabunny";class b{cache=new Map;maxSize;constructor(o){this.maxSize=o}get(o){let C=this.cache.get(o);if(C!==void 0)this.cache.delete(o),this.cache.set(o,C);return C}set(o,C){if(this.cache.has(o))this.cache.delete(o);else if(this.cache.size>=this.maxSize){let W=this.cache.keys().next().value;if(W!==void 0)this.cache.delete(W)}this.cache.set(o,C)}clear(){this.cache.clear()}get size(){return this.cache.size}}class B{id;type="video";duration;width;height;data;disposed=!1;constructor(o,C,W,w,k){this.id=o,this.data=C,this.duration=W,this.width=w,this.height=k}async getFrameAt(o){if(this.disposed)return null;let C=this.data.frameIntervalMs,W=Math.floor(o*1000/C)*C,w=this.data.frameCache.get(W);if(w)return w.canvas;try{let k=await this.data.canvasSink.getCanvas(o);if(!k)return null;return this.data.frameCache.set(W,k),k.canvas}catch{return null}}getAudioBufferSink(){return this.data.audioBufferSink}hasAudio(){return this.data.audioBufferSink!==null}clearCache(){this.data.frameCache.clear()}dispose(){if(this.disposed)return;this.disposed=!0,this.data.frameCache.clear(),this.data.input.dispose()}}class K{id;type="image";duration=1/0;width;height;data;disposed=!1;constructor(o,C){this.id=o,this.data=C,this.width=C.image.width,this.height=C.image.height}async getFrameAt(o){if(this.disposed)return null;return this.data.image}dispose(){if(this.disposed)return;if(this.disposed=!0,"close"in this.data.image)this.data.image.close()}}class V{id;type="audio";duration;width=0;height=0;data;disposed=!1;constructor(o,C,W){this.id=o,this.data=C,this.duration=W}async getFrameAt(o){return null}getAudioBufferSink(){return this.data.audioBufferSink}dispose(){if(this.disposed)return;this.disposed=!0,this.data.input.dispose()}}class Q{sources=new Map;audioContext=null;nextId=0;constructor(o){this.audioContext=o??null}generateId(){return`source_${this.nextId++}`}async loadVideo(o,C={}){let W=C.id??this.generateId(),w=this.createInput(o),k=await w.getVideoTracks();if(k.length===0)throw w.dispose(),Error("Source has no video track");let P=k[0];if(!await P.canDecode())throw w.dispose(),Error(`Cannot decode video track with codec: ${P.codec}`);let p=new L(P,{poolSize:4}),n=await P.computeDuration(),t=30;try{let F=await P.computePacketStats(100);if(F.averagePacketRate>0)t=F.averagePacketRate}catch{}let E=1000/t,h=P.displayWidth*P.displayHeight,q=h>2073600?15:h>921600?30:60,g=null,M=null;try{let F=await w.getAudioTracks();if(F.length>0){if(g=F[0],await g.canDecode())M=new Z(g)}}catch{}let $=new B(W,{input:w,videoTrack:P,canvasSink:p,frameCache:new b(q),frameIntervalMs:E,audioTrack:g,audioBufferSink:M},n,P.displayWidth,P.displayHeight);return this.sources.set(W,$),$}async loadImage(o){let C=this.generateId(),W;if(typeof o!=="string")W=await createImageBitmap(o);else if(typeof Image>"u"){let k=await fetch(o);if(!k.ok)throw Error(`Failed to load image: ${o}`);let P=await k.blob();W=await createImageBitmap(P)}else W=await new Promise((k,P)=>{let r=new Image;r.onload=()=>k(r),r.onerror=()=>P(Error(`Failed to load image: ${o}`)),r.crossOrigin="anonymous",r.src=o});let w=new K(C,{image:W});return this.sources.set(C,w),w}async loadAudio(o,C={}){let W=C.id??this.generateId(),w=this.createInput(o),k=await w.getAudioTracks();if(k.length===0)throw w.dispose(),Error("Source has no audio track");let P=k[0];if(!await P.canDecode())throw w.dispose(),Error(`Cannot decode audio track with codec: ${P.codec}`);let p=await P.computeDuration(),n=new Z(P),t=new V(W,{input:w,audioTrack:P,audioBufferSink:n},p);return this.sources.set(W,t),t}createInput(o){let C;if(o instanceof File||o instanceof Blob)C=new Y(o);else if(o instanceof ArrayBuffer||o instanceof Uint8Array)C=new j(o);else if(typeof o==="string"||o instanceof URL){let W=o instanceof URL?o.href:o;if(typeof window>"u"&&!W.startsWith("http"))C=new A(W);else C=new S(W)}else if(typeof ReadableStream<"u"&&o instanceof ReadableStream)C=new a(o);else throw Error("Unsupported source type");return new I({source:C,formats:X})}getSource(o){return this.sources.get(o)}hasSource(o){return this.sources.has(o)}unloadSource(o){let C=this.sources.get(o);if(C)return C.dispose(),this.sources.delete(o),!0;return!1}getAllSources(){return Array.from(this.sources.values())}clear(){for(let o of this.sources.values())o.dispose();this.sources.clear()}dispose(){if(this.clear(),this.audioContext&&this.audioContext.state!=="closed")this.audioContext.close();this.audioContext=null}}class _{worker;nextId=1;pending=new Map;ready;constructor(o){let C=typeof o.worker==="boolean"?{}:o.worker??{},W=C.type??"module",w=C.url??new URL("./compositor-worker.js",import.meta.url);this.worker=new Worker(w,{type:W}),this.worker.onmessage=(r)=>{let{id:p,ok:n,result:t,error:E}=r.data,h=this.pending.get(p);if(!h)return;if(this.pending.delete(p),n)h.resolve(t);else h.reject(Error(E??"Worker error"))},this.worker.onerror=(r)=>{let p=r.error instanceof Error?r.error:Error("Worker error");for(let n of this.pending.values())n.reject(p);this.pending.clear()};let k=o.canvas.transferControlToOffscreen(),P={canvas:k,width:o.width,height:o.height,backgroundColor:o.backgroundColor};this.ready=this.call("init",P,[k])}postMessage(o,C,W){let w=this.nextId++;return this.worker.postMessage({id:w,kind:o,payload:C},W??[]),w}call(o,C,W){let w=this.postMessage(o,C,W);return new Promise((k,P)=>{this.pending.set(w,{resolve:k,reject:P})})}async loadSource(o,C){await this.ready;let W={source:o,options:C};return this.call("loadSource",W)}async loadImage(o){await this.ready;let C={source:o};return this.call("loadImage",C)}async loadAudio(o,C){await this.ready;let W={source:o,options:C};return this.call("loadAudio",W)}async unloadSource(o){await this.ready;let C={id:o};return this.call("unloadSource",C)}async render(o){await this.ready;let C={frame:o};return this.call("render",C)}async clear(){return await this.ready,this.call("clear")}async resize(o,C){await this.ready;let W={width:o,height:C};return this.call("resize",W)}async exportFrame(o,C){await this.ready;let W={frame:o,options:C};return this.call("exportFrame",W)}dispose(){try{this.worker.postMessage({id:this.nextId++,kind:"dispose"})}catch{}this.worker.terminate(),this.pending.clear()}}class D{canvas;ctx=null;width;height;backgroundColor;sourcePool;audioManager=null;workerClient=null;workerSources=new Map;workerAudioSources=new Map;emitter;state;animationFrameId=null;lastFrameTime=0;lastRenderTime=0;previewOptions=null;disposed=!1;renderBuffers={visibleLayers:[],framePromises:[],frameImages:[]};lastTimeUpdateEmit=0;timeUpdateThrottleMs=100;renderPending=!1;activeAudioSourceIds=new Set;audioScratch={nextActiveSourceIds:new Set,newSourceIds:[],newSourceTimes:[]};registeredAudioSources=new Set;constructor(o){this.canvas=o.canvas,this.width=o.width??(this.canvas.width||1920),this.height=o.height??(this.canvas.height||1080),this.backgroundColor=o.backgroundColor??"#000000",this.emitter=new O({maxListeners:50}),this.state={playing:!1,currentTime:0,duration:0,seeking:!1},this.canvas.width=this.width,this.canvas.height=this.height;let C=typeof o.worker==="boolean"?o.worker:o.worker?o.worker.enabled??!0:!1,W=C&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof this.canvas.transferControlToOffscreen==="function"&&!(this.canvas instanceof OffscreenCanvas);if(C&&!W)throw Error("Worker compositor requires HTMLCanvasElement, OffscreenCanvas, and Worker support");if(this.sourcePool=new Q,W)this.workerClient=new _({canvas:this.canvas,width:this.width,height:this.height,backgroundColor:this.backgroundColor,worker:o.worker??!0});if(o.enableAudio!==!1)this.audioManager=new J;if(!this.workerClient){if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)throw Error("Failed to get 2D context for compositor canvas");this.clear()}}async loadSource(o,C){if(this.checkDisposed(),this.workerClient){let w=await this.workerClient.loadSource(o,C),k=this.createWorkerSource(w);if(this.audioManager&&w.hasAudio)await this.loadWorkerAudio(o,k.id);return this.emitter.emit("sourceloaded",{id:k.id,source:k}),k}let W=await this.sourcePool.loadVideo(o,C);return this.registerSourceAudio(W),this.emitter.emit("sourceloaded",{id:W.id,source:W}),W}async loadImage(o){if(this.checkDisposed(),this.workerClient){let W=await this.workerClient.loadImage(o),w=this.createWorkerSource(W);return this.emitter.emit("sourceloaded",{id:w.id,source:w}),w}let C=await this.sourcePool.loadImage(o);return this.emitter.emit("sourceloaded",{id:C.id,source:C}),C}async loadAudio(o,C){if(this.checkDisposed(),this.workerClient){let w=await this.workerClient.loadAudio(o,C),k=this.createWorkerSource(w);if(this.audioManager)await this.loadWorkerAudio(o,k.id);return this.emitter.emit("sourceloaded",{id:k.id,source:k}),k}let W=await this.sourcePool.loadAudio(o,C);return this.registerSourceAudio(W),this.emitter.emit("sourceloaded",{id:W.id,source:W}),W}unloadSource(o){if(this.workerClient){if(!this.workerSources.get(o))return!1;return this.workerClient.unloadSource(o),this.workerSources.delete(o),this.unloadWorkerAudio(o),this.emitter.emit("sourceunloaded",{id:o}),!0}if(this.registeredAudioSources.has(o))this.audioManager?.unregisterSource(o),this.registeredAudioSources.delete(o);let C=this.sourcePool.unloadSource(o);if(C)this.emitter.emit("sourceunloaded",{id:o});return C}registerSourceAudio(o){if(!this.audioManager)return;if(this.registeredAudioSources.has(o.id))return;let C=o.getAudioBufferSink?.();if(C)this.audioManager.registerSource(o,C),this.registeredAudioSources.add(o.id)}processAudioLayers(o,C){if(!this.audioManager)return;let W=this.audioScratch.newSourceIds,w=this.audioScratch.newSourceTimes,k=this.audioScratch.nextActiveSourceIds,P=this.activeAudioSourceIds;W.length=0,w.length=0,k.clear();for(let r=0;r<o.length;r++){let p=o[r];if(p.muted)continue;let n=p.source.id;if(!this.audioManager.hasSource(n))continue;if(k.add(n),!P.has(n))W.push(n),w.push(p.sourceTime??C)}if(P.size>0)P.clear();for(let r of k)P.add(r);this.audioManager.processAudioLayers(o,C);for(let r=0;r<W.length;r++)this.audioManager.startSourcePlayback(W[r],w[r])}getSource(o){if(this.workerClient)return this.workerSources.get(o);return this.sourcePool.getSource(o)}getAllSources(){if(this.workerClient)return Array.from(this.workerSources.values());return this.sourcePool.getAllSources()}async render(o){if(this.checkDisposed(),this.workerClient){let t=this.serializeWorkerFrame(o);return this.workerClient.render(t)}let C=this.ctx;if(!C)return!1;let{visibleLayers:W,framePromises:w,frameImages:k}=this.renderBuffers;W.length=0,w.length=0,k.length=0;let P=!1,r=-1/0,p=o.layers;for(let t=0;t<p.length;t++){let E=p[t];if(E.visible===!1)continue;let h=E.zIndex??0;if(h<r)P=!0;r=h,W.push(E)}if(W.length===0)return C.fillStyle=this.backgroundColor,C.fillRect(0,0,this.width,this.height),!0;if(P)W.sort((t,E)=>(t.zIndex??0)-(E.zIndex??0));for(let t=0;t<W.length;t++){let E=W[t],h=E.sourceTime??o.time;w[t]=E.source.getFrameAt(h)}let n=await Promise.all(w);for(let t=0;t<n.length;t++)k[t]=n[t]??null;C.fillStyle=this.backgroundColor,C.fillRect(0,0,this.width,this.height);for(let t=0;t<W.length;t++){let E=k[t];if(E)this.renderLayer(E,W[t])}return!0}renderLayer(o,C){let W=this.ctx;if(!W)return;let w=C.transform,k=C.source.width??this.width,P=C.source.height??this.height;if(!w){W.drawImage(o,0,0,k,P);return}let r=w.width??k,p=w.height??P,n=w.x??0,t=w.y??0,E=w.rotation??0,h=w.scaleX??1,q=w.scaleY??1,g=w.opacity??1,M=g!==1;if(!M&&!(E!==0||h!==1||q!==1)){W.drawImage(o,n,t,r,p);return}let F=w.anchorX??0.5,l=w.anchorY??0.5;if(W.save(),M)W.globalAlpha=g;if(W.translate(n+r*F,t+p*l),E!==0)W.rotate(E*Math.PI/180);if(h!==1||q!==1)W.scale(h,q);W.drawImage(o,-r*F,-p*l,r,p),W.restore()}createWorkerSource(o){let C={id:o.id,type:o.type,duration:o.duration,width:o.width,height:o.height,async getFrameAt(){throw Error("getFrameAt is not available when worker rendering is enabled")},getAudioBufferSink(){return null},hasAudio(){return o.hasAudio??!1},dispose(){}};return this.workerSources.set(C.id,C),C}async loadWorkerAudio(o,C){if(!this.audioManager)return;if(this.workerAudioSources.has(C))this.unloadWorkerAudio(C);try{let W=await this.sourcePool.loadAudio(o,{id:C});this.workerAudioSources.set(C,W),this.registerSourceAudio(W)}catch{}}unloadWorkerAudio(o){if(!this.audioManager)return;if(this.workerAudioSources.has(o))this.audioManager.unregisterSource(o),this.registeredAudioSources.delete(o),this.sourcePool.unloadSource(o),this.workerAudioSources.delete(o)}serializeWorkerFrame(o){if(!this.workerClient)throw Error("Worker compositor not initialized");let C=o.layers,W=Array(C.length);for(let w=0;w<C.length;w++){let k=C[w],P=k.source.id;if(!this.workerSources.has(P))throw Error(`Layer source ${P} is not managed by this compositor`);W[w]={sourceId:P,sourceTime:k.sourceTime,transform:k.transform,visible:k.visible,zIndex:k.zIndex}}return{time:o.time,layers:W}}clear(){if(this.workerClient){this.workerClient.clear();return}if(!this.ctx)return;this.ctx.fillStyle=this.backgroundColor,this.ctx.fillRect(0,0,this.width,this.height)}preview(o){this.checkDisposed(),this.previewOptions=o,this.state.duration=o.duration,this.lastRenderTime=0,this.emitter.emit("compositionchange",void 0)}async play(){if(this.checkDisposed(),this.state.playing)return;if(!this.previewOptions)throw Error("No preview configured. Call preview() first.");if(this.state.playing=!0,this.lastFrameTime=performance.now(),this.lastRenderTime=this.lastFrameTime,this.emitter.emit("play",void 0),this.audioManager)await this.audioManager.play(this.state.currentTime);this.startRenderLoop()}pause(){if(this.checkDisposed(),!this.state.playing)return;if(this.state.playing=!1,this.stopRenderLoop(),this.audioManager)this.audioManager.pause();this.emitter.emit("pause",void 0)}async seek(o){if(this.checkDisposed(),!this.previewOptions)return;let C=Math.max(0,Math.min(o,this.state.duration));if(this.state.seeking=!0,this.emitter.emit("seeking",{time:C}),this.state.currentTime=C,this.audioManager)await this.audioManager.seek(C);let W=this.previewOptions.getComposition(C);await this.render(W),this.state.seeking=!1,this.emitter.emit("seeked",{time:C}),this.emitter.emit("timeupdate",{currentTime:C})}startRenderLoop(){if(this.animationFrameId!==null)return;let o=()=>{if(!this.state.playing||!this.previewOptions)return;this.animationFrameId=requestAnimationFrame(o);let C=performance.now(),W=(C-this.lastFrameTime)/1000;if(this.lastFrameTime=C,this.state.currentTime+=W,this.state.currentTime>=this.state.duration)if(this.previewOptions.loop)this.state.currentTime=0;else{this.state.currentTime=this.state.duration,this.pause(),this.emitter.emit("ended",void 0);return}let w=this.previewOptions.fps??0,k=w>0?1000/w:0;if(!this.renderPending&&(k===0||C-this.lastRenderTime>=k)){this.renderPending=!0,this.lastRenderTime=C;let r=this.previewOptions.getComposition(this.state.currentTime);if(this.audioManager)this.processAudioLayers(r.audio??[],this.state.currentTime);this.render(r).catch(()=>{}).finally(()=>{this.renderPending=!1})}if(C-this.lastTimeUpdateEmit>=this.timeUpdateThrottleMs)this.lastTimeUpdateEmit=C,this.emitter.emit("timeupdate",{currentTime:this.state.currentTime})};this.animationFrameId=requestAnimationFrame(o)}stopRenderLoop(){if(this.animationFrameId!==null)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}async exportFrame(o,C={}){if(this.checkDisposed(),!this.previewOptions)return null;let W=this.previewOptions.getComposition(o);if(this.workerClient){let w=this.serializeWorkerFrame(W);return this.workerClient.exportFrame(w,C)}if(await this.render(W),"toBlob"in this.canvas)return new Promise((w)=>{this.canvas.toBlob((k)=>w(k),`image/${C.format??"png"}`,C.quality)});else return this.canvas.convertToBlob({type:`image/${C.format??"png"}`,quality:C.quality})}get currentTime(){return this.state.currentTime}get duration(){return this.state.duration}get playing(){return this.state.playing}get paused(){return!this.state.playing}get seeking(){return this.state.seeking}getWidth(){return this.width}getHeight(){return this.height}resize(o,C){if(this.checkDisposed(),this.width=o,this.height=C,this.canvas.width=o,this.canvas.height=C,this.workerClient){this.workerClient.resize(o,C);return}this.clear()}on(o,C){return this.emitter.on(o,C)}once(o,C){return this.emitter.once(o,C)}off(o,C){this.emitter.off(o,C)}setVolume(o){this.audioManager?.setMasterVolume(o)}setMuted(o){this.audioManager?.setMasterMuted(o)}getAudioContext(){if(!this.audioManager)throw Error("Audio is disabled for this compositor");return this.audioManager.getAudioContext()}checkDisposed(){if(this.disposed)throw Error("Compositor has been disposed")}dispose(){if(this.disposed)return;this.disposed=!0,this.stopRenderLoop(),this.audioManager?.dispose(),this.workerClient?.dispose(),this.workerClient=null,this.sourcePool.dispose(),this.registeredAudioSources.clear(),this.activeAudioSourceIds.clear(),this.audioScratch.nextActiveSourceIds.clear(),this.audioScratch.newSourceIds.length=0,this.audioScratch.newSourceTimes.length=0,this.workerSources.clear(),this.workerAudioSources.clear(),this.emitter.removeAllListeners(),this.ctx=null,this.previewOptions=null}}var H=self,R=null,U=null,G=(o)=>({id:o.id,type:o.type,duration:o.duration,width:o.width,height:o.height,hasAudio:o.type==="audio"?!0:o.hasAudio?o.hasAudio():!1}),y=(o)=>{if(!R)throw Error("Compositor not initialized");let C=Array(o.layers.length);for(let W=0;W<o.layers.length;W++){let w=o.layers[W],k=R.getSource(w.sourceId);if(!k)throw Error(`Unknown source: ${w.sourceId}`);C[W]={source:k,sourceTime:w.sourceTime,transform:w.transform,visible:w.visible,zIndex:w.zIndex}}return{time:o.time,layers:C}},z=(o,C)=>{H.postMessage(o,C??[])};H.onmessage=async(o)=>{let{id:C,kind:W,payload:w}=o.data;try{switch(W){case"init":{let k=w;U=k.canvas,R=new D({canvas:U,width:k.width,height:k.height,backgroundColor:k.backgroundColor,enableAudio:!1}),z({id:C,ok:!0});return}case"loadSource":{let{source:k,options:P}=w;if(!R)throw Error("Compositor not initialized");let r=await R.loadSource(k,P);z({id:C,ok:!0,result:G(r)});return}case"loadImage":{let{source:k}=w;if(!R)throw Error("Compositor not initialized");let P=await R.loadImage(k);z({id:C,ok:!0,result:G(P)});return}case"loadAudio":{let{source:k,options:P}=w;if(!R)throw Error("Compositor not initialized");let r=await R.loadAudio(k,P);z({id:C,ok:!0,result:G(r)});return}case"unloadSource":{if(!R)throw Error("Compositor not initialized");let{id:k}=w,P=R.unloadSource(k);z({id:C,ok:!0,result:P});return}case"render":{if(!R)throw Error("Compositor not initialized");let{frame:k}=w,P=y(k),r=await R.render(P);z({id:C,ok:!0,result:r});return}case"clear":{if(!R)throw Error("Compositor not initialized");R.clear(),z({id:C,ok:!0,result:!0});return}case"resize":{if(!R)throw Error("Compositor not initialized");let{width:k,height:P}=w;R.resize(k,P),z({id:C,ok:!0,result:!0});return}case"exportFrame":{if(!R||!U)throw Error("Compositor not initialized");let{frame:k,options:P}=w,r=y(k);await R.render(r);let p=`image/${P?.format??"png"}`,n=await U.convertToBlob({type:p,quality:P?.quality});z({id:C,ok:!0,result:n});return}case"dispose":{R?.dispose(),R=null,U=null,z({id:C,ok:!0,result:!0});return}default:throw Error(`Unknown worker command: ${W}`)}}catch(k){let P=k instanceof Error?k.message:"Worker error";z({id:C,ok:!1,error:P})}};
|
|
1
|
+
class H8{events=new Map;maxListeners;captureRejections;emitCache=[];constructor($={}){this.maxListeners=$.maxListeners??10,this.captureRejections=$.captureRejections??!1}on($,J){if(!this.events.has($))this.events.set($,new Set);let K=this.events.get($);if(!K)return()=>{};if(K.size>=this.maxListeners)console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${K.size} ${String($)} listeners added. Use emitter.setMaxListeners() to increase limit`);let Y=J;return K.add(Y),()=>{K.delete(Y)}}once($,J){let K=(Y)=>{this.off($,K),J(Y)};return this.on($,K)}off($,J){let K=this.events.get($);if(!K)return;if(J){let Y=J;K.delete(Y)}else K.clear()}emit($,J){let K=this.events.get($);if(!K||K.size===0)return;let Y=this.emitCache;Y.length=0;for(let Z of K)Y.push(Z);for(let Z=0;Z<Y.length;Z++){let X=Y[Z];try{let Q=X(J);if(this.captureRejections&&nJ(Q))this.handlePromiseRejection(Q)}catch(Q){if(this.captureRejections&&this.events.has("error"))this.emit("error",Q);else throw Q}}}handlePromiseRejection($){$.catch((J)=>{if(this.events.has("error"))this.emit("error",J);else throw J})}removeAllListeners($){if($)this.events.delete($);else this.events.clear()}setMaxListeners($){this.maxListeners=$}getMaxListeners(){return this.maxListeners}listeners($){let J=this.events.get($);return J?Array.from(J):[]}listenerCount($){let J=this.events.get($);return J?J.size:0}eventNames(){return Array.from(this.events.keys())}}function nJ($){if(!$||typeof $!=="object"&&typeof $!=="function")return!1;let J=$;return typeof J.then==="function"&&typeof J.catch==="function"}class A8{audioContext;masterGain;activeSources=new Map;activeSourceIdsScratch=new Set;playing=!1;disposed=!1;playbackId=0;startContextTime=0;startMediaTime=0;pauseTime=0;masterVolume=1;masterMuted=!1;constructor($={}){if($.audioContext)this.audioContext=$.audioContext;else{let J=globalThis,K=J.AudioContext||J.webkitAudioContext;if(!K)throw Error("AudioContext is not supported in this environment");this.audioContext=new K}this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination)}registerSource($,J){if(this.disposed)return;let K=this.audioContext.createGain(),Y=this.audioContext.createStereoPanner();K.connect(Y),Y.connect(this.masterGain),this.activeSources.set($.id,{sourceId:$.id,bufferSink:J,iterator:null,gainNode:K,panNode:Y,queuedNodes:new Set,volume:1,pan:0,muted:!1,startSourceTime:0,currentSourceTime:0,iteratorStartTime:0,lastScheduledTime:0})}unregisterSource($){let J=this.activeSources.get($);if(!J)return;this.stopSourceAudio(J),J.gainNode.disconnect(),J.panNode.disconnect(),this.activeSources.delete($)}hasSource($){return this.activeSources.has($)}processAudioLayers($,J){if(this.disposed||!this.playing)return;let K=this.activeSourceIdsScratch;K.clear();for(let Y of $){let Z=Y.source.id;K.add(Z);let X=this.activeSources.get(Z);if(!X)continue;let Q=Y.volume??1,W=Y.pan??0,G=Y.muted??!1,U=Y.sourceTime??J;if(X.volume!==Q||X.muted!==G)X.volume=Q,X.muted=G,X.gainNode.gain.value=G?0:Q*Q;if(X.pan!==W)X.pan=W,X.panNode.pan.value=Math.max(-1,Math.min(1,W));if(Math.abs(U-X.currentSourceTime)>0.5&&X.iterator!==null)this.restartSourceIterator(X,U);X.currentSourceTime=U}for(let[Y,Z]of this.activeSources)if(!K.has(Y)&&Z.iterator!==null)this.stopSourceAudio(Z)}async play($=this.pauseTime){if(this.playing||this.disposed)return;if(this.audioContext.state==="suspended")await this.audioContext.resume();this.playbackId++,this.playing=!0,this.startContextTime=this.audioContext.currentTime,this.startMediaTime=$,this.pauseTime=$}startSourcePlayback($,J){let K=this.activeSources.get($);if(!K||K.iterator!==null)return;this.restartSourceIterator(K,J)}restartSourceIterator($,J){this.stopSourceAudio($),$.startSourceTime=J,$.currentSourceTime=J,$.iteratorStartTime=this.audioContext.currentTime,$.iterator=$.bufferSink.buffers(J),$.lastScheduledTime=J,this.scheduleSourceBuffers($,this.playbackId)}async scheduleSourceBuffers($,J){let K=$.iterator;if(!K)return;try{for await(let{buffer:Y,timestamp:Z}of K){if(J!==this.playbackId||this.disposed||!this.playing)break;let X=this.audioContext.createBufferSource();X.buffer=Y,X.connect($.gainNode);let Q=Z-$.startSourceTime,W=$.iteratorStartTime+Q;if(W>=this.audioContext.currentTime)X.start(W);else{let q=this.audioContext.currentTime-W;if(q<Y.duration)X.start(this.audioContext.currentTime,q);else continue}$.queuedNodes.add(X),X.onended=()=>{$.queuedNodes.delete(X)},$.lastScheduledTime=Z;let G=this.audioContext.currentTime-$.iteratorStartTime;if(Z-$.startSourceTime-G>1)await this.waitForCatchup($,Z)}}catch{}}async waitForCatchup($,J){return new Promise((K)=>{let Y=setInterval(()=>{if(!this.playing||this.disposed){clearInterval(Y),K();return}let Z=this.audioContext.currentTime-$.iteratorStartTime;if(J-$.startSourceTime-Z<1)clearInterval(Y),K()},100)})}pause(){if(!this.playing)return;this.pauseTime=this.getCurrentTime(),this.playing=!1;for(let $ of this.activeSources.values())this.stopSourceAudio($)}stop(){this.pause(),this.pauseTime=0,this.startContextTime=0,this.startMediaTime=0}async seek($){let J=this.playing;if(this.pause(),this.pauseTime=$,this.startMediaTime=$,J)await this.play($)}stopSourceAudio($){for(let J of $.queuedNodes)try{J.stop()}catch{}if($.queuedNodes.clear(),$.iterator)$.iterator.return(),$.iterator=null}getCurrentTime(){if(this.playing)return this.startMediaTime+(this.audioContext.currentTime-this.startContextTime);return this.pauseTime}setMasterVolume($){this.masterVolume=Math.max(0,Math.min(1,$)),this.updateMasterGain()}setMasterMuted($){this.masterMuted=$,this.updateMasterGain()}updateMasterGain(){let $=this.masterMuted?0:this.masterVolume;this.masterGain.gain.value=$*$}getAudioContext(){return this.audioContext}isPlaying(){return this.playing}dispose(){if(this.disposed)return;this.disposed=!0,this.playbackId++,this.stop();for(let $ of this.activeSources.values())this.stopSourceAudio($),$.gainNode.disconnect(),$.panNode.disconnect();if(this.activeSources.clear(),this.masterGain.disconnect(),this.audioContext.state!=="closed")this.audioContext.close()}}/*!
|
|
2
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
3
|
+
*
|
|
4
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
*/function H($){if(!$)throw Error("Assertion failed.")}var w1=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;else throw Error(`Invalid rotation ${$}.`)},r=($)=>{return $&&$[$.length-1]};class b{constructor($){this.bytes=$,this.pos=0}seekToByte($){this.pos=8*$}readBit(){let $=Math.floor(this.pos/8),J=this.bytes[$]??0,K=7-(this.pos&7),Y=(J&1<<K)>>K;return this.pos++,Y}readBits($){if($===1)return this.readBit();let J=0;for(let K=0;K<$;K++)J<<=1,J|=this.readBit();return J}writeBits($,J){let K=this.pos+$;for(let Y=this.pos;Y<K;Y++){let Z=Math.floor(Y/8),X=this.bytes[Z],Q=7-(Y&7);X&=~(1<<Q),X|=(J&1<<K-Y-1)>>K-Y-1<<Q,this.bytes[Z]=X}this.pos=K}readAlignedByte(){if(this.pos%8!==0)throw Error("Bitstream is not byte-aligned.");let $=this.pos/8,J=this.bytes[$]??0;return this.pos+=8,J}skipBits($){this.pos+=$}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let $=new b(this.bytes);return $.pos=this.pos,$}}var B=($)=>{let J=0;while($.readBits(1)===0&&J<32)J++;if(J>=32)throw Error("Invalid exponential-Golomb code.");return(1<<J)-1+$.readBits(J)},m0=($)=>{let J=B($);return(J&1)===0?-(J>>1):J+1>>1};var $0=($)=>{if($.constructor===Uint8Array)return $;else if($ instanceof ArrayBuffer)return new Uint8Array($);else return new Uint8Array($.buffer,$.byteOffset,$.byteLength)},E=($)=>{if($.constructor===DataView)return $;else if($ instanceof ArrayBuffer)return new DataView($);else return new DataView($.buffer,$.byteOffset,$.byteLength)},l=new TextDecoder;var z8=($)=>{return Object.fromEntries(Object.entries($).map(([J,K])=>[K,J]))},F8={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},M1=z8(F8),_8={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},L1=z8(_8),C8={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},T1=z8(C8);var B1=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class U0{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let $,J=new Promise((Y)=>{$=Y}),K=this.currentPromise;return this.currentPromise=J,await K,$}}var D8=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},w8=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},l0=($,J,K)=>{let Y=0,Z=$.length-1,X=-1;while(Y<=Z){let Q=Y+Z>>1,W=K($[Q]);if(W===J)X=Q,Z=Q-1;else if(W<J)Y=Q+1;else Z=Q-1}return X},S=($,J,K)=>{let Y=0,Z=$.length-1,X=-1;while(Y<=Z){let Q=Y+(Z-Y+1)/2|0;if(K($[Q])<=J)X=Q,Y=Q+1;else Z=Q-1}return X},M8=($,J,K)=>{let Y=S($,K(J),K);$.splice(Y+1,0,J)},n=()=>{let $,J;return{promise:new Promise((Y,Z)=>{$=Y,J=Z}),resolve:$,reject:J}};var L8=($,J)=>{for(let K=$.length-1;K>=0;K--)if(J($[K]))return $[K];return},P1=($,J)=>{for(let K=$.length-1;K>=0;K--)if(J($[K]))return K;return-1},_$=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},C$=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},W0=($)=>{throw Error(`Unexpected value: ${$}`)},h0=($,J,K)=>{let Y=$.getUint8(J),Z=$.getUint8(J+1),X=$.getUint8(J+2);if(K)return Y|Z<<8|X<<16;else return Y<<16|Z<<8|X},D$=($,J,K)=>{return h0($,J,K)<<8>>8};var W1=($,J)=>{return{async next(){let K=await $.next();if(K.done)return{value:void 0,done:!0};else return{value:J(K.value),done:!1}},return(){return $.return()},throw(K){return $.throw(K)},[Symbol.asyncIterator](){return this}}},x0=($,J,K)=>{return Math.max(J,Math.min(K,$))},d="und",y0=($,J)=>{let K=10**J;return Math.round($*K)/K},w$=($,J)=>{return Math.round($/J)*J},M$=($)=>{let J=0;while($)J++,$>>=1;return J},rJ=/^[a-z]{3}$/,v1=($)=>{return rJ.test($)},G0=1e6*(1+Number.EPSILON),T8=($,J)=>{let K={...$,...J};if($.headers||J.headers){let Y=$.headers?F$($.headers):{},Z=J.headers?F$(J.headers):{},X={...Y};Object.entries(Z).forEach(([Q,W])=>{let G=Object.keys(X).find((U)=>U.toLowerCase()===Q.toLowerCase());if(G)delete X[G];X[Q]=W}),K.headers=X}return K},F$=($)=>{if($ instanceof Headers){let J={};return $.forEach((K,Y)=>{J[Y]=K}),J}if(Array.isArray($)){let J={};return $.forEach(([K,Y])=>{J[K]=Y}),J}return $},B8=async($,J,K,Y)=>{let Z=0;while(!0)try{return await $(J,K)}catch(X){Z++;let Q=Y(Z,X,J);if(Q===null)throw X;if(console.error("Retrying failed fetch. Error:",X),!Number.isFinite(Q)||Q<0)throw TypeError("Retry delay must be a non-negative finite number.");if(Q>0)await new Promise((W)=>setTimeout(W,1000*Q))}};class h1{constructor(){this.currentPromise=Promise.resolve()}call($){return this.currentPromise=this.currentPromise.then($)}}var O8=null,x1=()=>{if(O8!==null)return O8;let $=!!(typeof navigator<"u"&&navigator.vendor?.match(/apple/i)&&!navigator.userAgent?.match(/crios/i)&&!navigator.userAgent?.match(/fxios/i)&&!navigator.userAgent?.match(/Opera|OPT\//));return O8=$,$},R8=null,G1=()=>{if(R8!==null)return R8;return R8=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},S0=($,J)=>{return $!==-1?$:J},y1=($,J,K,Y)=>{return $<=Y&&K<=J};var L$=($)=>{let J=atob($),K=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)K[Y]=J.charCodeAt(Y);return K};var S1=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},M0=($)=>{return typeof $==="number"&&!Number.isNaN($)};/*!
|
|
8
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
9
|
+
*
|
|
10
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
11
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
12
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
13
|
+
*/class E0{constructor($,J){if(this.data=$,this.mimeType=J,!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(typeof J!=="string")throw TypeError("mimeType must be a string.")}}class P8{constructor($,J,K,Y){if(this.data=$,this.mimeType=J,this.name=K,this.description=Y,!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!==void 0&&typeof J!=="string")throw TypeError("mimeType, when provided, must be a string.");if(K!==void 0&&typeof K!=="string")throw TypeError("name, when provided, must be a string.");if(Y!==void 0&&typeof Y!=="string")throw TypeError("description, when provided, must be a string.")}}/*!
|
|
14
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
15
|
+
*
|
|
16
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
17
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
18
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
19
|
+
*/var j0=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],iJ=["aac","opus","mp3","vorbis","flac"],TY=[...iJ,...j0];var b0=[{maxPictureSize:36864,maxBitrate:200000,level:10},{maxPictureSize:73728,maxBitrate:800000,level:11},{maxPictureSize:122880,maxBitrate:1800000,level:20},{maxPictureSize:245760,maxBitrate:3600000,level:21},{maxPictureSize:552960,maxBitrate:7200000,level:30},{maxPictureSize:983040,maxBitrate:12000000,level:31},{maxPictureSize:2228224,maxBitrate:18000000,level:40},{maxPictureSize:2228224,maxBitrate:30000000,level:41},{maxPictureSize:8912896,maxBitrate:60000000,level:50},{maxPictureSize:8912896,maxBitrate:120000000,level:51},{maxPictureSize:8912896,maxBitrate:180000000,level:52},{maxPictureSize:35651584,maxBitrate:180000000,level:60},{maxPictureSize:35651584,maxBitrate:240000000,level:61},{maxPictureSize:35651584,maxBitrate:480000000,level:62}];var T$=".01.01.01.01.00",B$=".0.110.01.01.01.0";var E1=($)=>{let{codec:J,codecDescription:K,colorSpace:Y,avcCodecInfo:Z,hevcCodecInfo:X,vp9CodecInfo:Q,av1CodecInfo:W}=$;if(J==="avc"){if(Z){let G=new Uint8Array([Z.avcProfileIndication,Z.profileCompatibility,Z.avcLevelIndication]);return`avc1.${D8(G)}`}if(!K||K.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${D8(K.subarray(1,4))}`}else if(J==="hevc"){let G,U,q,j,V,N;if(X)G=X.generalProfileSpace,U=X.generalProfileIdc,q=w8(X.generalProfileCompatibilityFlags),j=X.generalTierFlag,V=X.generalLevelIdc,N=[...X.generalConstraintIndicatorFlags];else{if(!K||K.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let R=E(K),z=R.getUint8(1);G=z>>6&3,U=z&31,q=w8(R.getUint32(2)),j=z>>5&1,V=R.getUint8(12),N=[];for(let O=0;O<6;O++)N.push(R.getUint8(6+O))}let A="hev1.";A+=["","A","B","C"][G]+U,A+=".",A+=q.toString(16).toUpperCase(),A+=".",A+=j===0?"L":"H",A+=V;while(N.length>0&&N[N.length-1]===0)N.pop();if(N.length>0)A+=".",A+=N.map((R)=>R.toString(16).toUpperCase()).join(".");return A}else if(J==="vp8")return"vp8";else if(J==="vp9"){if(!Q){let O=$.width*$.height,F=r(b0).level;for(let _ of b0)if(O<=_.maxPictureSize){F=_.level;break}return`vp09.00.${F.toString().padStart(2,"0")}.08`}let G=Q.profile.toString().padStart(2,"0"),U=Q.level.toString().padStart(2,"0"),q=Q.bitDepth.toString().padStart(2,"0"),j=Q.chromaSubsampling.toString().padStart(2,"0"),V=Q.colourPrimaries.toString().padStart(2,"0"),N=Q.transferCharacteristics.toString().padStart(2,"0"),A=Q.matrixCoefficients.toString().padStart(2,"0"),R=Q.videoFullRangeFlag.toString().padStart(2,"0"),z=`vp09.${G}.${U}.${q}.${j}`;if(z+=`.${V}.${N}.${A}.${R}`,z.endsWith(T$))z=z.slice(0,-T$.length);return z}else if(J==="av1"){if(!W){let _=$.width*$.height,w=r(b0).level;for(let P of b0)if(_<=P.maxPictureSize){w=P.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let G=W.profile,U=W.level.toString().padStart(2,"0"),q=W.tier?"H":"M",j=W.bitDepth.toString().padStart(2,"0"),V=W.monochrome?"1":"0",N=100*W.chromaSubsamplingX+10*W.chromaSubsamplingY+1*(W.chromaSubsamplingX&&W.chromaSubsamplingY?W.chromaSamplePosition:0),A=Y?.primaries?F8[Y.primaries]:1,R=Y?.transfer?_8[Y.transfer]:1,z=Y?.matrix?C8[Y.matrix]:1,O=Y?.fullRange?1:0,F=`av01.${G}.${U}${q}.${j}`;if(F+=`.${V}.${N.toString().padStart(3,"0")}`,F+=`.${A.toString().padStart(2,"0")}`,F+=`.${R.toString().padStart(2,"0")}`,F+=`.${z.toString().padStart(2,"0")}`,F+=`.${O}`,F.endsWith(B$))F=F.slice(0,-B$.length);return F}throw TypeError(`Unhandled codec '${J}'.`)};var b1=($)=>{let{codec:J,codecDescription:K,aacCodecInfo:Y}=$;if(J==="aac"){if(!Y)throw TypeError("AAC codec info must be provided.");if(Y.isMpeg2)return"mp4a.67";else return`mp4a.40.${h8(K).objectType}`}else if(J==="mp3")return"mp3";else if(J==="opus")return"opus";else if(J==="vorbis")return"vorbis";else if(J==="flac")return"flac";else if(J&&j0.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)},q1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],v8=[-1,1,2,3,4,5,6,8],h8=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new b($),K=J.readBits(5);if(K===31)K=32+J.readBits(6);let Y=J.readBits(4),Z=null;if(Y===15)Z=J.readBits(24);else if(Y<q1.length)Z=q1[Y];let X=J.readBits(4),Q=null;if(X>=1&&X<=7)Q=v8[X];return{objectType:K,frequencyIndex:Y,sampleRate:Z,channelConfiguration:X,numberOfChannels:Q}},f0=48000,sJ=/^pcm-([usf])(\d+)+(be)?$/,f1=($)=>{if(H(j0.includes($)),$==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};else if($==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let J=sJ.exec($);H(J);let K;if(J[1]==="u")K="unsigned";else if(J[1]==="s")K="signed";else K="float";let Y=Number(J[2])/8,Z=J[3]!=="be";return{dataType:K,sampleSize:Y,littleEndian:Z,silentValue:$==="pcm-u8"?128:0}};/*!
|
|
20
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
21
|
+
*
|
|
22
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
23
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
24
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
25
|
+
*/var d0;(function($){$[$.IDR=5]="IDR",$[$.SPS=7]="SPS",$[$.PPS=8]="PPS",$[$.SPS_EXT=13]="SPS_EXT"})(d0||(d0={}));var i;(function($){$[$.RASL_N=8]="RASL_N",$[$.RASL_R=9]="RASL_R",$[$.BLA_W_LP=16]="BLA_W_LP",$[$.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",$[$.VPS_NUT=32]="VPS_NUT",$[$.SPS_NUT=33]="SPS_NUT",$[$.PPS_NUT=34]="PPS_NUT",$[$.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",$[$.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(i||(i={}));var k1=($)=>{let J=[],K=0;while(K<$.length){let Y=-1,Z=0;for(let X=K;X<$.length-3;X++){if($[X]===0&&$[X+1]===0&&$[X+2]===1){Y=X,Z=3;break}if(X<$.length-4&&$[X]===0&&$[X+1]===0&&$[X+2]===0&&$[X+3]===1){Y=X,Z=4;break}}if(Y===-1)break;if(K>0&&Y>K){let X=$.subarray(K,Y);if(X.length>0)J.push(X)}K=Y+Z}if(K<$.length){let Y=$.subarray(K);if(Y.length>0)J.push(Y)}return J},h$=($,J)=>{let K=[],Y=0,Z=new DataView($.buffer,$.byteOffset,$.byteLength);while(Y+J<=$.length){let X;if(J===1)X=Z.getUint8(Y);else if(J===2)X=Z.getUint16(Y,!1);else if(J===3)X=h0(Z,Y,!1);else if(J===4)X=Z.getUint32(Y,!1);else W0(J),H(!1);Y+=J;let Q=$.subarray(Y,Y+X);K.push(Q),Y+=X}return K},x8=($)=>{let J=[],K=$.length;for(let Y=0;Y<K;Y++)if(Y+2<K&&$[Y]===0&&$[Y+1]===0&&$[Y+2]===3)J.push(0,0),Y+=2;else J.push($[Y]);return new Uint8Array(J)};var tJ=($,J)=>{if(J.description){let Z=($0(J.description)[4]&3)+1;return h$($,Z)}else return k1($)},I1=($)=>{return $[0]&31},x$=($)=>{try{let J=k1($),K=J.filter((V)=>I1(V)===d0.SPS),Y=J.filter((V)=>I1(V)===d0.PPS),Z=J.filter((V)=>I1(V)===d0.SPS_EXT);if(K.length===0)return null;if(Y.length===0)return null;let X=K[0],Q=new b(x8(X));if(Q.skipBits(1),Q.skipBits(2),Q.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;let G=Q.readAlignedByte(),U=Q.readAlignedByte(),q=Q.readAlignedByte(),j={configurationVersion:1,avcProfileIndication:G,profileCompatibility:U,avcLevelIndication:q,lengthSizeMinusOne:3,sequenceParameterSets:K,pictureParameterSets:Y,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(G===100||G===110||G===122||G===144){B(Q);let V=B(Q);if(V===3)Q.skipBits(1);let N=B(Q),A=B(Q);j.chromaFormat=V,j.bitDepthLumaMinus8=N,j.bitDepthChromaMinus8=A,j.sequenceParameterSetExt=Z}return j}catch(J){return console.error("Error building AVC Decoder Configuration Record:",J),null}};var y8=($,J)=>{if(J.description){let Z=($0(J.description)[21]&3)+1;return h$($,Z)}else return k1($)},V0=($)=>{return $[0]>>1&63},y$=($)=>{try{let J=k1($),K=J.filter((I)=>V0(I)===i.VPS_NUT),Y=J.filter((I)=>V0(I)===i.SPS_NUT),Z=J.filter((I)=>V0(I)===i.PPS_NUT),X=J.filter((I)=>V0(I)===i.PREFIX_SEI_NUT||V0(I)===i.SUFFIX_SEI_NUT);if(Y.length===0||Z.length===0)return null;let Q=Y[0],W=new b(x8(Q));W.skipBits(16),W.readBits(4);let G=W.readBits(3),U=W.readBits(1),{general_profile_space:q,general_tier_flag:j,general_profile_idc:V,general_profile_compatibility_flags:N,general_constraint_indicator_flags:A,general_level_idc:R}=eJ(W,G);B(W);let z=B(W);if(z===3)W.skipBits(1);if(B(W),B(W),W.readBits(1))B(W),B(W),B(W),B(W);let O=B(W),F=B(W);B(W);let w=W.readBits(1)?0:G;for(let I=w;I<=G;I++)B(W),B(W),B(W);if(B(W),B(W),B(W),B(W),B(W),B(W),W.readBits(1)){if(W.readBits(1))$Y(W)}if(W.skipBits(1),W.skipBits(1),W.readBits(1))W.skipBits(4),W.skipBits(4),B(W),B(W),W.skipBits(1);let P=B(W);if(JY(W,P),W.readBits(1)){let I=B(W);for(let x=0;x<I;x++)B(W),W.skipBits(1)}W.skipBits(1),W.skipBits(1);let D=0;if(W.readBits(1))D=KY(W,G);let L=0;if(Z.length>0){let I=Z[0],x=new b(x8(I));if(x.skipBits(16),B(x),B(x),x.skipBits(1),x.skipBits(1),x.skipBits(3),x.skipBits(1),x.skipBits(1),B(x),B(x),m0(x),x.skipBits(1),x.skipBits(1),x.readBits(1))B(x);m0(x),m0(x),x.skipBits(1),x.skipBits(1),x.skipBits(1),x.skipBits(1);let v0=x.readBits(1),D1=x.readBits(1);if(!v0&&!D1)L=0;else if(v0&&!D1)L=2;else if(!v0&&D1)L=3;else L=0}let h=[...K.length?[{arrayCompleteness:1,nalUnitType:i.VPS_NUT,nalUnits:K}]:[],...Y.length?[{arrayCompleteness:1,nalUnitType:i.SPS_NUT,nalUnits:Y}]:[],...Z.length?[{arrayCompleteness:1,nalUnitType:i.PPS_NUT,nalUnits:Z}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:V0(X[0]),nalUnits:X}]:[]];return{configurationVersion:1,generalProfileSpace:q,generalTierFlag:j,generalProfileIdc:V,generalProfileCompatibilityFlags:N,generalConstraintIndicatorFlags:A,generalLevelIdc:R,minSpatialSegmentationIdc:D,parallelismType:L,chromaFormatIdc:z,bitDepthLumaMinus8:O,bitDepthChromaMinus8:F,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:G+1,temporalIdNested:U,lengthSizeMinusOne:3,arrays:h}}catch(J){return console.error("Error building HEVC Decoder Configuration Record:",J),null}},eJ=($,J)=>{let K=$.readBits(2),Y=$.readBits(1),Z=$.readBits(5),X=0;for(let q=0;q<32;q++)X=X<<1|$.readBits(1);let Q=new Uint8Array(6);for(let q=0;q<6;q++)Q[q]=$.readBits(8);let W=$.readBits(8),G=[],U=[];for(let q=0;q<J;q++)G.push($.readBits(1)),U.push($.readBits(1));if(J>0)for(let q=J;q<8;q++)$.skipBits(2);for(let q=0;q<J;q++){if(G[q])$.skipBits(88);if(U[q])$.skipBits(8)}return{general_profile_space:K,general_tier_flag:Y,general_profile_idc:Z,general_profile_compatibility_flags:X,general_constraint_indicator_flags:Q,general_level_idc:W}},$Y=($)=>{for(let J=0;J<4;J++)for(let K=0;K<(J===3?2:6);K++)if(!$.readBits(1))B($);else{let Z=Math.min(64,1<<4+(J<<1));if(J>1)m0($);for(let X=0;X<Z;X++)m0($)}},JY=($,J)=>{let K=[];for(let Y=0;Y<J;Y++)K[Y]=YY($,Y,J,K)},YY=($,J,K,Y)=>{let Z=0,X=0,Q=0;if(J!==0)X=$.readBits(1);if(X){if(J===K){let G=B($);Q=J-(G+1)}else Q=J-1;$.readBits(1),B($);let W=Y[Q]??0;for(let G=0;G<=W;G++)if(!$.readBits(1))$.readBits(1);Z=Y[Q]}else{let W=B($),G=B($);for(let U=0;U<W;U++)B($),$.readBits(1);for(let U=0;U<G;U++)B($),$.readBits(1);Z=W+G}return Z},KY=($,J)=>{if($.readBits(1)){if($.readBits(8)===255)$.readBits(16),$.readBits(16)}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),$.readBits(1),$.readBits(1))$.readBits(8),$.readBits(8),$.readBits(8)}if($.readBits(1))B($),B($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))B($),B($),B($),B($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))B($);if($.readBits(1))XY($,!0,J)}if($.readBits(1)){$.readBits(1),$.readBits(1),$.readBits(1);let K=B($);return B($),B($),B($),B($),K}return 0},XY=($,J,K)=>{let Y=!1,Z=!1,X=!1;if(J){if(Y=$.readBits(1)===1,Z=$.readBits(1)===1,Y||Z){if(X=$.readBits(1)===1,X)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),X)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let Q=0;Q<=K;Q++){let W=$.readBits(1)===1,G=!0;if(!W)G=$.readBits(1)===1;let U=!1;if(G)B($);else U=$.readBits(1)===1;let q=1;if(!U)q=B($)+1;if(Y)P$($,q,X);if(Z)P$($,q,X)}},P$=($,J,K)=>{for(let Y=0;Y<J;Y++){if(B($),B($),K)B($),B($);$.readBits(1)}};var g1=($)=>{let J=new b($);if(J.readBits(2)!==2)return null;let Y=J.readBits(1),X=(J.readBits(1)<<1)+Y;if(X===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let U=8;if(X>=2)U=J.readBits(1)?12:10;let q=J.readBits(3),j=0,V=0;if(q!==7)if(V=J.readBits(1),X===1||X===3){let L=J.readBits(1),h=J.readBits(1);j=!L&&!h?3:L&&!h?2:1,J.skipBits(1)}else j=1;else j=3,V=1;let N=J.readBits(16),A=J.readBits(16),R=N+1,z=A+1,O=R*z,F=r(b0).level;for(let D of b0)if(O<=D.maxPictureSize){F=D.level;break}return{profile:X,level:F,bitDepth:U,chromaSubsampling:j,videoFullRangeFlag:V,colourPrimaries:q===2?1:q===1?6:2,transferCharacteristics:q===2?1:q===1?6:2,matrixCoefficients:q===7?0:q===2?1:q===1?6:2}},S$=function*($){let J=new b($),K=()=>{let Y=0;for(let Z=0;Z<8;Z++){let X=J.readAlignedByte();if(Y|=(X&127)<<Z*7,!(X&128))break;if(Z===7&&X&128)return null}if(Y>=4294967295)return null;return Y};while(J.getBitsLeft()>=8){J.skipBits(1);let Y=J.readBits(4),Z=J.readBits(1),X=J.readBits(1);if(J.skipBits(1),Z)J.skipBits(8);let Q;if(X){let W=K();if(W===null)return;Q=W}else Q=Math.floor(J.getBitsLeft()/8);H(J.pos%8===0),yield{type:Y,data:$.subarray(J.pos/8,J.pos/8+Q)},J.skipBits(Q*8)}},u1=($)=>{for(let{type:J,data:K}of S$($)){if(J!==1)continue;let Y=new b(K),Z=Y.readBits(3),X=Y.readBits(1),Q=Y.readBits(1),W=0,G=0,U=0;if(Q)W=Y.readBits(5);else{if(Y.readBits(1)){if(Y.skipBits(32),Y.skipBits(32),Y.readBits(1))return null}let O=Y.readBits(1);if(O)U=Y.readBits(5),Y.skipBits(32),Y.skipBits(5),Y.skipBits(5);let F=Y.readBits(5);for(let _=0;_<=F;_++){Y.skipBits(12);let w=Y.readBits(5);if(_===0)W=w;if(w>7){let D=Y.readBits(1);if(_===0)G=D}if(O){if(Y.readBits(1)){let L=U+1;Y.skipBits(L),Y.skipBits(L),Y.skipBits(1)}}if(Y.readBits(1))Y.skipBits(4)}}let q=Y.readBits(1),j=8;if(Z===2&&q)j=Y.readBits(1)?12:10;else if(Z<=2)j=q?10:8;let V=0;if(Z!==1)V=Y.readBits(1);let N=1,A=1,R=0;if(!V){if(Z===0)N=1,A=1;else if(Z===1)N=0,A=0;else if(j===12){if(N=Y.readBits(1),N)A=Y.readBits(1)}if(N&&A)R=Y.readBits(2)}return{profile:Z,level:W,tier:G,bitDepth:j,monochrome:V,chromaSubsamplingX:N,chromaSubsamplingY:A,chromaSamplePosition:R}}return null},E$=($)=>{let J=E($),K=J.getUint8(9),Y=J.getUint16(10,!0),Z=J.getUint32(12,!0),X=J.getInt16(16,!0),Q=J.getUint8(18),W=null;if(Q)W=$.subarray(19,21+K);return{outputChannelCount:K,preSkip:Y,inputSampleRate:Z,outputGain:X,channelMappingFamily:Q,channelMappingTable:W}},ZY=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],b$=($)=>{let J=$[0]>>3;return{durationInSamples:ZY[J]}},f$=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let K=$.length,Y=new Uint8Array(K);for(let j=0;j<K;j++)Y[j]=$[K-1-j];let Z=new b(Y),X=0;while(Z.getBitsLeft()>97)if(Z.readBits(1)===1){X=Z.pos;break}if(X===0)throw Error("Invalid Setup header: framing bit not found.");let Q=0,W=!1,G=0;while(Z.getBitsLeft()>=97){let j=Z.pos,V=Z.readBits(8),N=Z.readBits(16),A=Z.readBits(16);if(V>63||N!==0||A!==0){Z.pos=j;break}if(Z.skipBits(1),Q++,Q>64)break;if(Z.clone().readBits(6)+1===Q)W=!0,G=Q}if(!W)throw Error("Invalid Setup header: mode header not found.");if(G>63)throw Error(`Unsupported mode count: ${G}.`);let U=G;Z.pos=0,Z.skipBits(X);let q=Array(U).fill(0);for(let j=U-1;j>=0;j--)Z.skipBits(40),q[j]=Z.readBits(1);return{modeBlockflags:q}},p1=($,J,K)=>{switch($){case"avc":return tJ(K,J).some((X)=>I1(X)===d0.IDR)?"key":"delta";case"hevc":return y8(K,J).some((X)=>{let Q=V0(X);return i.BLA_W_LP<=Q&&Q<=i.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return(K[0]&1)===0?"key":"delta";case"vp9":{let Y=new b(K);if(Y.readBits(2)!==2)return null;let Z=Y.readBits(1);if((Y.readBits(1)<<1)+Z===3)Y.skipBits(1);if(Y.readBits(1))return null;return Y.readBits(1)===0?"key":"delta"}case"av1":{let Y=!1;for(let{type:Z,data:X}of S$(K))if(Z===1){let Q=new b(X);Q.skipBits(4),Y=!!Q.readBits(1)}else if(Z===3||Z===6||Z===7){if(Y)return"key";let Q=new b(X);if(Q.readBits(1))return null;return Q.readBits(2)===0?"key":"delta"}return null}default:W0($),H(!1)}},N0;(function($){$[$.STREAMINFO=0]="STREAMINFO",$[$.VORBIS_COMMENT=4]="VORBIS_COMMENT",$[$.PICTURE=6]="PICTURE"})(N0||(N0={}));var U1=($,J)=>{let K=E($),Y=0,Z=K.getUint32(Y,!0);Y+=4;let X=l.decode($.subarray(Y,Y+Z));if(Y+=Z,Z>0)J.raw??={},J.raw.vendor??=X;let Q=K.getUint32(Y,!0);Y+=4;for(let W=0;W<Q;W++){let G=K.getUint32(Y,!0);Y+=4;let U=l.decode($.subarray(Y,Y+G));Y+=G;let q=U.indexOf("=");if(q===-1)continue;let j=U.slice(0,q).toUpperCase(),V=U.slice(q+1);switch(J.raw??={},J.raw[j]??=V,j){case"TITLE":J.title??=V;break;case"DESCRIPTION":J.description??=V;break;case"ARTIST":J.artist??=V;break;case"ALBUM":J.album??=V;break;case"ALBUMARTIST":J.albumArtist??=V;break;case"COMMENT":J.comment??=V;break;case"LYRICS":J.lyrics??=V;break;case"TRACKNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.trackNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.tracksTotal??=R}break;case"TRACKTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.tracksTotal??=N}break;case"DISCNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.discNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.discsTotal??=R}break;case"DISCTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.discsTotal??=N}break;case"DATE":{let N=new Date(V);if(!Number.isNaN(N.getTime()))J.date??=N}break;case"GENRE":J.genre??=V;break;case"METADATA_BLOCK_PICTURE":{let N=L$(V),A=E(N),R=A.getUint32(0,!1),z=A.getUint32(4,!1),O=String.fromCharCode(...N.subarray(8,8+z)),F=A.getUint32(8+z,!1),_=l.decode(N.subarray(12+z,12+z+F)),w=A.getUint32(z+F+28),P=N.subarray(z+F+32,z+F+32+w);J.images??=[],J.images.push({data:P,mimeType:O,kind:R===3?"coverFront":R===4?"coverBack":"unknown",name:void 0,description:_||void 0})}break}}};/*!
|
|
26
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
27
|
+
*
|
|
28
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
29
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
30
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
31
|
+
*/class s{constructor($){this.input=$}}/*!
|
|
32
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
33
|
+
*
|
|
34
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
35
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
36
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
37
|
+
*/var m1=[],l1=[];/*!
|
|
38
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
39
|
+
*
|
|
40
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
41
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
42
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
43
|
+
*/var u=new Uint8Array(0);class f{constructor($,J,K,Y,Z=-1,X,Q){if(this.data=$,this.type=J,this.timestamp=K,this.duration=Y,this.sequenceNumber=Z,$===u&&X===void 0)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(X===void 0)X=$.byteLength;if(!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!=="key"&&J!=="delta")throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(K))throw TypeError("timestamp must be a number.");if(!Number.isFinite(Y)||Y<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(Z))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(X)||X<0)throw TypeError("byteLength must be a non-negative integer.");if(Q!==void 0&&(typeof Q!=="object"||!Q))throw TypeError("sideData, when provided, must be an object.");if(Q?.alpha!==void 0&&!(Q.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(Q?.alphaByteLength!==void 0&&(!Number.isInteger(Q.alphaByteLength)||Q.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");if(this.byteLength=X,this.sideData=Q??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0)this.sideData.alphaByteLength=this.sideData.alpha.byteLength}get isMetadataOnly(){return this.data===u}get microsecondTimestamp(){return Math.trunc(G0*this.timestamp)}get microsecondDuration(){return Math.trunc(G0*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk($=this.type){if(!this.sideData.alpha)throw TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:$,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk($,J){if(!($ instanceof EncodedVideoChunk||$ instanceof EncodedAudioChunk))throw TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let K=new Uint8Array($.byteLength);return $.copyTo(K),new f(K,$.type,$.timestamp/1e6,($.duration??0)/1e6,void 0,void 0,J)}clone($){if($!==void 0&&(typeof $!=="object"||$===null))throw TypeError("options, when provided, must be an object.");if($?.timestamp!==void 0&&!Number.isFinite($.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if($?.duration!==void 0&&!Number.isFinite($.duration))throw TypeError("options.duration, when provided, must be a number.");return new f(this.data,this.type,$?.timestamp??this.timestamp,$?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*!
|
|
44
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
45
|
+
*
|
|
46
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
47
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
48
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
49
|
+
*/var I$=($)=>{let K=0,Y=0,Z=~$;if(Z&128)Z&=-129,K=-1;Y=((Z&240)>>4)+5;let X=(1<<Y|(Z&15)<<Y-4|1<<Y-5)-33;return K===0?X:-X};var k$=($)=>{let J=0,K=0,Y=$^85;if(Y&128)Y&=-129,J=-1;K=((Y&240)>>4)+4;let Z=0;if(K!==4)Z=1<<K|(Y&15)<<K-4|1<<K-5;else Z=Y<<1|1;return J===0?Z:-Z};/*!
|
|
50
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
51
|
+
*
|
|
52
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
53
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
54
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
55
|
+
*/S1();class H0{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(G0*this.timestamp)}get microsecondDuration(){return Math.trunc(G0*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if(this._closed=!1,$ instanceof ArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(!("format"in J)||typeof J.format!=="string")throw TypeError("init.format must be a string.");if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=$0($).slice(),this.format=J.format,this.codedWidth=J.codedWidth,this.codedHeight=J.codedHeight,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new VideoColorSpace(J.colorSpace)}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=$,this.format=$.format,this.codedWidth=$.displayWidth,this.codedHeight=$.displayHeight,this.rotation=J?.rotation??0,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=$.colorSpace}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new H0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*G0),duration:Math.trunc((J.duration??0)*G0)||void 0}),J);let K=0,Y=0;if("naturalWidth"in $)K=$.naturalWidth,Y=$.naturalHeight;else if("videoWidth"in $)K=$.videoWidth,Y=$.videoHeight;else if("width"in $)K=Number($.width),Y=Number($.height);if(!K||!Y)throw TypeError("Could not determine dimensions.");let Z=new OffscreenCanvas(K,Y),X=Z.getContext("2d",{alpha:G1(),willReadFrequently:!0});H(X),X.drawImage($,0,0),this._data=Z,this.format="RGBX",this.codedWidth=K,this.codedHeight=Y,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}clone(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),j1(this._data))return new H0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation});else if(this._data instanceof Uint8Array)return new H0(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation});else return new H0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){if(this._closed)return;if(j1(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),j1(this._data))return this._data.allocationSize();else if(this._data instanceof Uint8Array)return this._data.byteLength;else return this.codedWidth*this.codedHeight*4}async copyTo($){if(!B1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),j1(this._data))await this._data.copyTo($);else if(this._data instanceof Uint8Array)$0($).set(this._data);else{let K=this._data.getContext("2d");H(K);let Y=K.getImageData(0,0,this.codedWidth,this.codedHeight);$0($).set(Y.data)}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),j1(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});else if(this._data instanceof Uint8Array)return new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace});else return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,K,Y,Z,X,Q,W,G){let U=0,q=0,j=this.displayWidth,V=this.displayHeight,N=0,A=0,R=this.displayWidth,z=this.displayHeight;if(X!==void 0)if(U=J,q=K,j=Y,V=Z,N=X,A=Q,W!==void 0)R=W,z=G;else R=j,z=V;else if(N=J,A=K,Y!==void 0)R=Y,z=Z;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(U))throw TypeError("sx must be a number.");if(!Number.isFinite(q))throw TypeError("sy must be a number.");if(!Number.isFinite(j)||j<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(V)||V<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(N))throw TypeError("dx must be a number.");if(!Number.isFinite(A))throw TypeError("dy must be a number.");if(!Number.isFinite(R)||R<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(z)||z<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:U,sy:q,sWidth:j,sHeight:V}=this._rotateSourceRegion(U,q,j,V,this.rotation));let O=this.toCanvasImageSource();$.save();let F=N+R/2,_=A+z/2;$.translate(F,_),$.rotate(this.rotation*Math.PI/180);let w=this.rotation%180===0?1:R/z;$.scale(1/w,w),$.drawImage(O,U,q,j,V,-R/2,-z/2,R,z),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)b8(J.crop,"options.");let K=$.canvas.width,Y=$.canvas.height,Z=J.rotation??this.rotation,[X,Q]=Z%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];if(J.crop)E8(J.crop,X,Q);let W,G,U,q,{sx:j,sy:V,sWidth:N,sHeight:A}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??X,J.crop?.height??Q,Z);if(J.fit==="fill")W=0,G=0,U=K,q=Y;else{let[z,O]=J.crop?[J.crop.width,J.crop.height]:[X,Q],F=J.fit==="contain"?Math.min(K/z,Y/O):Math.max(K/z,Y/O);U=z*F,q=O*F,W=(K-U)/2,G=(Y-q)/2}let R=Z%180===0?1:U/q;$.translate(K/2,Y/2),$.rotate(Z*Math.PI/180),$.scale(1/R,R),$.translate(-K/2,-Y/2),$.drawImage(this.toCanvasImageSource(),j,V,N,A,W,G,U,q)}_rotateSourceRegion($,J,K,Y,Z){if(Z===90)[$,J,K,Y]=[J,this.codedHeight-$-K,Y,K];else if(Z===180)[$,J]=[this.codedWidth-$-K,this.codedHeight-J-Y];else if(Z===270)[$,J,K,Y]=[this.codedWidth-J-Y,$,Y,K];return{sx:$,sy:J,sWidth:K,sHeight:Y}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}else return this._data}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}[Symbol.dispose](){this.close()}}var j1=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},E8=($,J,K)=>{$.left=Math.min($.left,J),$.top=Math.min($.top,K),$.width=Math.min($.width,J-$.left),$.height=Math.min($.height,K-$.top),H($.width>=0),H($.height>=0)},b8=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},S8=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class A0{get microsecondTimestamp(){return Math.trunc(G0*this.timestamp)}get microsecondDuration(){return Math.trunc(G0*this.duration)}constructor($){if(this._closed=!1,N1($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!S8.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(V1($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let K;if($.data instanceof ArrayBuffer)K=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))K=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let Y=this.numberOfFrames*this.numberOfChannels*V1(this.format);if(K.byteLength<Y)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=K}}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!S8.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,K=$.frameOffset??0;if(K>=this.numberOfFrames)throw RangeError("frameOffset out of range");let Y=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-K;if(Y>this.numberOfFrames-K)throw RangeError("frameCount out of range");let Z=V1(J),X=d1(J);if(X&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!X&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(X?Y:Y*this.numberOfChannels)*Z}copyTo($,J){if(!B1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!S8.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:K,format:Y,frameCount:Z,frameOffset:X}=J,Q=Y??this.format;if(!Q)throw Error("Destination format not determined");let W=this.numberOfFrames,G=this.numberOfChannels,U=X??0;if(U>=W)throw RangeError("frameOffset out of range");let q=Z!==void 0?Z:W-U;if(q>W-U)throw RangeError("frameCount out of range");let j=V1(Q),V=d1(Q);if(V&&K>=G)throw RangeError("planeIndex out of range");if(!V&&K!==0)throw RangeError("planeIndex out of range");let A=(V?q:q*G)*j;if($.byteLength<A)throw RangeError("Destination buffer is too small");let R=E($),z=WY(Q);if(N1(this._data))if(V)if(Q==="f32-planar")this._data.copyTo($,{planeIndex:K,frameOffset:U,frameCount:q,format:"f32-planar"});else{let O=new ArrayBuffer(q*4),F=new Float32Array(O);this._data.copyTo(F,{planeIndex:K,frameOffset:U,frameCount:q,format:"f32-planar"});let _=new DataView(O);for(let w=0;w<q;w++){let P=w*j,D=_.getFloat32(w*4,!0);z(R,P,D)}}else{let O=G,F=new Float32Array(q);for(let _=0;_<O;_++){this._data.copyTo(F,{planeIndex:_,frameOffset:U,frameCount:q,format:"f32-planar"});for(let w=0;w<q;w++){let D=(w*O+_)*j;z(R,D,F[w])}}}else{let O=this._data,F=new DataView(O.buffer,O.byteOffset,O.byteLength),_=this.format,w=QY(_),P=V1(_),D=d1(_);for(let L=0;L<q;L++)if(V){let h=L*j,o;if(D)o=(K*W+(L+U))*P;else o=((L+U)*G+K)*P;let I=w(F,o);z(R,h,I)}else for(let h=0;h<G;h++){let I=(L*G+h)*j,x;if(D)x=(h*W+(L+U))*P;else x=((L+U)*G+h)*P;let v0=w(F,x);z(R,I,v0)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(N1(this._data)){let $=new A0(this._data.clone());return $.setTimestamp(this.timestamp),$}else return new A0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){if(this._closed)return;if(N1(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(N1(this._data))if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();else if(d1(this.format)){let $=this.allocationSize({planeIndex:0,format:this.format}),J=new ArrayBuffer($*this.numberOfChannels);for(let K=0;K<this.numberOfChannels;K++)this.copyTo(new Uint8Array(J,K*$,$),{planeIndex:K,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:J})}else{let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data})}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let K=0;K<this.numberOfChannels;K++)this.copyTo(J,{planeIndex:K,format:"f32-planar"}),$.copyToChannel(J,K);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let K=240000,Y=$.numberOfChannels,Z=$.sampleRate,X=$.length,Q=Math.floor(K/Y),W=0,G=X;while(G>0){let U=Math.min(Q,G),q=new Float32Array(Y*U);for(let j=0;j<Y;j++)$.copyFromChannel(q.subarray(j*U,(j+1)*U),j,W);yield new A0({format:"f32-planar",sampleRate:Z,numberOfFrames:U,numberOfChannels:Y,timestamp:J+W/Z,data:q}),W+=U,G-=U}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let K=240000,Y=$.numberOfChannels,Z=$.sampleRate,X=$.length,Q=Math.floor(K/Y),W=0,G=X,U=[];while(G>0){let q=Math.min(Q,G),j=new Float32Array(Y*q);for(let N=0;N<Y;N++)$.copyFromChannel(j.subarray(N*q,(N+1)*q),N,W);let V=new A0({format:"f32-planar",sampleRate:Z,numberOfFrames:q,numberOfChannels:Y,timestamp:J+W/Z,data:j});U.push(V),W+=q,G-=q}return U}}var V1=($)=>{switch($){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 Error("Unknown AudioSampleFormat")}},d1=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},QY=($)=>{switch($){case"u8":case"u8-planar":return(J,K)=>(J.getUint8(K)-128)/128;case"s16":case"s16-planar":return(J,K)=>J.getInt16(K,!0)/32768;case"s32":case"s32-planar":return(J,K)=>J.getInt32(K,!0)/2147483648;case"f32":case"f32-planar":return(J,K)=>J.getFloat32(K,!0)}},WY=($)=>{switch($){case"u8":case"u8-planar":return(J,K,Y)=>J.setUint8(K,x0((Y+1)*127.5,0,255));case"s16":case"s16-planar":return(J,K,Y)=>J.setInt16(K,x0(Math.round(Y*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,K,Y)=>J.setInt32(K,x0(Math.round(Y*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,K,Y)=>J.setFloat32(K,Y,!0)}},N1=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};/*!
|
|
56
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
57
|
+
*
|
|
58
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
59
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
60
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
61
|
+
*/var c0=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.metadataOnly!==void 0&&typeof $.metadataOnly!=="boolean")throw TypeError("options.metadataOnly, when defined, must be a boolean.");if($.verifyKeyPackets!==void 0&&typeof $.verifyKeyPackets!=="boolean")throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if($.verifyKeyPackets&&$.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},O0=($)=>{if(!M0($))throw TypeError("timestamp must be a number.")},f8=($,J,K)=>{if(K.verifyKeyPackets)return J.then(async(Y)=>{if(!Y||Y.type==="delta")return Y;let Z=await $.determinePacketType(Y);if(Z)Y.type=Z;return Y});else return J};class o0{constructor($){if(!($ instanceof A1))throw TypeError("track must be an InputTrack.");this._track=$}getFirstPacket($={}){if(c0($),this._track.input._disposed)throw new c;return f8(this._track,this._track._backing.getFirstPacket($),$)}getPacket($,J={}){if(O0($),c0(J),this._track.input._disposed)throw new c;return f8(this._track,this._track._backing.getPacket($,J),J)}getNextPacket($,J={}){if(!($ instanceof f))throw TypeError("packet must be an EncodedPacket.");if(c0(J),this._track.input._disposed)throw new c;return f8(this._track,this._track._backing.getNextPacket($,J),J)}async getKeyPacket($,J={}){if(O0($),c0(J),this._track.input._disposed)throw new c;if(!J.verifyKeyPackets)return this._track._backing.getKeyPacket($,J);let K=await this._track._backing.getKeyPacket($,J);if(!K||K.type==="delta")return K;if(await this._track.determinePacketType(K)==="delta")return this.getKeyPacket(K.timestamp-1/this._track.timeResolution,J);return K}async getNextKeyPacket($,J={}){if(!($ instanceof f))throw TypeError("packet must be an EncodedPacket.");if(c0(J),this._track.input._disposed)throw new c;if(!J.verifyKeyPackets)return this._track._backing.getNextKeyPacket($,J);let K=await this._track._backing.getNextKeyPacket($,J);if(!K||K.type==="delta")return K;if(await this._track.determinePacketType(K)==="delta")return this.getNextKeyPacket(K,J);return K}packets($,J,K={}){if($!==void 0&&!($ instanceof f))throw TypeError("startPacket must be an EncodedPacket.");if($!==void 0&&$.isMetadataOnly&&!K?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(J!==void 0&&!(J instanceof f))throw TypeError("endPacket must be an EncodedPacket.");if(c0(K),this._track.input._disposed)throw new c;let Y=[],{promise:Z,resolve:X}=n(),{promise:Q,resolve:W}=n(),G=!1,U=!1,q=null,j=[],V=()=>Math.max(2,j.length);(async()=>{let A=$??await this.getFirstPacket(K);while(A&&!U&&!this._track.input._disposed){if(J&&A.sequenceNumber>=J?.sequenceNumber)break;if(Y.length>V()){({promise:Q,resolve:W}=n()),await Q;continue}Y.push(A),X(),{promise:Z,resolve:X}=n(),A=await this.getNextPacket(A,K)}G=!0,X()})().catch((A)=>{if(!q)q=A,X()});let N=this._track;return{async next(){while(!0)if(N.input._disposed)throw new c;else if(U)return{value:void 0,done:!0};else if(q)throw q;else if(Y.length>0){let A=Y.shift(),R=performance.now();j.push(R);while(j.length>0&&R-j[0]>=1000)j.shift();return W(),{value:A,done:!1}}else if(G)return{value:void 0,done:!0};else await Z},async return(){return U=!0,W(),X(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this}}}}class c1{constructor($,J){this.onSample=$,this.onError=J}}class o1{mediaSamplesInRange($=0,J=1/0){O0($),O0(J);let K=[],Y=!1,Z=null,{promise:X,resolve:Q}=n(),{promise:W,resolve:G}=n(),U=!1,q=!1,j=!1,V=null;(async()=>{let R=Error(),z=await this._createDecoder((D)=>{if(G(),D.timestamp>=J)q=!0;if(q){D.close();return}if(Z)if(D.timestamp>$)K.push(Z),Y=!0;else Z.close();if(D.timestamp>=$)K.push(D),Y=!0;if(Z=Y?null:D,K.length>0)Q(),{promise:X,resolve:Q}=n()},(D)=>{if(!V)D.stack=R.stack,V=D,Q()}),O=this._createPacketSink(),F=await O.getKeyPacket($,{verifyKeyPackets:!0})??await O.getFirstPacket();if(!F)return;let _=F,w=void 0;if(J<1/0){let D=await O.getPacket(J),L=!D?null:D.type==="key"&&D.timestamp===J?D:await O.getNextKeyPacket(D,{verifyKeyPackets:!0});if(L)w=L}let P=O.packets(F,w);await P.next();while(_&&!q&&!this._track.input._disposed){let D=g$(K.length);if(K.length+z.getDecodeQueueSize()>D){({promise:W,resolve:G}=n()),await W;continue}z.decode(_);let L=await P.next();if(L.done)break;_=L.value}if(await P.return(),!j&&!this._track.input._disposed)await z.flush();if(z.close(),!Y&&Z)K.push(Z);U=!0,Q()})().catch((R)=>{if(!V)V=R,Q()});let N=this._track,A=()=>{Z?.close();for(let R of K)R.close()};return{async next(){while(!0)if(N.input._disposed)throw A(),new c;else if(j)return{value:void 0,done:!0};else if(V)throw A(),V;else if(K.length>0){let R=K.shift();return G(),{value:R,done:!1}}else if(!U)await X;else return{value:void 0,done:!0}},async return(){return j=!0,q=!0,G(),Q(),A(),{value:void 0,done:!0}},async throw(R){throw R},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps($){C$($);let J=_$($),K=[],Y=[],{promise:Z,resolve:X}=n(),{promise:Q,resolve:W}=n(),G=!1,U=!1,q=null,j=(A)=>{Y.push(A),X(),{promise:Z,resolve:X}=n()};(async()=>{let A=Error(),R=await this._createDecoder((D)=>{if(W(),U){D.close();return}let L=0;while(K.length>0&&D.timestamp-K[0]>-0.0000000001)L++,K.shift();if(L>0)for(let h=0;h<L;h++)j(h<L-1?D.clone():D);else D.close()},(D)=>{if(!q)D.stack=A.stack,q=D,X()}),z=this._createPacketSink(),O=null,F=null,_=-1,w=async()=>{H(F);let D=F;R.decode(D);while(D.sequenceNumber<_){let L=g$(Y.length);while(Y.length+R.getDecodeQueueSize()>L&&!U)({promise:Q,resolve:W}=n()),await Q;if(U)break;let h=await z.getNextPacket(D);H(h),R.decode(h),D=h}_=-1},P=async()=>{await R.flush();for(let D=0;D<K.length;D++)j(null);K.length=0};for await(let D of J){if(O0(D),U||this._track.input._disposed)break;let L=await z.getPacket(D),h=L&&await z.getKeyPacket(D,{verifyKeyPackets:!0});if(!h){if(_!==-1)await w(),await P();j(null),O=null;continue}if(O&&(h.sequenceNumber!==F.sequenceNumber||L.timestamp<O.timestamp))await w(),await P();K.push(L.timestamp),_=Math.max(L.sequenceNumber,_),O=L,F=h}if(!U&&!this._track.input._disposed){if(_!==-1)await w();await P()}R.close(),G=!0,X()})().catch((A)=>{if(!q)q=A,X()});let V=this._track,N=()=>{for(let A of Y)A?.close()};return{async next(){while(!0)if(V.input._disposed)throw N(),new c;else if(U)return{value:void 0,done:!0};else if(q)throw N(),q;else if(Y.length>0){let A=Y.shift();return H(A!==void 0),W(),{value:A,done:!1}}else if(!G)await Z;else return{value:void 0,done:!0}},async return(){return U=!0,W(),X(),N(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this}}}}var g$=($)=>{return $===0?40:8};class u$ extends c1{constructor($,J,K,Y,Z,X){super($,J);this.codec=K,this.decoderConfig=Y,this.rotation=Z,this.timeResolution=X,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new h1,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.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let Q=m1.find((W)=>W.supports(K,Y));if(Q)this.customDecoder=new Q,this.customDecoder.codec=K,this.customDecoder.config=Y,this.customDecoder.onSample=(W)=>{if(!(W instanceof H0))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(W)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let W=(G)=>{if(this.alphaQueue.length>0){let U=this.alphaQueue.shift();H(U!==void 0),this.mergeAlpha(G,U)}else this.colorQueue.push(G)};this.decoder=new VideoDecoder({output:(G)=>{try{W(G)}catch(U){this.onError(U)}},error:J}),this.decoder.configure(Y)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return H(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)}decode($){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture($.data))return;this.raslSkipped=!0}if(this.currentPacketIndex++,this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else{if(H(this.decoder),!x1())M8(this.inputTimestamps,$.timestamp,(J)=>J);this.decoder.decode($.toEncodedVideoChunk()),this.decodeAlphaData($)}}decodeAlphaData($){if(!$.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new p$}catch(K){console.error("Due to an error, only color data will be decoded.",K),this.mergerCreationFailed=!0,this.decodeAlphaData($);return}if(!this.alphaDecoder){let K=(Y)=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let Z=this.colorQueue.shift();H(Z!==void 0),this.mergeAlpha(Z,Y)}else this.alphaQueue.push(Y);this.decodedAlphaChunkCount++;while(this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let Z=this.colorQueue.shift();H(Z!==void 0),this.mergeAlpha(Z,null)}else this.alphaQueue.push(null)};this.alphaDecoder=new VideoDecoder({output:(Y)=>{try{K(Y)}catch(Z){this.onError(Z)}},error:this.onError}),this.alphaDecoder.configure(this.decoderConfig)}let J=p1(this.codec,this.decoderConfig,$.sideData.alpha);if(!this.alphaHadKeyframe)this.alphaHadKeyframe=J==="key";if(this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture($.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode($.alphaToEncodedVideoChunk(J??$.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){if(this.alphaDecoderQueueSize===0)this.alphaQueue.push(null);else this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture($){return y8($,this.decoderConfig).some((K)=>{let Y=V0(K);return Y===i.RASL_N||Y===i.RASL_R})}sampleHandler($){if(x1()){if(this.sampleQueue.length>0&&$.timestamp>=r(this.sampleQueue).timestamp){for(let J of this.sampleQueue)this.finalizeAndEmitSample(J);this.sampleQueue.length=0}M8(this.sampleQueue,$,(J)=>J.timestamp)}else{let J=this.inputTimestamps.shift();H(J!==void 0),$.setTimestamp(J),this.finalizeAndEmitSample($)}}finalizeAndEmitSample($){$.setTimestamp(Math.round($.timestamp*this.timeResolution)/this.timeResolution),$.setDuration(Math.round($.duration*this.timeResolution)/this.timeResolution),$.setRotation(this.rotation),this.onSample($)}mergeAlpha($,J){if(!J){let Z=new H0($);this.sampleHandler(Z);return}H(this.merger),this.merger.update($,J),$.close(),J.close();let K=new VideoFrame(this.merger.canvas,{timestamp:$.timestamp,duration:$.duration??void 0}),Y=new H0(K);this.sampleHandler(Y)}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else H(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;if(x1()){for(let $ of this.sampleQueue)this.finalizeAndEmitSample($);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else H(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.merger?.close();for(let $ of this.sampleQueue)$.close();this.sampleQueue.length=0}}class p${constructor(){if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas(300,150);else this.canvas=document.createElement("canvas");let $=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!$)throw Error("Couldn't acquire WebGL 2 context.");this.gl=$,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){let $=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
62
|
+
in vec2 a_position;
|
|
63
|
+
in vec2 a_texCoord;
|
|
64
|
+
out vec2 v_texCoord;
|
|
65
|
+
|
|
66
|
+
void main() {
|
|
67
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
68
|
+
v_texCoord = a_texCoord;
|
|
69
|
+
}
|
|
70
|
+
`),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
71
|
+
precision highp float;
|
|
72
|
+
|
|
73
|
+
uniform sampler2D u_colorTexture;
|
|
74
|
+
uniform sampler2D u_alphaTexture;
|
|
75
|
+
in vec2 v_texCoord;
|
|
76
|
+
out vec4 fragColor;
|
|
77
|
+
|
|
78
|
+
void main() {
|
|
79
|
+
vec3 color = texture(u_colorTexture, v_texCoord).rgb;
|
|
80
|
+
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
81
|
+
fragColor = vec4(color, alpha);
|
|
82
|
+
}
|
|
83
|
+
`),K=this.gl.createProgram();return this.gl.attachShader(K,$),this.gl.attachShader(K,J),this.gl.linkProgram(K),K}createShader($,J){let K=this.gl.createShader($);return this.gl.shaderSource(K,J),this.gl.compileShader(K),K}createVAO(){let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),K=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,K),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let Y=this.gl.getAttribLocation(this.program,"a_position"),Z=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(Y),this.gl.vertexAttribPointer(Y,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(Z),this.gl.vertexAttribPointer(Z,2,this.gl.FLOAT,!1,16,8),$}createTexture(){let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),$}update($,J){if($.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.displayHeight;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,J),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class I8 extends o1{constructor($){if(!($ instanceof R0))throw TypeError("videoTrack must be an InputVideoTrack.");super();this._track=$}async _createDecoder($,J){if(!await this._track.canDecode())throw Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let K=this._track.codec,Y=this._track.rotation,Z=await this._track.getDecoderConfig(),X=this._track.timeResolution;return H(K&&Z),new u$($,J,K,Z,Y,X)}_createPacketSink(){return new o0(this._track)}async getSample($){O0($);for await(let J of this.mediaSamplesAtTimestamps([$]))return J;throw Error("Internal error: Iterator returned nothing.")}samples($=0,J=1/0){return this.mediaSamplesInRange($,J)}samplesAtTimestamps($){return this.mediaSamplesAtTimestamps($)}}class n1{constructor($,J={}){if(this._nextCanvasIndex=0,!($ instanceof R0))throw TypeError("videoTrack must be an InputVideoTrack.");if(J&&typeof J!=="object")throw TypeError("options must be an object.");if(J.alpha!==void 0&&typeof J.alpha!=="boolean")throw TypeError("options.alpha, when provided, must be a boolean.");if(J.width!==void 0&&(!Number.isInteger(J.width)||J.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(J.height!==void 0&&(!Number.isInteger(J.height)||J.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(J.fit!==void 0&&!["fill","contain","cover"].includes(J.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(J.width!==void 0&&J.height!==void 0&&J.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(J.crop!==void 0)b8(J.crop,"options.");if(J.poolSize!==void 0&&(typeof J.poolSize!=="number"||!Number.isInteger(J.poolSize)||J.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");let K=J.rotation??$.rotation,[Y,Z]=K%180===0?[$.codedWidth,$.codedHeight]:[$.codedHeight,$.codedWidth],X=J.crop;if(X)E8(X,Y,Z);let[Q,W]=X?[X.width,X.height]:[Y,Z],G=Q/W;if(J.width!==void 0&&J.height===void 0)Q=J.width,W=Math.round(Q/G);else if(J.width===void 0&&J.height!==void 0)W=J.height,Q=Math.round(W*G);else if(J.width!==void 0&&J.height!==void 0)Q=J.width,W=J.height;this._videoTrack=$,this._alpha=J.alpha??!1,this._width=Q,this._height=W,this._rotation=K,this._crop=X,this._fit=J.fit??"fill",this._videoSampleSink=new I8($),this._canvasPool=Array.from({length:J.poolSize??0},()=>null)}_videoSampleToWrappedCanvas($){let J=this._canvasPool[this._nextCanvasIndex],K=!1;if(!J){if(typeof document<"u")J=document.createElement("canvas"),J.width=this._width,J.height=this._height;else J=new OffscreenCanvas(this._width,this._height);if(this._canvasPool.length>0)this._canvasPool[this._nextCanvasIndex]=J;K=!0}if(this._canvasPool.length>0)this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length;let Y=J.getContext("2d",{alpha:this._alpha||G1()});if(H(Y),Y.resetTransform(),!K)if(!this._alpha&&G1())Y.fillStyle="black",Y.fillRect(0,0,this._width,this._height);else Y.clearRect(0,0,this._width,this._height);$.drawWithFit(Y,{fit:this._fit,rotation:this._rotation,crop:this._crop});let Z={canvas:J,timestamp:$.timestamp,duration:$.duration};return $.close(),Z}async getCanvas($){O0($);let J=await this._videoSampleSink.getSample($);return J&&this._videoSampleToWrappedCanvas(J)}canvases($=0,J=1/0){return W1(this._videoSampleSink.samples($,J),(K)=>this._videoSampleToWrappedCanvas(K))}canvasesAtTimestamps($){return W1(this._videoSampleSink.samplesAtTimestamps($),(J)=>J&&this._videoSampleToWrappedCanvas(J))}}class m$ extends c1{constructor($,J,K,Y){super($,J);this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new h1,this.customDecoderQueueSize=0,this.currentTimestamp=null;let Z=(Q)=>{if(this.currentTimestamp===null||Math.abs(Q.timestamp-this.currentTimestamp)>=Q.duration)this.currentTimestamp=Q.timestamp;let W=this.currentTimestamp;if(this.currentTimestamp+=Q.duration,Q.numberOfFrames===0){Q.close();return}let G=Y.sampleRate;Q.setTimestamp(Math.round(W*G)/G),$(Q)},X=l1.find((Q)=>Q.supports(K,Y));if(X)this.customDecoder=new X,this.customDecoder.codec=K,this.customDecoder.config=Y,this.customDecoder.onSample=(Q)=>{if(!(Q instanceof A0))throw TypeError("The argument passed to onSample must be an AudioSample.");Z(Q)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else this.decoder=new AudioDecoder({output:(Q)=>{try{Z(new A0(Q))}catch(W){this.onError(W)}},error:J}),this.decoder.configure(Y)}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return H(this.decoder),this.decoder.decodeQueueSize}decode($){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else H(this.decoder),this.decoder.decode($.toEncodedAudioChunk())}flush(){if(this.customDecoder)return this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else return H(this.decoder),this.decoder.flush()}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else H(this.decoder),this.decoder.close()}}class l$ extends c1{constructor($,J,K){super($,J);this.decoderConfig=K,this.currentTimestamp=null,H(j0.includes(K.codec)),this.codec=K.codec;let{dataType:Y,sampleSize:Z,littleEndian:X}=f1(this.codec);switch(this.inputSampleSize=Z,Z){case 1:if(Y==="unsigned")this.readInputValue=(Q,W)=>Q.getUint8(W)-128;else if(Y==="signed")this.readInputValue=(Q,W)=>Q.getInt8(W);else if(Y==="ulaw")this.readInputValue=(Q,W)=>I$(Q.getUint8(W));else if(Y==="alaw")this.readInputValue=(Q,W)=>k$(Q.getUint8(W));else H(!1);break;case 2:if(Y==="unsigned")this.readInputValue=(Q,W)=>Q.getUint16(W,X)-32768;else if(Y==="signed")this.readInputValue=(Q,W)=>Q.getInt16(W,X);else H(!1);break;case 3:if(Y==="unsigned")this.readInputValue=(Q,W)=>h0(Q,W,X)-8388608;else if(Y==="signed")this.readInputValue=(Q,W)=>D$(Q,W,X);else H(!1);break;case 4:if(Y==="unsigned")this.readInputValue=(Q,W)=>Q.getUint32(W,X)-2147483648;else if(Y==="signed")this.readInputValue=(Q,W)=>Q.getInt32(W,X);else if(Y==="float")this.readInputValue=(Q,W)=>Q.getFloat32(W,X);else H(!1);break;case 8:if(Y==="float")this.readInputValue=(Q,W)=>Q.getFloat64(W,X);else H(!1);break;default:W0(Z),H(!1)}switch(Z){case 1:if(Y==="ulaw"||Y==="alaw")this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(Q,W,G)=>Q.setInt16(W,G,!0);else this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(Q,W,G)=>Q.setUint8(W,G+128);break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(Q,W,G)=>Q.setInt16(W,G,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(Q,W,G)=>Q.setInt32(W,G<<8,!0);break;case 4:if(this.outputSampleSize=4,Y==="float")this.outputFormat="f32",this.writeOutputValue=(Q,W,G)=>Q.setFloat32(W,G,!0);else this.outputFormat="s32",this.writeOutputValue=(Q,W,G)=>Q.setInt32(W,G,!0);break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(Q,W,G)=>Q.setFloat32(W,G,!0);break;default:W0(Z),H(!1)}}getDecodeQueueSize(){return 0}decode($){let J=E($.data),K=$.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,Y=K*this.decoderConfig.numberOfChannels*this.outputSampleSize,Z=new ArrayBuffer(Y),X=new DataView(Z);for(let U=0;U<K*this.decoderConfig.numberOfChannels;U++){let q=U*this.inputSampleSize,j=U*this.outputSampleSize,V=this.readInputValue(J,q);this.writeOutputValue(X,j,V)}let Q=K/this.decoderConfig.sampleRate;if(this.currentTimestamp===null||Math.abs($.timestamp-this.currentTimestamp)>=Q)this.currentTimestamp=$.timestamp;let W=this.currentTimestamp;this.currentTimestamp+=Q;let G=new A0({format:this.outputFormat,data:Z,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:K,timestamp:W});this.onSample(G)}async flush(){}close(){}}class k8 extends o1{constructor($){if(!($ instanceof p))throw TypeError("audioTrack must be an InputAudioTrack.");super();this._track=$}async _createDecoder($,J){if(!await this._track.canDecode())throw Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let K=this._track.codec,Y=await this._track.getDecoderConfig();if(H(K&&Y),j0.includes(Y.codec))return new l$($,J,Y);else return new m$($,J,K,Y)}_createPacketSink(){return new o0(this._track)}async getSample($){O0($);for await(let J of this.mediaSamplesAtTimestamps([$]))return J;throw Error("Internal error: Iterator returned nothing.")}samples($=0,J=1/0){return this.mediaSamplesInRange($,J)}samplesAtTimestamps($){return this.mediaSamplesAtTimestamps($)}}class H1{constructor($){if(!($ instanceof p))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new k8($)}_audioSampleToWrappedArrayBuffer($){return{buffer:$.toAudioBuffer(),timestamp:$.timestamp,duration:$.duration}}async getBuffer($){O0($);let J=await this._audioSampleSink.getSample($);return J&&this._audioSampleToWrappedArrayBuffer(J)}buffers($=0,J=1/0){return W1(this._audioSampleSink.samples($,J),(K)=>this._audioSampleToWrappedArrayBuffer(K))}buffersAtTimestamps($){return W1(this._audioSampleSink.samplesAtTimestamps($),(J)=>J&&this._audioSampleToWrappedArrayBuffer(J))}}/*!
|
|
84
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
85
|
+
*
|
|
86
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
87
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
88
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
89
|
+
*/class A1{constructor($,J){this.input=$,this._backing=J}isVideoTrack(){return this instanceof R0}isAudioTrack(){return this instanceof p}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats($=1/0){let J=new o0(this),K=1/0,Y=-1/0,Z=0,X=0;for await(let Q of J.packets(void 0,void 0,{metadataOnly:!0})){if(Z>=$&&Q.timestamp>=Y)break;K=Math.min(K,Q.timestamp),Y=Math.max(Y,Q.timestamp+Q.duration),Z++,X+=Q.byteLength}return{packetCount:Z,averagePacketRate:Z?Number((Z/(Y-K)).toPrecision(16)):0,averageBitrate:Z?Number((8*X/(Y-K)).toPrecision(16)):0}}}class R0 extends A1{constructor($,J){super($,J);this._backing=J}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let $=await this._backing.getColorSpace();return $.primaries==="bt2020"||$.primaries==="smpte432"||$.transfer==="pg"||$.transfer==="hlg"||$.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=this._backing.getCodec();if(H(J!==null),m1.some((Y)=>Y.supports(J,$)))return!0;if(typeof VideoDecoder>"u")return!1;return(await VideoDecoder.isConfigSupported($)).supported===!0}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof f))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let J=await this.getDecoderConfig();return H(J),p1(this.codec,J,$.data)}}class p extends A1{constructor($,J){super($,J);this._backing=J}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=this._backing.getCodec();if(H(J!==null),l1.some((K)=>K.supports(J,$)))return!0;if($.codec.startsWith("pcm-"))return!0;else{if(typeof AudioDecoder>"u")return!1;return(await AudioDecoder.isConfigSupported($)).supported===!0}}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof f))throw TypeError("packet must be an EncodedPacket.");if(this.codec===null)return null;return"key"}}/*!
|
|
90
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
91
|
+
*
|
|
92
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
93
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
94
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
95
|
+
*/var d$=($)=>{let K=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isQuickTime?"quicktime":"mp4");if($.codecStrings.length>0){let Y=[...new Set($.codecStrings)];K+=`; codecs="${Y.join(", ")}"`}return K};/*!
|
|
96
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
97
|
+
*
|
|
98
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
99
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
100
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
101
|
+
*/var I0=8,n0=16,z0=($)=>{let J=M($),K=k($,4),Y=8;if(J===1)J=e($),Y=16;let X=J-Y;if(X<0)return null;return{name:K,totalSize:J,headerSize:Y,contentSize:X}},L0=($)=>{return F0($)/65536},r1=($)=>{return F0($)/1073741824},i1=($)=>{let J=0;for(let K=0;K<4;K++){J<<=7;let Y=T($);if(J|=Y&127,(Y&128)===0)break}return J},J0=($)=>{let J=m($);return $.skip(2),J=Math.min(J,$.remainingLength),l.decode(v($,J))},c$=($)=>{let J=z0($);if(!J||J.name!=="data")return null;let K=M($);$.skip(4);let Y=v($,J.contentSize-8);switch(K){case 1:return l.decode(Y);case 2:return new TextDecoder("utf-16be").decode(Y);case 13:return new E0(Y,"image/jpeg");case 14:return new E0(Y,"image/png");case 27:return new E0(Y,"image/bmp");default:return Y}};/*!
|
|
102
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
103
|
+
*
|
|
104
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
105
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
106
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
107
|
+
*/class u8 extends s{constructor($){super($);this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((K)=>K.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.tracks.map(($)=>$.inputTrack)}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.inputTrack.getCodecParameterString()));return d$({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((J)=>J.info?.type==="video"),hasAudio:this.tracks.some((J)=>J.info?.type==="audio"),codecStrings:$.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,I0,n0);if(J instanceof Promise)J=await J;if(!J)break;let K=$,Y=z0(J);if(!Y)break;if(Y.name==="ftyp"){let Z=k(J,4);this.isQuickTime=Z==="qt "}else if(Y.name==="moov"){let Z=this.reader.requestSlice(J.filePos,Y.contentSize);if(Z instanceof Promise)Z=await Z;if(!Z)break;this.moovSlice=Z,this.readContiguousBoxes(this.moovSlice);for(let X of this.tracks){let Q=X.editListPreviousSegmentDurations/this.movieTimescale;X.editListOffset-=Math.round(Q*X.timescale)}break}$=K+Y.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let J=this.reader.requestSlice(this.reader.fileSize-4,4);if(J instanceof Promise)J=await J;H(J);let K=M(J),Y=this.reader.fileSize-K;if(Y>=0&&Y<=this.reader.fileSize-n0){let Z=this.reader.requestSliceRange(Y,I0,n0);if(Z instanceof Promise)Z=await Z;if(Z){let X=z0(Z);if(X&&X.name==="mfra"){let Q=this.reader.requestSlice(Z.filePos,X.contentSize);if(Q instanceof Promise)Q=await Q;if(Q)this.readContiguousBoxes(Q)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};$.sampleTable=J,H(this.moovSlice);let K=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(K),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&j0.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){H($.info?.type==="audio");let Z=f1($.info.codec),X=[],Q=[];for(let W=0;W<J.sampleToChunk.length;W++){let G=J.sampleToChunk[W],U=J.sampleToChunk[W+1],q=(U?U.startChunkIndex:J.chunkOffsets.length)-G.startChunkIndex;for(let j=0;j<q;j++){let V=G.startSampleIndex+j*G.samplesPerChunk,N=V+G.samplesPerChunk,A=S(J.sampleTimingEntries,V,(L)=>L.startIndex),R=J.sampleTimingEntries[A],z=S(J.sampleTimingEntries,N,(L)=>L.startIndex),O=J.sampleTimingEntries[z],F=R.startDecodeTimestamp+(V-R.startIndex)*R.delta,w=O.startDecodeTimestamp+(N-O.startIndex)*O.delta-F,P=r(X);if(P&&P.delta===w)P.count++;else X.push({startIndex:G.startChunkIndex+j,startDecodeTimestamp:F,count:1,delta:w});let D=G.samplesPerChunk*Z.sampleSize*$.info.numberOfChannels;Q.push(D)}G.startSampleIndex=G.startChunkIndex,G.samplesPerChunk=1}J.sampleTimingEntries=X,J.sampleSizes=Q}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let Z of J.sampleTimingEntries)for(let X=0;X<Z.count;X++)J.presentationTimestamps.push({presentationTimestamp:Z.startDecodeTimestamp+X*Z.delta,sampleIndex:Z.startIndex+X});for(let Z of J.sampleCompositionTimeOffsets)for(let X=0;X<Z.count;X++){let Q=Z.startIndex+X,W=J.presentationTimestamps[Q];if(!W)continue;W.presentationTimestamp+=Z.offset}J.presentationTimestamps.sort((Z,X)=>Z.presentationTimestamp-X.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let Z=0;Z<J.presentationTimestamps.length;Z++)J.presentationTimestampIndexMap[J.presentationTimestamps[Z].sampleIndex]=Z}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,I0,n0);if(J instanceof Promise)J=await J;H(J);let K=z0(J);H(K?.name==="moof");let Y=this.reader.requestSlice($,K.totalSize);if(Y instanceof Promise)Y=await Y;H(Y),this.traverseBox(Y);let Z=this.lastReadFragment;H(Z&&Z.moofOffset===$);for(let[,X]of Z.trackData){let Q=X.track,{fragmentPositionCache:W}=Q;if(!X.startTimestampIsFinal){let U=Q.fragmentLookupTable.find((q)=>q.moofOffset===Z.moofOffset);if(U)g8(X,U.timestamp);else{let q=S(W,Z.moofOffset-1,(j)=>j.moofOffset);if(q!==-1){let j=W[q];g8(X,j.endTimestamp)}}X.startTimestampIsFinal=!0}let G=S(W,X.startTimestamp,(U)=>U.startTimestamp);if(G===-1||W[G].moofOffset!==Z.moofOffset)W.splice(G+1,0,{moofOffset:Z.moofOffset,startTimestamp:X.startTimestamp,endTimestamp:X.endTimestamp})}return Z}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-I0)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-I0){let K=$.filePos,Y=z0($);if(!Y)break;yield{boxInfo:Y,slice:$},$.filePos=K+Y.totalSize}}traverseBox($){let J=$.filePos,K=z0($);if(!K)return!1;let Y=$.filePos,Z=J+K.totalSize;switch(K.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes($.slice(Y,K.contentSize));break;case"mvhd":{let X=T($);if($.skip(3),X===1)$.skip(16),this.movieTimescale=M($),this.movieDurationInTimescale=e($);else $.skip(8),this.movieTimescale=M($),this.movieDurationInTimescale=M($)}break;case"trak":{let X={id:-1,demuxer:this,inputTrack:null,info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:d,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=X,this.readContiguousBoxes($.slice(Y,K.contentSize)),X.id!==-1&&X.timescale!==-1&&X.info!==null){if(X.info.type==="video"&&X.info.width!==-1){let Q=X;X.inputTrack=new R0(this.input,new r$(Q)),this.tracks.push(X)}else if(X.info.type==="audio"&&X.info.numberOfChannels!==-1){let Q=X;X.inputTrack=new p(this.input,new i$(Q)),this.tracks.push(X)}}this.currentTrack=null}break;case"tkhd":{let X=this.currentTrack;if(!X)break;let Q=T($);if((T0($)&1)===0)break;if(Q===0)$.skip(8),X.id=M($),$.skip(4),X.durationInMovieTimescale=M($);else if(Q===1)$.skip(16),X.id=M($),$.skip(4),X.durationInMovieTimescale=e($);else throw Error(`Incorrect track header version ${Q}.`);$.skip(16);let U=[L0($),L0($),r1($),L0($),L0($),r1($),L0($),L0($),r1($)],q=w1(w$(jY(U),90));H(q===0||q===90||q===180||q===270),X.rotation=q}break;case"elst":{let X=this.currentTrack;if(!X)break;let Q=T($);$.skip(3);let W=!1,G=0,U=M($);for(let q=0;q<U;q++){let j=Q===1?e($):M($),V=Q===1?s$($):F0($),N=L0($);if(j===0)continue;if(W){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(V===-1){G+=j;continue}if(N!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}X.editListPreviousSegmentDurations=G,X.editListOffset=V,W=!0}}break;case"mdhd":{let X=this.currentTrack;if(!X)break;let Q=T($);if($.skip(3),Q===0)$.skip(8),X.timescale=M($),X.durationInMediaTimescale=M($);else if(Q===1)$.skip(16),X.timescale=M($),X.durationInMediaTimescale=e($);let W=m($);if(W>0){X.languageCode="";for(let G=0;G<3;G++)X.languageCode=String.fromCharCode(96+(W&31))+X.languageCode,W>>=5;if(!v1(X.languageCode))X.languageCode=d}}break;case"hdlr":{let X=this.currentTrack;if(!X)break;$.skip(8);let Q=k($,4);if(Q==="vide")X.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null};else if(Q==="soun")X.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null}}break;case"stbl":{let X=this.currentTrack;if(!X)break;X.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(Y,K.contentSize))}break;case"stsd":{let X=this.currentTrack;if(!X)break;if(X.info===null||X.sampleTable)break;let Q=T($);$.skip(3);let W=M($);for(let G=0;G<W;G++){let U=$.filePos,q=z0($);if(!q)break;X.internalCodecId=q.name;let j=q.name.toLowerCase();if(X.info.type==="video"){if(j==="avc1")X.info.codec="avc";else if(j==="hvc1"||j==="hev1")X.info.codec="hevc";else if(j==="vp08")X.info.codec="vp8";else if(j==="vp09")X.info.codec="vp9";else if(j==="av01")X.info.codec="av1";else console.warn(`Unsupported video codec (sample entry type '${q.name}').`);$.skip(24),X.info.width=m($),X.info.height=m($),$.skip(50),this.readContiguousBoxes($.slice($.filePos,U+q.totalSize-$.filePos))}else{if(j==="mp4a");else if(j==="opus")X.info.codec="opus";else if(j==="flac")X.info.codec="flac";else if(j==="twos"||j==="sowt"||j==="raw "||j==="in24"||j==="in32"||j==="fl32"||j==="fl64"||j==="lpcm"||j==="ipcm"||j==="fpcm");else if(j==="ulaw")X.info.codec="ulaw";else if(j==="alaw")X.info.codec="alaw";else console.warn(`Unsupported audio codec (sample entry type '${q.name}').`);$.skip(8);let V=m($);$.skip(6);let N=m($),A=m($);$.skip(4);let R=M($)/65536;if(Q===0&&V>0){if(V===1)$.skip(4),A=8*M($),$.skip(8);else if(V===2){$.skip(4),R=s1($),N=M($),$.skip(4),A=M($);let z=M($);if($.skip(8),j==="lpcm"){let O=A+7>>3,F=Boolean(z&1),_=Boolean(z&2),w=z&4?-1:0;if(A>0&&A<=64){if(F){if(A===32)X.info.codec=_?"pcm-f32be":"pcm-f32"}else if(w&1<<O-1){if(O===1)X.info.codec="pcm-s8";else if(O===2)X.info.codec=_?"pcm-s16be":"pcm-s16";else if(O===3)X.info.codec=_?"pcm-s24be":"pcm-s24";else if(O===4)X.info.codec=_?"pcm-s32be":"pcm-s32"}else if(O===1)X.info.codec="pcm-u8"}if(X.info.codec===null)console.warn("Unsupported PCM format.")}}}if(X.info.codec==="opus")R=f0;if(X.info.numberOfChannels=N,X.info.sampleRate=R,j==="twos")if(A===8)X.info.codec="pcm-s8";else if(A===16)X.info.codec="pcm-s16be";else console.warn(`Unsupported sample size ${A} for codec 'twos'.`),X.info.codec=null;else if(j==="sowt")if(A===8)X.info.codec="pcm-s8";else if(A===16)X.info.codec="pcm-s16";else console.warn(`Unsupported sample size ${A} for codec 'sowt'.`),X.info.codec=null;else if(j==="raw ")X.info.codec="pcm-u8";else if(j==="in24")X.info.codec="pcm-s24be";else if(j==="in32")X.info.codec="pcm-s32be";else if(j==="fl32")X.info.codec="pcm-f32be";else if(j==="fl64")X.info.codec="pcm-f64be";else if(j==="ipcm")X.info.codec="pcm-s16be";else if(j==="fpcm")X.info.codec="pcm-f32be";this.readContiguousBoxes($.slice($.filePos,U+q.totalSize-$.filePos))}}}break;case"avcC":{let X=this.currentTrack;if(!X)break;H(X.info),X.info.codecDescription=v($,K.contentSize)}break;case"hvcC":{let X=this.currentTrack;if(!X)break;H(X.info),X.info.codecDescription=v($,K.contentSize)}break;case"vpcC":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="video"),$.skip(4);let Q=T($),W=T($),G=T($),U=G>>4,q=G>>1&7,j=G&1,V=T($),N=T($),A=T($);X.info.vp9CodecInfo={profile:Q,level:W,bitDepth:U,chromaSubsampling:q,videoFullRangeFlag:j,colourPrimaries:V,transferCharacteristics:N,matrixCoefficients:A}}break;case"av1C":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="video"),$.skip(1);let Q=T($),W=Q>>5,G=Q&31,U=T($),q=U>>7,j=U>>6&1,V=U>>5&1,N=U>>4&1,A=U>>3&1,R=U>>2&1,z=U&3,O=W===2&&j?V?12:10:j?10:8;X.info.av1CodecInfo={profile:W,level:G,tier:q,bitDepth:O,monochrome:N,chromaSubsamplingX:A,chromaSubsamplingY:R,chromaSamplePosition:z}}break;case"colr":{let X=this.currentTrack;if(!X)break;if(H(X.info?.type==="video"),k($,4)!=="nclx")break;let W=m($),G=m($),U=m($),q=Boolean(T($)&128);X.info.colorSpace={primaries:M1[W],transfer:L1[G],matrix:T1[U],fullRange:q}}break;case"wave":this.readContiguousBoxes($.slice(Y,K.contentSize));break;case"esds":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="audio"),$.skip(4);let Q=T($);H(Q===3),i1($),$.skip(2);let W=T($),G=(W&128)!==0,U=(W&64)!==0,q=(W&32)!==0;if(G)$.skip(2);if(U){let R=T($);$.skip(R)}if(q)$.skip(2);let j=T($);H(j===4);let V=i1($),N=$.filePos,A=T($);if(A===64||A===103)X.info.codec="aac",X.info.aacCodecInfo={isMpeg2:A===103};else if(A===105||A===107)X.info.codec="mp3";else if(A===221)X.info.codec="vorbis";else console.warn(`Unsupported audio codec (objectTypeIndication ${A}) - discarding track.`);if($.skip(12),V>$.filePos-N){let R=T($);H(R===5);let z=i1($);if(X.info.codecDescription=v($,z),X.info.codec==="aac"){let O=h8(X.info.codecDescription);if(O.numberOfChannels!==null)X.info.numberOfChannels=O.numberOfChannels;if(O.sampleRate!==null)X.info.sampleRate=O.sampleRate}}}break;case"enda":{let X=this.currentTrack;if(!X)break;if(H(X.info?.type==="audio"),m($)&255){if(X.info.codec==="pcm-s16be")X.info.codec="pcm-s16";else if(X.info.codec==="pcm-s24be")X.info.codec="pcm-s24";else if(X.info.codec==="pcm-s32be")X.info.codec="pcm-s32";else if(X.info.codec==="pcm-f32be")X.info.codec="pcm-f32";else if(X.info.codec==="pcm-f64be")X.info.codec="pcm-f64"}}break;case"pcmC":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="audio"),$.skip(4);let Q=T($),W=Boolean(Q&1),G=T($);if(X.info.codec==="pcm-s16be")if(W)if(G===16)X.info.codec="pcm-s16";else if(G===24)X.info.codec="pcm-s24";else if(G===32)X.info.codec="pcm-s32";else console.warn(`Invalid ipcm sample size ${G}.`),X.info.codec=null;else if(G===16)X.info.codec="pcm-s16be";else if(G===24)X.info.codec="pcm-s24be";else if(G===32)X.info.codec="pcm-s32be";else console.warn(`Invalid ipcm sample size ${G}.`),X.info.codec=null;else if(X.info.codec==="pcm-f32be")if(W)if(G===32)X.info.codec="pcm-f32";else if(G===64)X.info.codec="pcm-f64";else console.warn(`Invalid fpcm sample size ${G}.`),X.info.codec=null;else if(G===32)X.info.codec="pcm-f32be";else if(G===64)X.info.codec="pcm-f64be";else console.warn(`Invalid fpcm sample size ${G}.`),X.info.codec=null;break}case"dOps":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="audio"),$.skip(1);let Q=T($),W=m($),G=M($),U=O1($),q=T($),j;if(q!==0)j=v($,2+Q);else j=new Uint8Array(0);let V=new Uint8Array(19+j.byteLength),N=new DataView(V.buffer);N.setUint32(0,1332770163,!1),N.setUint32(4,1214603620,!1),N.setUint8(8,1),N.setUint8(9,Q),N.setUint16(10,W,!0),N.setUint32(12,G,!0),N.setInt16(16,U,!0),N.setUint8(18,q),V.set(j,19),X.info.codecDescription=V,X.info.numberOfChannels=Q}break;case"dfLa":{let X=this.currentTrack;if(!X)break;H(X.info?.type==="audio"),$.skip(4);let Q=127,W=128,G=$.filePos;while($.filePos<Z){let N=T($),A=T0($);if((N&Q)===N0.STREAMINFO){$.skip(10);let z=M($),O=z>>>12,F=(z>>9&7)+1;X.info.sampleRate=O,X.info.numberOfChannels=F,$.skip(20)}else $.skip(A);if(N&W)break}let U=$.filePos;$.filePos=G;let q=v($,U-G),j=new Uint8Array(4+q.byteLength);new DataView(j.buffer).setUint32(0,1716281667,!1),j.set(q,4),X.info.codecDescription=j}break;case"stts":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($),W=0,G=0;for(let U=0;U<Q;U++){let q=M($),j=M($);X.sampleTable.sampleTimingEntries.push({startIndex:W,startDecodeTimestamp:G,count:q,delta:j}),W+=q,G+=q*j}}break;case"ctts":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($),W=0;for(let G=0;G<Q;G++){let U=M($),q=F0($);X.sampleTable.sampleCompositionTimeOffsets.push({startIndex:W,count:U,offset:q}),W+=U}}break;case"stsz":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($),W=M($);if(Q===0)for(let G=0;G<W;G++){let U=M($);X.sampleTable.sampleSizes.push(U)}else X.sampleTable.sampleSizes.push(Q)}break;case"stz2":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4),$.skip(3);let Q=T($),W=M($),G=v($,Math.ceil(W*Q/8)),U=new b(G);for(let q=0;q<W;q++){let j=U.readBits(Q);X.sampleTable.sampleSizes.push(j)}}break;case"stss":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4),X.sampleTable.keySampleIndices=[];let Q=M($);for(let W=0;W<Q;W++){let G=M($)-1;X.sampleTable.keySampleIndices.push(G)}if(X.sampleTable.keySampleIndices[0]!==0)X.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($);for(let G=0;G<Q;G++){let U=M($)-1,q=M($),j=M($);X.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:U,samplesPerChunk:q,sampleDescriptionIndex:j})}let W=0;for(let G=0;G<X.sampleTable.sampleToChunk.length;G++)if(X.sampleTable.sampleToChunk[G].startSampleIndex=W,G<X.sampleTable.sampleToChunk.length-1){let q=X.sampleTable.sampleToChunk[G+1].startChunkIndex-X.sampleTable.sampleToChunk[G].startChunkIndex;W+=q*X.sampleTable.sampleToChunk[G].samplesPerChunk}}break;case"stco":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($);for(let W=0;W<Q;W++){let G=M($);X.sampleTable.chunkOffsets.push(G)}}break;case"co64":{let X=this.currentTrack;if(!X)break;if(!X.sampleTable)break;$.skip(4);let Q=M($);for(let W=0;W<Q;W++){let G=e($);X.sampleTable.chunkOffsets.push(G)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(Y,K.contentSize));break;case"mehd":{let X=T($);$.skip(3);let Q=X===1?e($):M($);this.movieDurationInTimescale=Q}break;case"trex":{$.skip(4);let X=M($),Q=M($),W=M($),G=M($),U=M($);this.fragmentTrackDefaults.push({trackId:X,defaultSampleDescriptionIndex:Q,defaultSampleDuration:W,defaultSampleSize:G,defaultSampleFlags:U})}break;case"tfra":{let X=T($);$.skip(3);let Q=M($),W=this.tracks.find((O)=>O.id===Q);if(!W)break;let G=M($),U=(G&48)>>4,q=(G&12)>>2,j=G&3,V=[T,m,T0,M],N=V[U],A=V[q],R=V[j],z=M($);for(let O=0;O<z;O++){let F=X===1?e($):M($),_=X===1?e($):M($);N($),A($),R($),W.fragmentLookupTable.push({timestamp:F,moofOffset:_})}W.fragmentLookupTable.sort((O,F)=>O.timestamp-F.timestamp);for(let O=0;O<W.fragmentLookupTable.length-1;O++){let F=W.fragmentLookupTable[O],_=W.fragmentLookupTable[O+1];if(F.timestamp===_.timestamp)W.fragmentLookupTable.splice(O+1,1),O--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:K.totalSize,implicitBaseDataOffset:J,trackData:new Map},this.readContiguousBoxes($.slice(Y,K.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(H(this.currentFragment),this.readContiguousBoxes($.slice(Y,K.contentSize)),this.currentTrack){let X=this.currentFragment.trackData.get(this.currentTrack.id);if(X){let{currentFragmentState:Q}=this.currentTrack;if(H(Q),Q.startTimestamp!==null)g8(X,Q.startTimestamp),X.startTimestampIsFinal=!0}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{H(this.currentFragment),$.skip(1);let X=T0($),Q=Boolean(X&1),W=Boolean(X&2),G=Boolean(X&8),U=Boolean(X&16),q=Boolean(X&32),j=Boolean(X&65536),V=Boolean(X&131072),N=M($),A=this.tracks.find((z)=>z.id===N);if(!A)break;let R=this.fragmentTrackDefaults.find((z)=>z.trackId===N);if(this.currentTrack=A,A.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:R?.defaultSampleDescriptionIndex??null,defaultSampleDuration:R?.defaultSampleDuration??null,defaultSampleSize:R?.defaultSampleSize??null,defaultSampleFlags:R?.defaultSampleFlags??null,startTimestamp:null},Q)A.currentFragmentState.baseDataOffset=e($);else if(V)A.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(W)A.currentFragmentState.sampleDescriptionIndex=M($);if(G)A.currentFragmentState.defaultSampleDuration=M($);if(U)A.currentFragmentState.defaultSampleSize=M($);if(q)A.currentFragmentState.defaultSampleFlags=M($);if(j)A.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let X=this.currentTrack;if(!X)break;H(X.currentFragmentState);let Q=T($);$.skip(3);let W=Q===0?M($):e($);X.currentFragmentState.startTimestamp=W}break;case"trun":{let X=this.currentTrack;if(!X)break;if(H(this.currentFragment),H(X.currentFragmentState),this.currentFragment.trackData.has(X.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let Q=T($),W=T0($),G=Boolean(W&1),U=Boolean(W&4),q=Boolean(W&256),j=Boolean(W&512),V=Boolean(W&1024),N=Boolean(W&2048),A=M($),R=X.currentFragmentState.baseDataOffset;if(G)R+=F0($);let z=null;if(U)z=M($);let O=R;if(A===0){this.currentFragment.implicitBaseDataOffset=O;break}let F=0,_={track:X,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(X.id,_);for(let D=0;D<A;D++){let L;if(q)L=M($);else H(X.currentFragmentState.defaultSampleDuration!==null),L=X.currentFragmentState.defaultSampleDuration;let h;if(j)h=M($);else H(X.currentFragmentState.defaultSampleSize!==null),h=X.currentFragmentState.defaultSampleSize;let o;if(V)o=M($);else H(X.currentFragmentState.defaultSampleFlags!==null),o=X.currentFragmentState.defaultSampleFlags;if(D===0&&z!==null)o=z;let I=0;if(N)if(Q===0)I=M($);else I=F0($);let x=!(o&65536);_.samples.push({presentationTimestamp:F+I,duration:L,byteOffset:O,byteSize:h,isKeyFrame:x}),O+=h,F+=L}_.presentationTimestamps=_.samples.map((D,L)=>({presentationTimestamp:D.presentationTimestamp,sampleIndex:L})).sort((D,L)=>D.presentationTimestamp-L.presentationTimestamp);for(let D=0;D<_.presentationTimestamps.length;D++){let L=_.presentationTimestamps[D],h=_.samples[L.sampleIndex];if(_.firstKeyFrameTimestamp===null&&h.isKeyFrame)_.firstKeyFrameTimestamp=h.presentationTimestamp;if(D<_.presentationTimestamps.length-1){let o=_.presentationTimestamps[D+1];h.duration=o.presentationTimestamp-L.presentationTimestamp}}let w=_.samples[_.presentationTimestamps[0].sampleIndex],P=_.samples[r(_.presentationTimestamps).sampleIndex];_.startTimestamp=w.presentationTimestamp,_.endTimestamp=P.presentationTimestamp+P.duration,this.currentFragment.implicitBaseDataOffset=O}break;case"udta":{let X=this.iterateContiguousBoxes($.slice(Y,K.contentSize));for(let{boxInfo:Q,slice:W}of X){if(Q.name!=="meta"&&!this.currentTrack){let G=W.filePos;if(this.metadataTags.raw??={},Q.name[0]==="©")this.metadataTags.raw[Q.name]??=J0(W);else this.metadataTags.raw[Q.name]??=v(W,Q.contentSize);W.filePos=G}switch(Q.name){case"meta":W.skip(-Q.headerSize),this.traverseBox(W);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=l.decode(v(W,Q.contentSize));else this.metadataTags.title??=J0(W);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=J0(W);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=J0(W);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=J0(W);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=J0(W);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=J0(W);break;case"©day":if(!this.currentTrack){let G=new Date(J0(W));if(!Number.isNaN(G.getTime()))this.metadataTags.date??=G}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=J0(W);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=J0(W);break}}}break;case"meta":{if(this.currentTrack)break;let Q=M($)!==0;if(this.currentMetadataKeys=new Map,Q)this.readContiguousBoxes($.slice(Y,K.contentSize));else this.readContiguousBoxes($.slice(Y+4,K.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let X=M($);for(let Q=0;Q<X;Q++){let W=M($);$.skip(4);let G=l.decode(v($,W-8));this.currentMetadataKeys.set(Q+1,G)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let X=this.iterateContiguousBoxes($.slice(Y,K.contentSize));for(let{boxInfo:Q,slice:W}of X){let G=Q.name,U=(G.charCodeAt(0)<<24)+(G.charCodeAt(1)<<16)+(G.charCodeAt(2)<<8)+G.charCodeAt(3);if(this.currentMetadataKeys.has(U))G=this.currentMetadataKeys.get(U);let q=c$(W);switch(this.metadataTags.raw??={},this.metadataTags.raw[G]??=q,G){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof q==="string")this.metadataTags.title??=q;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof q==="string")this.metadataTags.description??=q;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof q==="string")this.metadataTags.artist??=q;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof q==="string")this.metadataTags.album??=q;break;case"aART":case"album_artist":if(typeof q==="string")this.metadataTags.albumArtist??=q;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof q==="string")this.metadataTags.comment??=q;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof q==="string")this.metadataTags.genre??=q;break;case"©lyr":case"lyrics":if(typeof q==="string")this.metadataTags.lyrics??=q;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof q==="string"){let j=new Date(q);if(!Number.isNaN(j.getTime()))this.metadataTags.date??=j}break;case"covr":case"com.apple.quicktime.artwork":if(q instanceof E0)this.metadataTags.images??=[],this.metadataTags.images.push({data:q.data,kind:"coverFront",mimeType:q.mimeType});else if(q instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:q,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof q==="string"){let j=q.split("/"),V=Number.parseInt(j[0],10),N=j[1]&&Number.parseInt(j[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"trkn":if(q instanceof Uint8Array&&q.length>=6){let j=E(q),V=j.getUint16(2,!1),N=j.getUint16(4,!1);if(V>0)this.metadataTags.trackNumber??=V;if(N>0)this.metadataTags.tracksTotal??=N}break;case"disc":case"disk":if(q instanceof Uint8Array&&q.length>=6){let j=E(q),V=j.getUint16(2,!1),N=j.getUint16(4,!1);if(V>0)this.metadataTags.discNumber??=V;if(N>0)this.metadataTags.discsTotal??=N}break}}}break}return $.filePos=Z,!0}}class p8{constructor($){this.internalTrack=$,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(K)=>{if(K.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return y0($*this.internalTrack.timescale,14)+this.internalTrack.editListOffset}async getPacket($,J){let K=this.mapTimestampIntoTimescale($),Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=o$(Y,K),X=await this.fetchPacketForSampleIndex(Z,J);if(!n$(Y)||!this.internalTrack.demuxer.isFragmented)return X;return this.performFragmentedLookup(null,(Q)=>{let W=Q.trackData.get(this.internalTrack.id);if(!W)return{sampleIndex:-1,correctSampleFound:!1};let G=S(W.presentationTimestamps,K,(j)=>j.presentationTimestamp),U=G!==-1?W.presentationTimestamps[G].sampleIndex:-1,q=G!==-1&&K<W.endTimestamp;return{sampleIndex:U,correctSampleFound:q}},K,K,J)}async getNextPacket($,J){let K=this.packetToSampleIndex.get($);if(K!==void 0)return this.fetchPacketForSampleIndex(K+1,J);let Y=this.packetToFragmentLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(Y.fragment,(Z)=>{if(Z===Y.fragment){let X=Z.trackData.get(this.internalTrack.id);if(Y.sampleIndex+1<X.samples.length)return{sampleIndex:Y.sampleIndex+1,correctSampleFound:!0}}else if(Z.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let K=this.mapTimestampIntoTimescale($),Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=o$(Y,K),X=Z===-1?-1:qY(Y,Z),Q=await this.fetchPacketForSampleIndex(X,J);if(!n$(Y)||!this.internalTrack.demuxer.isFragmented)return Q;return this.performFragmentedLookup(null,(W)=>{let G=W.trackData.get(this.internalTrack.id);if(!G)return{sampleIndex:-1,correctSampleFound:!1};let U=P1(G.presentationTimestamps,(V)=>{return G.samples[V.sampleIndex].isKeyFrame&&V.presentationTimestamp<=K}),q=U!==-1?G.presentationTimestamps[U].sampleIndex:-1,j=U!==-1&&K<G.endTimestamp;return{sampleIndex:q,correctSampleFound:j}},K,K,J)}async getNextKeyPacket($,J){let K=this.packetToSampleIndex.get($);if(K!==void 0){let Z=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=UY(Z,K);return this.fetchPacketForSampleIndex(X,J)}let Y=this.packetToFragmentLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(Y.fragment,(Z)=>{if(Z===Y.fragment){let Q=Z.trackData.get(this.internalTrack.id).samples.findIndex((W,G)=>W.isKeyFrame&&G>Y.sampleIndex);if(Q!==-1)return{sampleIndex:Q,correctSampleFound:!0}}else{let X=Z.trackData.get(this.internalTrack.id);if(X&&X.firstKeyFrameTimestamp!==null){let Q=X.samples.findIndex((W)=>W.isKeyFrame);return H(Q!==-1),{sampleIndex:Q,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let K=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Y=GY(K,$);if(!Y)return null;let Z;if(J.metadataOnly)Z=u;else{let G=this.internalTrack.demuxer.reader.requestSlice(Y.sampleOffset,Y.sampleSize);if(G instanceof Promise)G=await G;H(G),Z=v(G,Y.sampleSize)}let X=(Y.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,Q=Y.duration/this.internalTrack.timescale,W=new f(Z,Y.isKeyFrame?"key":"delta",X,Q,$,Y.sampleSize);return this.packetToSampleIndex.set(W,$),W}async fetchPacketInFragment($,J,K){if(J===-1)return null;let Z=$.trackData.get(this.internalTrack.id).samples[J];H(Z);let X;if(K.metadataOnly)X=u;else{let U=this.internalTrack.demuxer.reader.requestSlice(Z.byteOffset,Z.byteSize);if(U instanceof Promise)U=await U;H(U),X=v(U,Z.byteSize)}let Q=(Z.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,W=Z.duration/this.internalTrack.timescale,G=new f(X,Z.isKeyFrame?"key":"delta",Q,W,$.moofOffset+J,Z.byteSize);return this.packetToFragmentLocation.set(G,{fragment:$,sampleIndex:J}),G}async performFragmentedLookup($,J,K,Y,Z){let X=this.internalTrack.demuxer,Q=null,W=null,G=-1;if($){let{sampleIndex:R,correctSampleFound:z}=J($);if(z)return this.fetchPacketInFragment($,R,Z);if(R!==-1)W=$,G=R}let U=S(this.internalTrack.fragmentLookupTable,K,(R)=>R.timestamp),q=U!==-1?this.internalTrack.fragmentLookupTable[U]:null,j=S(this.internalTrack.fragmentPositionCache,K,(R)=>R.startTimestamp),V=j!==-1?this.internalTrack.fragmentPositionCache[j]:null,N=Math.max(q?.moofOffset??0,V?.moofOffset??0)||null,A;if(!$)A=N??0;else if(N===null||$.moofOffset>=N)A=$.moofOffset+$.moofSize,Q=$;else A=N;while(!0){if(Q){let F=Q.trackData.get(this.internalTrack.id);if(F&&F.startTimestamp>Y)break}let R=X.reader.requestSliceRange(A,I0,n0);if(R instanceof Promise)R=await R;if(!R)break;let z=A,O=z0(R);if(!O)break;if(O.name==="moof"){Q=await X.readFragment(z);let{sampleIndex:F,correctSampleFound:_}=J(Q);if(_)return this.fetchPacketInFragment(Q,F,Z);if(F!==-1)W=Q,G=F}A=z+O.totalSize}if(q&&(!W||W.moofOffset<q.moofOffset)){let R=this.internalTrack.fragmentLookupTable[U-1];H(!R||R.timestamp<q.timestamp);let z=R?.timestamp??-1/0;return this.performFragmentedLookup(null,J,z,Y,Z)}if(W)return this.fetchPacketInFragment(W,G,Z);return null}}class r$ extends p8{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=$&&g1($.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=$&&u1($.data)}return{codec:E1(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()}}class i$ extends p8{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:b1(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}var o$=($,J)=>{if($.presentationTimestamps){let K=S($.presentationTimestamps,J,(Y)=>Y.presentationTimestamp);if(K===-1)return-1;return $.presentationTimestamps[K].sampleIndex}else{let K=S($.sampleTimingEntries,J,(Z)=>Z.startDecodeTimestamp);if(K===-1)return-1;let Y=$.sampleTimingEntries[K];return Y.startIndex+Math.min(Math.floor((J-Y.startDecodeTimestamp)/Y.delta),Y.count-1)}},GY=($,J)=>{let K=S($.sampleTimingEntries,J,(O)=>O.startIndex),Y=$.sampleTimingEntries[K];if(!Y||Y.startIndex+Y.count<=J)return null;let X=Y.startDecodeTimestamp+(J-Y.startIndex)*Y.delta,Q=S($.sampleCompositionTimeOffsets,J,(O)=>O.startIndex),W=$.sampleCompositionTimeOffsets[Q];if(W&&J-W.startIndex<W.count)X+=W.offset;let G=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],U=S($.sampleToChunk,J,(O)=>O.startSampleIndex),q=$.sampleToChunk[U];H(q);let j=q.startChunkIndex+Math.floor((J-q.startSampleIndex)/q.samplesPerChunk),V=$.chunkOffsets[j],N=q.startSampleIndex+(j-q.startChunkIndex)*q.samplesPerChunk,A=0,R=V;if($.sampleSizes.length===1)R+=G*(J-N),A+=G*q.samplesPerChunk;else for(let O=N;O<N+q.samplesPerChunk;O++){let F=$.sampleSizes[O];if(O<J)R+=F;A+=F}let z=Y.delta;if($.presentationTimestamps){let O=$.presentationTimestampIndexMap[J];if(H(O!==void 0),O<$.presentationTimestamps.length-1)z=$.presentationTimestamps[O+1].presentationTimestamp-X}return{presentationTimestamp:X,duration:z,sampleOffset:R,sampleSize:G,chunkOffset:V,chunkSize:A,isKeyFrame:$.keySampleIndices?l0($.keySampleIndices,J,(O)=>O)!==-1:!0}},qY=($,J)=>{if(!$.keySampleIndices)return J;let K=S($.keySampleIndices,J,(Y)=>Y);return $.keySampleIndices[K]??-1},UY=($,J)=>{if(!$.keySampleIndices)return J+1;let K=S($.keySampleIndices,J,(Y)=>Y);return $.keySampleIndices[K+1]??-1},g8=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let K of $.samples)K.presentationTimestamp+=J;for(let K of $.presentationTimestamps)K.presentationTimestamp+=J},jY=($)=>{let[J,,,K]=$,Y=Math.hypot(J,K),Z=J/Y,X=K/Y,Q=-Math.atan2(X,Z)*(180/Math.PI);if(!Number.isFinite(Q))return 0;return Q},n$=($)=>{return $.sampleSizes.length===0};/*!
|
|
108
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
109
|
+
*
|
|
110
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
111
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
112
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
113
|
+
*/var C;(function($){$[$.EBML=440786851]="EBML",$[$.EBMLVersion=17030]="EBMLVersion",$[$.EBMLReadVersion=17143]="EBMLReadVersion",$[$.EBMLMaxIDLength=17138]="EBMLMaxIDLength",$[$.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",$[$.DocType=17026]="DocType",$[$.DocTypeVersion=17031]="DocTypeVersion",$[$.DocTypeReadVersion=17029]="DocTypeReadVersion",$[$.Void=236]="Void",$[$.Segment=408125543]="Segment",$[$.SeekHead=290298740]="SeekHead",$[$.Seek=19899]="Seek",$[$.SeekID=21419]="SeekID",$[$.SeekPosition=21420]="SeekPosition",$[$.Duration=17545]="Duration",$[$.Info=357149030]="Info",$[$.TimestampScale=2807729]="TimestampScale",$[$.MuxingApp=19840]="MuxingApp",$[$.WritingApp=22337]="WritingApp",$[$.Tracks=374648427]="Tracks",$[$.TrackEntry=174]="TrackEntry",$[$.TrackNumber=215]="TrackNumber",$[$.TrackUID=29637]="TrackUID",$[$.TrackType=131]="TrackType",$[$.FlagEnabled=185]="FlagEnabled",$[$.FlagDefault=136]="FlagDefault",$[$.FlagForced=21930]="FlagForced",$[$.FlagLacing=156]="FlagLacing",$[$.Name=21358]="Name",$[$.Language=2274716]="Language",$[$.LanguageBCP47=2274717]="LanguageBCP47",$[$.CodecID=134]="CodecID",$[$.CodecPrivate=25506]="CodecPrivate",$[$.CodecDelay=22186]="CodecDelay",$[$.SeekPreRoll=22203]="SeekPreRoll",$[$.DefaultDuration=2352003]="DefaultDuration",$[$.Video=224]="Video",$[$.PixelWidth=176]="PixelWidth",$[$.PixelHeight=186]="PixelHeight",$[$.AlphaMode=21440]="AlphaMode",$[$.Audio=225]="Audio",$[$.SamplingFrequency=181]="SamplingFrequency",$[$.Channels=159]="Channels",$[$.BitDepth=25188]="BitDepth",$[$.SimpleBlock=163]="SimpleBlock",$[$.BlockGroup=160]="BlockGroup",$[$.Block=161]="Block",$[$.BlockAdditions=30113]="BlockAdditions",$[$.BlockMore=166]="BlockMore",$[$.BlockAdditional=165]="BlockAdditional",$[$.BlockAddID=238]="BlockAddID",$[$.BlockDuration=155]="BlockDuration",$[$.ReferenceBlock=251]="ReferenceBlock",$[$.Cluster=524531317]="Cluster",$[$.Timestamp=231]="Timestamp",$[$.Cues=475249515]="Cues",$[$.CuePoint=187]="CuePoint",$[$.CueTime=179]="CueTime",$[$.CueTrackPositions=183]="CueTrackPositions",$[$.CueTrack=247]="CueTrack",$[$.CueClusterPosition=241]="CueClusterPosition",$[$.Colour=21936]="Colour",$[$.MatrixCoefficients=21937]="MatrixCoefficients",$[$.TransferCharacteristics=21946]="TransferCharacteristics",$[$.Primaries=21947]="Primaries",$[$.Range=21945]="Range",$[$.Projection=30320]="Projection",$[$.ProjectionType=30321]="ProjectionType",$[$.ProjectionPoseRoll=30325]="ProjectionPoseRoll",$[$.Attachments=423732329]="Attachments",$[$.AttachedFile=24999]="AttachedFile",$[$.FileDescription=18046]="FileDescription",$[$.FileName=18030]="FileName",$[$.FileMediaType=18016]="FileMediaType",$[$.FileData=18012]="FileData",$[$.FileUID=18094]="FileUID",$[$.Chapters=272869232]="Chapters",$[$.Tags=307544935]="Tags",$[$.Tag=29555]="Tag",$[$.Targets=25536]="Targets",$[$.TargetTypeValue=26826]="TargetTypeValue",$[$.TargetType=25546]="TargetType",$[$.TagTrackUID=25541]="TagTrackUID",$[$.TagEditionUID=25545]="TagEditionUID",$[$.TagChapterUID=25540]="TagChapterUID",$[$.TagAttachmentUID=25542]="TagAttachmentUID",$[$.SimpleTag=26568]="SimpleTag",$[$.TagName=17827]="TagName",$[$.TagLanguage=17530]="TagLanguage",$[$.TagString=17543]="TagString",$[$.TagBinary=17541]="TagBinary",$[$.ContentEncodings=28032]="ContentEncodings",$[$.ContentEncoding=25152]="ContentEncoding",$[$.ContentEncodingOrder=20529]="ContentEncodingOrder",$[$.ContentEncodingScope=20530]="ContentEncodingScope",$[$.ContentCompression=20532]="ContentCompression",$[$.ContentCompAlgo=16980]="ContentCompAlgo",$[$.ContentCompSettings=16981]="ContentCompSettings",$[$.ContentEncryption=20533]="ContentEncryption"})(C||(C={}));var VY=[C.EBML,C.Segment],r0=[C.SeekHead,C.Info,C.Cluster,C.Tracks,C.Cues,C.Attachments,C.Chapters,C.Tags],a1=[...VY,...r0];var m8=8,a=2,Y0=2*m8,l8=($)=>{let J=T($);if($.skip(-1),J===0)return null;let K=1,Y=128;while((J&Y)===0)K++,Y>>=1;return K},i0=($)=>{let J=T($);if(J===0)return null;let K=1,Y=128;while((J&Y)===0)K++,Y>>=1;let Z=J&Y-1;for(let X=1;X<K;X++)Z*=256,Z+=T($);return Z},y=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let K=0;for(let Y=0;Y<J;Y++)K*=256,K+=T($);return K},a$=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let K=0n;for(let Y=0;Y<J;Y++)K<<=8n,K+=BigInt(T($));return K},t$=($,J)=>{let K=y($,J);if(K&1<<J*8-1)K-=2**(J*8);return K},t1=($)=>{let J=l8($);if(J===null)return null;return y($,J)},d8=($)=>{let J=T($);if(J===255)J=null;else if($.skip(-1),J=i0($),J===72057594037927940)J=null;return J},K0=($)=>{let J=t1($);if(J===null)return null;let K=d8($);return{id:J,size:K}},B0=($,J)=>{let K=v($,J),Y=0;while(Y<J&&K[Y]!==0)Y+=1;return String.fromCharCode(...K.subarray(0,Y))},s0=($,J)=>{let K=v($,J),Y=0;while(Y<J&&K[Y]!==0)Y+=1;return l.decode(K.subarray(0,Y))},e1=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?e$($):s1($)},$8=async($,J,K,Y)=>{let Z=new Set(K),X=J;while(Y===null||X<Y){let Q=$.requestSliceRange(X,a,Y0);if(Q instanceof Promise)Q=await Q;if(!Q)break;let W=K0(Q);if(!W)break;if(Z.has(W.id))return{pos:X,found:!0};_0(W.size),X=Q.filePos+W.size}return{pos:Y!==null&&Y>X?Y:X,found:!1}},c8=async($,J,K,Y)=>{let X=new Set(K),Q=J;while(Q<Y){let W=$.requestSliceRange(Q,0,Math.min(65536,Y-Q));if(W instanceof Promise)W=await W;if(!W)break;if(W.length<m8)break;for(let G=0;G<W.length-m8;G++){W.filePos=Q;let U=t1(W);if(U!==null&&X.has(U))return Q;Q++}}return null},X0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function _0($){if($===null)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
|
|
114
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
115
|
+
*
|
|
116
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
117
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
118
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
119
|
+
*/var $J=($)=>{let K=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isWebM?"webm":"x-matroska");if($.codecStrings.length>0){let Y=[...new Set($.codecStrings.filter(Boolean))];K+=`; codecs="${Y.join(", ")}"`}return K};/*!
|
|
120
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
121
|
+
*
|
|
122
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
123
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
124
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
125
|
+
*/var C0;(function($){$[$.None=0]="None",$[$.Xiph=1]="Xiph",$[$.FixedSize=2]="FixedSize",$[$.Ebml=3]="Ebml"})(C0||(C0={}));var J8;(function($){$[$.Block=1]="Block",$[$.Private=2]="Private",$[$.Next=4]="Next"})(J8||(J8={}));var R1;(function($){$[$.Zlib=0]="Zlib",$[$.Bzlib=1]="Bzlib",$[$.lzo1x=2]="lzo1x",$[$.HeaderStripping=3]="HeaderStripping"})(R1||(R1={}));var o8=[{id:C.SeekHead,flag:"seekHeadSeen"},{id:C.Info,flag:"infoSeen"},{id:C.Tracks,flag:"tracksSeen"},{id:C.Cues,flag:"cuesSeen"}],JJ=10485760;class n8 extends s{constructor($){super($);this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((K)=>K.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(($)=>$.tracks.map((J)=>J.inputTrack))}async getMimeType(){await this.readMetadata();let $=await this.getTracks(),J=await Promise.all($.map((K)=>K.getCodecParameterString()));return $J({isWebM:this.isWebM,hasVideo:this.segments.some((K)=>K.tracks.some((Y)=>Y.info?.type==="video")),hasAudio:this.segments.some((K)=>K.tracks.some((Y)=>Y.info?.type==="audio")),codecStrings:J.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let J of this.segments)if(!J.metadataTagsCollected){if(this.reader.fileSize!==null)await this.loadSegmentMetadata(J);J.metadataTagsCollected=!0}let $={};for(let J of this.segments)$={...$,...J.metadataTags};return $}readMetadata(){return this.readMetadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,a,Y0);if(J instanceof Promise)J=await J;if(!J)break;let K=K0(J);if(!K)break;let{id:Y,size:Z}=K,X=J.filePos;if(Y===C.EBML){_0(Z);let Q=this.reader.requestSlice(X,Z);if(Q instanceof Promise)Q=await Q;if(!Q)break;this.readContiguousElements(Q)}else if(Y===C.Segment){if(await this.readSegment(X,Z),Z===null)break;if(this.reader.fileSize===null)break}else if(Y===C.Cluster){if(this.reader.fileSize===null)break;if(Z===null)Z=(await $8(this.reader,X,a1,this.reader.fileSize)).pos-X;let Q=r(this.segments);if(Q)Q.elementEndPos=X+Z}_0(Z),$=X+Z}})()}async readSegment($,J){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:$,elementEndPos:J===null?null:$+J,clusterSeekStartPos:$,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let K=$;while(this.currentSegment.elementEndPos===null||K<this.currentSegment.elementEndPos){let Q=this.reader.requestSliceRange(K,a,Y0);if(Q instanceof Promise)Q=await Q;if(!Q)break;let W=K,G=K0(Q);if(!G||!r0.includes(G.id)&&G.id!==C.Void){let N=await c8(this.reader,W,r0,Math.min(this.currentSegment.elementEndPos??1/0,W+JJ));if(N){K=N;continue}else break}let{id:U,size:q}=G,j=Q.filePos,V=o8.findIndex((N)=>N.id===U);if(V!==-1){let N=o8[V].flag;this.currentSegment[N]=!0,_0(q);let A=this.reader.requestSlice(j,q);if(A instanceof Promise)A=await A;if(A)this.readContiguousElements(A)}else if(U===C.Tags||U===C.Attachments){if(U===C.Tags)this.currentSegment.tagsSeen=!0;else this.currentSegment.attachmentsSeen=!0;_0(q);let N=this.reader.requestSlice(j,q);if(N instanceof Promise)N=await N;if(N)this.readContiguousElements(N)}else if(U===C.Cluster){this.currentSegment.clusterSeekStartPos=W;break}if(q===null)break;else K=j+q}if(this.currentSegment.seekEntries.sort((Q,W)=>Q.segmentPosition-W.segmentPosition),this.reader.fileSize!==null)for(let Q of this.currentSegment.seekEntries){let W=o8.find((N)=>N.id===Q.id);if(!W)continue;if(this.currentSegment[W.flag])continue;let G=this.reader.requestSliceRange($+Q.segmentPosition,a,Y0);if(G instanceof Promise)G=await G;if(!G)continue;let U=K0(G);if(!U)continue;let{id:q,size:j}=U;if(q!==W.id)continue;_0(j),this.currentSegment[W.flag]=!0;let V=this.reader.requestSlice(G.filePos,j);if(V instanceof Promise)V=await V;if(!V)continue;this.readContiguousElements(V)}if(this.currentSegment.timestampScale===-1)this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1000;this.currentSegment.tracks.sort((Q,W)=>Number(W.isDefault)-Number(Q.isDefault));let Y=new Map(this.currentSegment.tracks.map((Q)=>[Q.id,Q]));for(let Q of this.currentSegment.cuePoints){let W=Y.get(Q.trackId);if(W)W.cuePoints.push(Q)}for(let Q of this.currentSegment.tracks){Q.cuePoints.sort((W,G)=>W.time-G.time);for(let W=0;W<Q.cuePoints.length-1;W++){let G=Q.cuePoints[W],U=Q.cuePoints[W+1];if(G.time===U.time)Q.cuePoints.splice(W+1,1),W--}}let Z=null,X=-1/0;for(let Q of this.currentSegment.tracks)if(Q.cuePoints.length>X)X=Q.cuePoints.length,Z=Q;for(let Q of this.currentSegment.tracks)if(Q.cuePoints.length===0)Q.cuePoints=Z.cuePoints;this.currentSegment=null}async readCluster($,J){if(J.lastReadCluster?.elementStartPos===$)return J.lastReadCluster;let K=this.reader.requestSliceRange($,a,Y0);if(K instanceof Promise)K=await K;H(K);let Y=$,Z=K0(K);H(Z);let X=Z.id;H(X===C.Cluster);let Q=Z.size,W=K.filePos;if(Q===null)Q=(await $8(this.reader,W,a1,J.elementEndPos)).pos-W;let G=this.reader.requestSlice(W,Q);if(G instanceof Promise)G=await G;let U={segment:J,elementStartPos:Y,elementEndPos:W+Q,dataStartPos:W,timestamp:-1,trackData:new Map};if(this.currentCluster=U,G)this.readContiguousElements(G);for(let[,q]of U.trackData){let j=q.track;H(q.blocks.length>0);let V=!1,N=!1;for(let O=0;O<q.blocks.length;O++){let F=q.blocks[O];F.timestamp+=U.timestamp,V||=F.referencedTimestamps.length>0,N||=F.lacing!==C0.None}if(V)q.blocks=NY(q.blocks);q.presentationTimestamps=q.blocks.map((O,F)=>({timestamp:O.timestamp,blockIndex:F})).sort((O,F)=>O.timestamp-F.timestamp);for(let O=0;O<q.presentationTimestamps.length;O++){let F=q.presentationTimestamps[O],_=q.blocks[F.blockIndex];if(q.firstKeyFrameTimestamp===null&&_.isKeyFrame)q.firstKeyFrameTimestamp=_.timestamp;if(O<q.presentationTimestamps.length-1){let w=q.presentationTimestamps[O+1];_.duration=w.timestamp-_.timestamp}else if(_.duration===0){if(j.defaultDuration!=null){if(_.lacing===C0.None)_.duration=j.defaultDuration}}}if(N)this.expandLacedBlocks(q.blocks,j),q.presentationTimestamps=q.blocks.map((O,F)=>({timestamp:O.timestamp,blockIndex:F})).sort((O,F)=>O.timestamp-F.timestamp);let A=q.blocks[q.presentationTimestamps[0].blockIndex],R=q.blocks[r(q.presentationTimestamps).blockIndex];q.startTimestamp=A.timestamp,q.endTimestamp=R.timestamp+R.duration;let z=S(j.clusterPositionCache,q.startTimestamp,(O)=>O.startTimestamp);if(z===-1||j.clusterPositionCache[z].elementStartPos!==Y)j.clusterPositionCache.splice(z+1,0,{elementStartPos:U.elementStartPos,startTimestamp:q.startTimestamp})}return J.lastReadCluster=U,U}getTrackDataInCluster($,J){let K=$.trackData.get(J);if(!K){let Y=$.segment.tracks.find((Z)=>Z.id===J);if(!Y)return null;K={track:Y,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},$.trackData.set(J,K)}return K}expandLacedBlocks($,J){for(let K=0;K<$.length;K++){let Y=$[K];if(Y.lacing===C0.None)continue;if(!Y.decoded)Y.data=this.decodeBlockData(J,Y.data),Y.decoded=!0;let Z=k0.tempFromBytes(Y.data),X=[],Q=T(Z)+1;switch(Y.lacing){case C0.Xiph:{let W=0;for(let G=0;G<Q-1;G++){let U=0;while(Z.bufferPos<Z.length){let q=T(Z);if(U+=q,q<255){X.push(U),W+=U;break}}}X.push(Z.length-(Z.bufferPos+W))}break;case C0.FixedSize:{let W=Z.length-1,G=Math.floor(W/Q);for(let U=0;U<Q;U++)X.push(G)}break;case C0.Ebml:{let W=i0(Z);H(W!==null);let G=W;X.push(G);let U=G;for(let q=1;q<Q-1;q++){let j=Z.bufferPos,V=i0(Z);H(V!==null);let N=V,R=(1<<(Z.bufferPos-j)*7-1)-1,z=N-R;G+=z,X.push(G),U+=G}X.push(Z.length-(Z.bufferPos+U))}break;default:H(!1)}H(X.length===Q),$.splice(K,1);for(let W=0;W<Q;W++){let G=X[W],U=v(Z,G),q=Y.duration||Q*(J.defaultDuration??0),j=Y.timestamp+q*W/Q,V=q/Q;$.splice(K+W,0,{timestamp:j,duration:V,isKeyFrame:Y.isKeyFrame,referencedTimestamps:Y.referencedTimestamps,data:U,lacing:C0.None,decoded:!0,mainAdditional:Y.mainAdditional})}K+=Q,K--}}async loadSegmentMetadata($){for(let J of $.seekEntries){if(J.id===C.Tags&&!$.tagsSeen);else if(J.id===C.Attachments&&!$.attachmentsSeen);else continue;let K=this.reader.requestSliceRange($.dataStartPos+J.segmentPosition,a,Y0);if(K instanceof Promise)K=await K;if(!K)continue;let Y=K0(K);if(!Y||Y.id!==J.id)continue;let{size:Z}=Y;_0(Z),H(!this.currentSegment),this.currentSegment=$;let X=this.reader.requestSlice(K.filePos,Z);if(X instanceof Promise)X=await X;if(X)this.readContiguousElements(X);if(this.currentSegment=null,J.id===C.Tags)$.tagsSeen=!0;else if(J.id===C.Attachments)$.attachmentsSeen=!0}}readContiguousElements($){let J=$.filePos;while($.filePos-J<=$.length-a)if(!this.traverseElement($))break}traverseElement($){let J=K0($);if(!J)return!1;let{id:K,size:Y}=J,Z=$.filePos;switch(_0(Y),K){case C.DocType:this.isWebM=B0($,Y)==="webm";break;case C.Seek:{if(!this.currentSegment)break;let X={id:-1,segmentPosition:-1};if(this.currentSegment.seekEntries.push(X),this.readContiguousElements($.slice(Z,Y)),X.id===-1||X.segmentPosition===-1)this.currentSegment.seekEntries.pop()}break;case C.SeekID:{let X=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!X)break;X.id=y($,Y)}break;case C.SeekPosition:{let X=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!X)break;X.segmentPosition=y($,Y)}break;case C.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=y($,Y),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case C.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=e1($,Y)}break;case C.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],isDefault:!1,inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:d,decodingInstructions:[],info:null},this.readContiguousElements($.slice(Z,Y)),this.currentTrack.decodingInstructions.some((X)=>{return X.data?.type!=="decompress"||X.scope!==J8.Block||X.data.algorithm!==R1.HeaderStripping}))console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null;if(this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let X=this.currentTrack.codecId.indexOf("/"),Q=X===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,X);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.codecId===X0.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===X0.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(Q===X0.vp8)this.currentTrack.info.codec="vp8";else if(Q===X0.vp9)this.currentTrack.info.codec="vp9";else if(Q===X0.av1)this.currentTrack.info.codec="av1";let W=this.currentTrack,G=new R0(this.input,new YJ(W));this.currentTrack.inputTrack=G,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){if(Q===X0.aac)this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===X0.mp3)this.currentTrack.info.codec="mp3";else if(Q===X0.opus)this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=f0;else if(Q===X0.vorbis)this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(Q===X0.flac)this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId==="A_PCM/INT/LIT"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32"}else if(this.currentTrack.codecId==="A_PCM/INT/BIG"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16be";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24be";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32be"}else if(this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"){if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-f32";else if(this.currentTrack.info.bitDepth===64)this.currentTrack.info.codec="pcm-f64"}let W=this.currentTrack,G=new p(this.input,new KJ(W));this.currentTrack.inputTrack=G,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case C.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=y($,Y)}break;case C.TrackType:{if(!this.currentTrack)break;let X=y($,Y);if(X===1)this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1};else if(X===2)this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null}}break;case C.FlagEnabled:{if(!this.currentTrack)break;if(!y($,Y))this.currentSegment.tracks.pop(),this.currentTrack=null}break;case C.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.isDefault=!!y($,Y)}break;case C.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=B0($,Y)}break;case C.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=v($,Y)}break;case C.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*y($,Y)/1e9}break;case C.Name:{if(!this.currentTrack)break;this.currentTrack.name=s0($,Y)}break;case C.Language:{if(!this.currentTrack)break;if(this.currentTrack.languageCode!==d)break;if(this.currentTrack.languageCode=B0($,Y),!v1(this.currentTrack.languageCode))this.currentTrack.languageCode=d}break;case C.LanguageBCP47:{if(!this.currentTrack)break;let Q=B0($,Y).split("-")[0];if(Q)this.currentTrack.languageCode=Q;else this.currentTrack.languageCode=d}break;case C.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Y))}break;case C.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=y($,Y)}break;case C.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=y($,Y)}break;case C.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=y($,Y)===1}break;case C.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements($.slice(Z,Y))}break;case C.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let X=y($,Y),Q=T1[X]??null;this.currentTrack.info.colorSpace.matrix=Q}break;case C.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=y($,Y)===2}break;case C.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let X=y($,Y),Q=L1[X]??null;this.currentTrack.info.colorSpace.transfer=Q}break;case C.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let X=y($,Y),Q=M1[X]??null;this.currentTrack.info.colorSpace.primaries=Q}break;case C.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Y))}break;case C.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let Q=-e1($,Y);try{this.currentTrack.info.rotation=w1(Q)}catch{}}break;case C.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements($.slice(Z,Y))}break;case C.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=e1($,Y)}break;case C.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=y($,Y)}break;case C.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=y($,Y)}break;case C.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements($.slice(Z,Y)),this.currentCueTime=null}break;case C.CueTime:this.currentCueTime=y($,Y);break;case C.CueTrackPositions:{if(this.currentCueTime===null)break;H(this.currentSegment);let X={time:this.currentCueTime,trackId:-1,clusterPosition:-1};if(this.currentSegment.cuePoints.push(X),this.readContiguousElements($.slice(Z,Y)),X.trackId===-1||X.clusterPosition===-1)this.currentSegment.cuePoints.pop()}break;case C.CueTrack:{let X=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!X)break;X.trackId=y($,Y)}break;case C.CueClusterPosition:{let X=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!X)break;H(this.currentSegment),X.clusterPosition=this.currentSegment.dataStartPos+y($,Y)}break;case C.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=y($,Y)}break;case C.SimpleBlock:{if(!this.currentCluster)break;let X=i0($);if(X===null)break;let Q=this.getTrackDataInCluster(this.currentCluster,X);if(!Q)break;let W=O1($),G=T($),U=!!(G&128),q=G>>1&3,j=v($,Y-($.filePos-Z)),V=Q.track.decodingInstructions.length>0;Q.blocks.push({timestamp:W,duration:0,isKeyFrame:U,referencedTimestamps:[],data:j,lacing:q,decoded:!V,mainAdditional:null})}break;case C.BlockGroup:{if(!this.currentCluster)break;if(this.readContiguousElements($.slice(Z,Y)),this.currentBlock){for(let X=0;X<this.currentBlock.referencedTimestamps.length;X++)this.currentBlock.referencedTimestamps[X]+=this.currentBlock.timestamp;this.currentBlock=null}}break;case C.Block:{if(!this.currentCluster)break;let X=i0($);if(X===null)break;let Q=this.getTrackDataInCluster(this.currentCluster,X);if(!Q)break;let W=O1($),U=T($)>>1&3,q=v($,Y-($.filePos-Z)),j=Q.track.decodingInstructions.length>0;this.currentBlock={timestamp:W,duration:0,isKeyFrame:!0,referencedTimestamps:[],data:q,lacing:U,decoded:!j,mainAdditional:null},Q.blocks.push(this.currentBlock)}break;case C.BlockAdditions:this.readContiguousElements($.slice(Z,Y));break;case C.BlockMore:{if(!this.currentBlock)break;if(this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements($.slice(Z,Y)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1)this.currentBlock.mainAdditional=this.currentBlockAdditional.data;this.currentBlockAdditional=null}break;case C.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=v($,Y)}break;case C.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=y($,Y)}break;case C.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=y($,Y)}break;case C.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;let X=t$($,Y);this.currentBlock.referencedTimestamps.push(X)}break;case C.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements($.slice(Z,Y));break;case C.Targets:this.readContiguousElements($.slice(Z,Y));break;case C.TargetTypeValue:if(y($,Y)!==50)this.currentTagTargetIsMovie=!1;break;case C.TagTrackUID:case C.TagEditionUID:case C.TagChapterUID:case C.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case C.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements($.slice(Z,Y))}break;case C.TagName:this.currentSimpleTagName=s0($,Y);break;case C.TagString:{if(!this.currentSimpleTagName)break;let X=s0($,Y);this.processTagValue(this.currentSimpleTagName,X)}break;case C.TagBinary:{if(!this.currentSimpleTagName)break;let X=v($,Y);this.processTagValue(this.currentSimpleTagName,X)}break;case C.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements($.slice(Z,Y));let X=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData)X.raw??={},X.raw[this.currentAttachedFile.fileUid.toString()]=new P8(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0);if(this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let Q=this.currentAttachedFile.fileName,W="unknown";if(Q){let G=Q.toLowerCase();if(G.startsWith("cover."))W="coverFront";else if(G.startsWith("back."))W="coverBack"}X.images??=[],X.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:W,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case C.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=a$($,Y)}break;case C.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=s0($,Y)}break;case C.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=B0($,Y)}break;case C.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=v($,Y)}break;case C.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=s0($,Y)}break;case C.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements($.slice(Z,Y)),this.currentTrack.decodingInstructions.sort((X,Q)=>Q.order-X.order)}break;case C.ContentEncoding:{if(this.currentDecodingInstruction={order:0,scope:J8.Block,data:null},this.readContiguousElements($.slice(Z,Y)),this.currentDecodingInstruction.data)this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction);this.currentDecodingInstruction=null}break;case C.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=y($,Y)}break;case C.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=y($,Y)}break;case C.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:R1.Zlib,settings:null},this.readContiguousElements($.slice(Z,Y))}break;case C.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=y($,Y)}break;case C.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=v($,Y)}break;case C.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return $.filePos=Z+Y,!0}decodeBlockData($,J){H($.decodingInstructions.length>0);let K=J;for(let Y of $.decodingInstructions)switch(H(Y.data),Y.data.type){case"decompress":switch(Y.data.algorithm){case R1.HeaderStripping:if(Y.data.settings&&Y.data.settings.length>0){let Z=Y.data.settings,X=new Uint8Array(Z.length+K.length);X.set(Z,0),X.set(K,Z.length),K=X}break;default:}break;default:}return K}processTagValue($,J){if(!this.currentSegment?.metadataTags)return;let K=this.currentSegment.metadataTags;if(K.raw??={},K.raw[$]??=J,typeof J==="string")switch($.toLowerCase()){case"title":K.title??=J;break;case"description":K.description??=J;break;case"artist":K.artist??=J;break;case"album":K.album??=J;break;case"album_artist":K.albumArtist??=J;break;case"genre":K.genre??=J;break;case"comment":K.comment??=J;break;case"lyrics":K.lyrics??=J;break;case"date":{let Y=new Date(J);if(!Number.isNaN(Y.getTime()))K.date??=Y}break;case"track_number":case"part_number":{let Y=J.split("/"),Z=Number.parseInt(Y[0],10),X=Y[1]&&Number.parseInt(Y[1],10);if(Number.isInteger(Z)&&Z>0)K.trackNumber??=Z;if(X&&Number.isInteger(X)&&X>0)K.tracksTotal??=X}break;case"disc_number":case"disc":{let Y=J.split("/"),Z=Number.parseInt(Y[0],10),X=Y[1]&&Number.parseInt(Y[1],10);if(Number.isInteger(Z)&&Z>0)K.discNumber??=Z;if(X&&Number.isInteger(X)&&X>0)K.discsTotal??=X}break}}}class r8{constructor($){this.internalTrack=$,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}async getFirstPacket($){return this.performClusterLookup(null,(J)=>{if(J.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,$)}intoTimescale($){return y0($*this.internalTrack.segment.timestampFactor,14)}async getPacket($,J){let K=this.intoTimescale($);return this.performClusterLookup(null,(Y)=>{let Z=Y.trackData.get(this.internalTrack.id);if(!Z)return{blockIndex:-1,correctBlockFound:!1};let X=S(Z.presentationTimestamps,K,(G)=>G.timestamp),Q=X!==-1?Z.presentationTimestamps[X].blockIndex:-1,W=X!==-1&&K<Z.endTimestamp;return{blockIndex:Q,correctBlockFound:W}},K,K,J)}async getNextPacket($,J){let K=this.packetToClusterLocation.get($);if(K===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(K.cluster,(Y)=>{if(Y===K.cluster){let Z=Y.trackData.get(this.internalTrack.id);if(K.blockIndex+1<Z.blocks.length)return{blockIndex:K.blockIndex+1,correctBlockFound:!0}}else if(Y.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let K=this.intoTimescale($);return this.performClusterLookup(null,(Y)=>{let Z=Y.trackData.get(this.internalTrack.id);if(!Z)return{blockIndex:-1,correctBlockFound:!1};let X=P1(Z.presentationTimestamps,(G)=>{return Z.blocks[G.blockIndex].isKeyFrame&&G.timestamp<=K}),Q=X!==-1?Z.presentationTimestamps[X].blockIndex:-1,W=X!==-1&&K<Z.endTimestamp;return{blockIndex:Q,correctBlockFound:W}},K,K,J)}async getNextKeyPacket($,J){let K=this.packetToClusterLocation.get($);if(K===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(K.cluster,(Y)=>{if(Y===K.cluster){let X=Y.trackData.get(this.internalTrack.id).blocks.findIndex((Q,W)=>Q.isKeyFrame&&W>K.blockIndex);if(X!==-1)return{blockIndex:X,correctBlockFound:!0}}else{let Z=Y.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let X=Z.blocks.findIndex((Q)=>Q.isKeyFrame);return H(X!==-1),{blockIndex:X,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async fetchPacketInCluster($,J,K){if(J===-1)return null;let Z=$.trackData.get(this.internalTrack.id).blocks[J];if(H(Z),!Z.decoded)Z.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,Z.data),Z.decoded=!0;let X=K.metadataOnly?u:Z.data,Q=Z.timestamp/this.internalTrack.segment.timestampFactor,W=Z.duration/this.internalTrack.segment.timestampFactor,G={};if(Z.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode)G.alpha=K.metadataOnly?u:Z.mainAdditional,G.alphaByteLength=Z.mainAdditional.byteLength;let U=new f(X,Z.isKeyFrame?"key":"delta",Q,W,$.dataStartPos+J,Z.data.byteLength,G);return this.packetToClusterLocation.set(U,{cluster:$,blockIndex:J}),U}async performClusterLookup($,J,K,Y,Z){let{demuxer:X,segment:Q}=this.internalTrack,W=null,G=null,U=-1;if($){let{blockIndex:z,correctBlockFound:O}=J($);if(O)return this.fetchPacketInCluster($,z,Z);if(z!==-1)G=$,U=z}let q=S(this.internalTrack.cuePoints,K,(z)=>z.time),j=q!==-1?this.internalTrack.cuePoints[q]:null,V=S(this.internalTrack.clusterPositionCache,K,(z)=>z.startTimestamp),N=V!==-1?this.internalTrack.clusterPositionCache[V]:null,A=Math.max(j?.clusterPosition??0,N?.elementStartPos??0)||null,R;if(!$)R=A??Q.clusterSeekStartPos;else if(A===null||$.elementStartPos>=A)R=$.elementEndPos,W=$;else R=A;while(Q.elementEndPos===null||R<=Q.elementEndPos-a){if(W){let D=W.trackData.get(this.internalTrack.id);if(D&&D.startTimestamp>Y)break}let z=X.reader.requestSliceRange(R,a,Y0);if(z instanceof Promise)z=await z;if(!z)break;let O=R,F=K0(z);if(!F||!r0.includes(F.id)&&F.id!==C.Void){let D=await c8(X.reader,O,r0,Math.min(Q.elementEndPos??1/0,O+JJ));if(D){R=D;continue}else break}let{id:_,size:w}=F,P=z.filePos;if(_===C.Cluster){W=await X.readCluster(O,Q);let{blockIndex:D,correctBlockFound:L}=J(W);if(L)return this.fetchPacketInCluster(W,D,Z);if(D!==-1)G=W,U=D}if(w===null){if(_===C.Cluster)H(W),w=W.elementEndPos-P;else w=(await $8(X.reader,P,a1,Q.elementEndPos)).pos-P;let D=P+w;if(Q.elementEndPos!==null&&D>Q.elementEndPos-a)break;else{let L=X.reader.requestSliceRange(D,a,Y0);if(L instanceof Promise)L=await L;if(!L)break;if(t1(L)===C.Segment){Q.elementEndPos=D;break}}}R=P+w}if(j&&(!G||G.elementStartPos<j.clusterPosition)){let z=this.internalTrack.cuePoints[q-1];H(!z||z.time<j.time);let O=z?.time??-1/0;return this.performClusterLookup(null,J,O,Y,Z)}if(G)return this.fetchPacketInCluster(G,U,Z);return null}}class YJ extends r8{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{let $=null;if(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)$=await this.getFirstPacket({});return{codec:E1({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcCodecInfo:this.internalTrack.info.codec==="avc"&&$?x$($.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&$?y$($.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&$?g1($.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&$?u1($.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})()}}class KJ extends r8{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:b1({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}var NY=($)=>{let J=new Map;for(let X=0;X<$.length;X++){let Q=$[X];J.set(Q.timestamp,Q)}let K=new Set,Y=[],Z=(X)=>{if(K.has(X))return;K.add(X);for(let Q=0;Q<X.referencedTimestamps.length;Q++){let W=X.referencedTimestamps[Q],G=J.get(W);if(!G)continue;Z(G)}Y.push(X)};for(let X=0;X<$.length;X++)Z($[X]);return Y};/*!
|
|
126
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
127
|
+
*
|
|
128
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
129
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
130
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
131
|
+
*/var Y8=4,HY=[44100,48000,32000],AY=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],XJ=1483304551,ZJ=1231971951,OY=($,J,K,Y,Z)=>{if(J===0)return 0;else if(J===1)return Math.floor(144*K/(Y<<$))+Z;else if(J===2)return Math.floor(144*K/Y)+Z;else return(Math.floor(12*K/Y)+Z)*4},QJ=($,J)=>{return $===3?J===3?21:36:J===3?13:21},WJ=($,J)=>{let K=$>>>24,Y=$>>>16&255,Z=$>>>8&255,X=$&255;if(K!==255&&Y!==255&&Z!==255&&X!==255)return{header:null,bytesAdvanced:4};if(K!==255)return{header:null,bytesAdvanced:1};if((Y&224)!==224)return{header:null,bytesAdvanced:1};let Q=0,W=0;if(Y&16)Q=Y&8?0:1;else Q=1,W=1;let G=Y>>3&3,U=Y>>1&3,q=Z>>4&15,j=(Z>>2&3)%3,V=Z>>1&1,N=X>>6&3,A=X>>4&3,R=X>>3&1,z=X>>2&1,O=X&3,F=AY[Q*16*4+U*16+q];if(F===-1)return{header:null,bytesAdvanced:1};let _=F*1000,w=HY[j]>>Q+W,P=OY(Q,U,_,w,V);if(J!==null&&J<P)return{header:null,bytesAdvanced:1};let D;if(G===3)D=U===3?384:1152;else if(U===3)D=384;else if(U===2)D=1152;else D=576;return{header:{totalSize:P,mpegVersionId:G,layer:U,bitrate:_,frequencyIndex:j,sampleRate:w,channel:N,modeExtension:A,copyright:R,original:z,emphasis:O,audioSamplesInFrame:D},bytesAdvanced:1}};var K8=($)=>{let J=2130706432,K=0;while(J!==0)K>>=1,K|=$&J,J>>=8;return K};/*!
|
|
132
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
133
|
+
*
|
|
134
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
135
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
136
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
137
|
+
*/var t0;(function($){$[$.Unsynchronisation=128]="Unsynchronisation",$[$.ExtendedHeader=64]="ExtendedHeader",$[$.ExperimentalIndicator=32]="ExperimentalIndicator",$[$.Footer=16]="Footer"})(t0||(t0={}));var e0;(function($){$[$.ISO_8859_1=0]="ISO_8859_1",$[$.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",$[$.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",$[$.UTF_8=3]="UTF_8"})(e0||(e0={}));var z1=128,J1=10,$1=["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"],GJ=($,J)=>{let K=$.filePos;J.raw??={},J.raw.TAG??=v($,z1-3),$.filePos=K;let Y=a0($,30);if(Y)J.title??=Y;let Z=a0($,30);if(Z)J.artist??=Z;let X=a0($,30);if(X)J.album??=X;let Q=a0($,4),W=Number.parseInt(Q,10);if(Number.isInteger(W)&&W>0)J.date??=new Date(W,0,1);let G=v($,30),U;if(G[28]===0&&G[29]!==0){let j=G[29];if(j>0)J.trackNumber??=j;$.skip(-30),U=a0($,28),$.skip(2)}else $.skip(-30),U=a0($,30);if(U)J.comment??=U;let q=T($);if(q<$1.length)J.genre??=$1[q]},a0=($,J)=>{let K=v($,J),Y=S0(K.indexOf(0),K.length),Z=K.subarray(0,Y),X="";for(let Q=0;Q<Z.length;Q++)X+=String.fromCharCode(Z[Q]);return X.trimEnd()},g0=($)=>{let J=$.filePos,K=k($,3),Y=T($),Z=T($),X=T($),Q=M($);if(K!=="ID3"||Y===255||Z===255||(Q&2155905152)!==0)return $.filePos=J,null;let W=K8(Q);return{majorVersion:Y,revision:Z,flags:X,size:W}},X8=($,J,K)=>{if(![2,3,4].includes(J.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${J.majorVersion}`);return}let Y=v($,J.size),Z=new qJ(J,Y);if(J.flags&t0.Footer)Z.removeFooter();if(J.flags&t0.Unsynchronisation&&J.majorVersion===3)Z.ununsynchronizeAll();if(J.flags&t0.ExtendedHeader){let X=Z.readU32();if(J.majorVersion===3)Z.pos+=X;else Z.pos+=X-4}while(Z.pos<=Z.bytes.length-Z.frameHeaderSize()){let X=Z.readId3V2Frame();if(!X)break;let Q=Z.pos,W=Z.pos+X.size,G=!1,U=!1,q=!1;if(J.majorVersion===3)G=!!(X.flags&64),U=!!(X.flags&128);else if(J.majorVersion===4)G=!!(X.flags&4),U=!!(X.flags&8),q=!!(X.flags&2)||!!(J.flags&t0.Unsynchronisation);if(G){console.warn(`Skipping encrypted ID3v2 frame ${X.id}`),Z.pos=W;continue}if(U){console.warn(`Skipping compressed ID3v2 frame ${X.id}`),Z.pos=W;continue}if(q)Z.ununsynchronizeRegion(Z.pos,W);if(K.raw??={},X.id[0]==="T")K.raw[X.id]??=Z.readId3V2EncodingAndText(W);else K.raw[X.id]??=Z.readBytes(X.size);switch(Z.pos=Q,X.id){case"TIT2":case"TT2":K.title??=Z.readId3V2EncodingAndText(W);break;case"TIT3":case"TT3":K.description??=Z.readId3V2EncodingAndText(W);break;case"TPE1":case"TP1":K.artist??=Z.readId3V2EncodingAndText(W);break;case"TALB":case"TAL":K.album??=Z.readId3V2EncodingAndText(W);break;case"TPE2":case"TP2":K.albumArtist??=Z.readId3V2EncodingAndText(W);break;case"TRCK":case"TRK":{let V=Z.readId3V2EncodingAndText(W).split("/"),N=Number.parseInt(V[0],10),A=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(N)&&N>0)K.trackNumber??=N;if(A&&Number.isInteger(A)&&A>0)K.tracksTotal??=A}break;case"TPOS":case"TPA":{let V=Z.readId3V2EncodingAndText(W).split("/"),N=Number.parseInt(V[0],10),A=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(N)&&N>0)K.discNumber??=N;if(A&&Number.isInteger(A)&&A>0)K.discsTotal??=A}break;case"TCON":case"TCO":{let j=Z.readId3V2EncodingAndText(W),V=/^\((\d+)\)/.exec(j);if(V){let N=Number.parseInt(V[1]);if($1[N]!==void 0){K.genre??=$1[N];break}}if(V=/^\d+$/.exec(j),V){let N=Number.parseInt(V[0]);if($1[N]!==void 0){K.genre??=$1[N];break}}K.genre??=j}break;case"TDRC":case"TDAT":{let j=Z.readId3V2EncodingAndText(W),V=new Date(j);if(!Number.isNaN(V.getTime()))K.date??=V}break;case"TYER":case"TYE":{let j=Z.readId3V2EncodingAndText(W),V=Number.parseInt(j,10);if(Number.isInteger(V))K.date??=new Date(V,0,1)}break;case"USLT":case"ULT":{let j=Z.readU8();Z.pos+=3,Z.readId3V2Text(j,W),K.lyrics??=Z.readId3V2Text(j,W)}break;case"COMM":case"COM":{let j=Z.readU8();Z.pos+=3,Z.readId3V2Text(j,W),K.comment??=Z.readId3V2Text(j,W)}break;case"APIC":case"PIC":{let j=Z.readId3V2TextEncoding(),V;if(J.majorVersion===2){let z=Z.readAscii(3);V=z==="PNG"?"image/png":z==="JPG"?"image/jpeg":"image/*"}else V=Z.readId3V2Text(j,W);let N=Z.readU8(),A=Z.readId3V2Text(j,W).trimEnd(),R=W-Z.pos;if(R>=0){let z=Z.readBytes(R);if(!K.images)K.images=[];K.images.push({data:z,mimeType:V,kind:N===3?"coverFront":N===4?"coverBack":"unknown",description:A})}}break;default:Z.pos+=X.size;break}Z.pos=W}};class qJ{constructor($,J){this.header=$,this.bytes=J,this.pos=0,this.view=new DataView(J.buffer,J.byteOffset,J.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let $=[];for(let J=0;J<this.bytes.length;J++){let K=this.bytes[J];if($.push(K),K===255&&J!==this.bytes.length-1){if(this.bytes[J]===0)J++}}this.bytes=new Uint8Array($),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion($,J){let K=[];for(let X=$;X<J;X++){let Q=this.bytes[X];if(K.push(Q),Q===255&&X!==J-1){if(this.bytes[X+1]===0)X++}}let Y=this.bytes.subarray(0,$),Z=this.bytes.subarray(J);this.bytes=new Uint8Array(Y.length+K.length+Z.length),this.bytes.set(Y,0),this.bytes.set(K,Y.length),this.bytes.set(Z,Y.length+K.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-J1),this.view=new DataView(this.bytes.buffer)}readBytes($){let J=this.bytes.subarray(this.pos,this.pos+$);return this.pos+=$,J}readU8(){let $=this.view.getUint8(this.pos);return this.pos+=1,$}readU16(){let $=this.view.getUint16(this.pos,!1);return this.pos+=2,$}readU24(){let $=this.view.getUint16(this.pos,!1),J=this.view.getUint8(this.pos+1);return this.pos+=3,$*256+J}readU32(){let $=this.view.getUint32(this.pos,!1);return this.pos+=4,$}readAscii($){let J="";for(let K=0;K<$;K++)J+=String.fromCharCode(this.view.getUint8(this.pos+K));return this.pos+=$,J}readId3V2Frame(){if(this.header.majorVersion===2){let $=this.readAscii(3);if($==="\x00\x00\x00")return null;let J=this.readU24();return{id:$,size:J,flags:0}}else{let $=this.readAscii(4);if($==="\x00\x00\x00\x00")return null;let J=this.readU32(),K=this.header.majorVersion===4?K8(J):J,Y=this.readU16(),Z=this.pos,X=(Q)=>{let W=this.pos+Q;if(W>this.bytes.length)return!1;if(W<=this.bytes.length-this.frameHeaderSize()){this.pos+=Q;let G=this.readAscii(4);if(G!=="\x00\x00\x00\x00"&&!/[0-9A-Z]{4}/.test(G))return!1}return!0};if(!X(K)){let Q=this.header.majorVersion===4?J:K8(J);if(X(Q))K=Q}return this.pos=Z,{id:$,size:K,flags:Y}}}readId3V2TextEncoding(){let $=this.readU8();if($>3)throw Error(`Unsupported text encoding: ${$}`);return $}readId3V2Text($,J){let K=this.pos,Y=this.readBytes(J-this.pos);switch($){case e0.ISO_8859_1:{let Z="";for(let X=0;X<Y.length;X++){let Q=Y[X];if(Q===0){this.pos=K+X+1;break}Z+=String.fromCharCode(Q)}return Z}case e0.UTF_16_WITH_BOM:if(Y[0]===255&&Y[1]===254){let Z=new TextDecoder("utf-16le"),X=S0(Y.findIndex((Q,W)=>Q===0&&Y[W+1]===0&&W%2===0),Y.length);return this.pos=K+Math.min(X+2,Y.length),Z.decode(Y.subarray(2,X))}else if(Y[0]===254&&Y[1]===255){let Z=new TextDecoder("utf-16be"),X=S0(Y.findIndex((Q,W)=>Q===0&&Y[W+1]===0&&W%2===0),Y.length);return this.pos=K+Math.min(X+2,Y.length),Z.decode(Y.subarray(2,X))}else{let Z=S0(Y.findIndex((X)=>X===0),Y.length);return this.pos=K+Math.min(Z+1,Y.length),l.decode(Y.subarray(0,Z))}case e0.UTF_16_BE_NO_BOM:{let Z=new TextDecoder("utf-16be"),X=S0(Y.findIndex((Q,W)=>Q===0&&Y[W+1]===0&&W%2===0),Y.length);return this.pos=K+Math.min(X+2,Y.length),Z.decode(Y.subarray(0,X))}case e0.UTF_8:{let Z=S0(Y.findIndex((X)=>X===0),Y.length);return this.pos=K+Math.min(Z+1,Y.length),l.decode(Y.subarray(0,Z))}}}readId3V2EncodingAndText($){if(this.pos>=$)return"";let J=this.readId3V2TextEncoding();return this.readId3V2Text(J,$)}}/*!
|
|
138
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
139
|
+
*
|
|
140
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
141
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
142
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
143
|
+
*/var F1=async($,J,K)=>{let Y=J;while(K===null||Y<K){let Z=$.requestSlice(Y,Y8);if(Z instanceof Promise)Z=await Z;if(!Z)break;let X=M(Z),Q=WJ(X,$.fileSize!==null?$.fileSize-Y:null);if(Q.header)return{header:Q.header,startPos:Y};Y+=Q.bytesAdvanced}return null};/*!
|
|
144
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
145
|
+
*
|
|
146
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
147
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
148
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
149
|
+
*/class i8 extends s{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new U0,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();if(!this.firstFrameHeader)throw Error("No valid MP3 frame found.");this.tracks=[new p(this.input,new UJ(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let Q=this.reader.requestSlice(this.lastLoadedPos,J1);if(Q instanceof Promise)Q=await Q;if(!Q){this.lastSampleLoaded=!0;return}let W=g0(Q);if(!W)break;this.lastLoadedPos=Q.filePos+W.size}let $=await F1(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!$){this.lastSampleLoaded=!0;return}let J=$.header;this.lastLoadedPos=$.startPos+J.totalSize-1;let K=QJ(J.mpegVersionId,J.channel),Y=this.reader.requestSlice($.startPos+K,4);if(Y instanceof Promise)Y=await Y;if(Y){let Q=M(Y);if(Q===XJ||Q===ZJ)return}if(!this.firstFrameHeader)this.firstFrameHeader=J;if(J.sampleRate!==this.firstFrameHeader.sampleRate)console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${J.sampleRate} Hz. Might be a bug, so please report this file.`);let Z=J.audioSamplesInFrame/this.firstFrameHeader.sampleRate,X={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:Z,dataStart:$.startPos,dataSize:J.totalSize};this.loadedSamples.push(X),this.nextTimestampInSamples+=J.audioSamplesInFrame;return}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getMetadataTags(){let $=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let J=0,K=!1;while(!0){let Y=this.reader.requestSlice(J,J1);if(Y instanceof Promise)Y=await Y;if(!Y)break;let Z=g0(Y);if(!Z)break;K=!0;let X=this.reader.requestSlice(Y.filePos,Z.size);if(X instanceof Promise)X=await X;if(!X)break;X8(X,Z,this.metadataTags),J=Y.filePos+Z.size}if(!K&&this.reader.fileSize!==null&&this.reader.fileSize>=z1){let Y=this.reader.requestSlice(this.reader.fileSize-z1,z1);if(Y instanceof Promise)Y=await Y;if(H(Y),k(Y,3)==="TAG")GJ(Y,this.metadataTags)}return this.metadataTags}finally{$()}}}class UJ{constructor($){this.demuxer=$}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return null}getLanguageCode(){return d}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}async getDecoderConfig(){return H(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex($,J){if($===-1)return null;let K=this.demuxer.loadedSamples[$];if(!K)return null;let Y;if(J.metadataOnly)Y=u;else{let Z=this.demuxer.reader.requestSlice(K.dataStart,K.dataSize);if(Z instanceof Promise)Z=await Z;if(!Z)return null;Y=v(Z,K.dataSize)}return new f(Y,"key",K.timestamp,K.duration,$,K.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let K=await this.demuxer.readingMutex.acquire();try{let Y=l0(this.demuxer.loadedSamples,$.timestamp,(X)=>X.timestamp);if(Y===-1)throw Error("Packet was not created from this track.");let Z=Y+1;while(Z>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(Z,J)}finally{K()}}async getPacket($,J){let K=await this.demuxer.readingMutex.acquire();try{while(!0){let Y=S(this.demuxer.loadedSamples,$,(Z)=>Z.timestamp);if(Y===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(Y,J);if(Y>=0&&Y+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(Y,J);await this.demuxer.advanceReader()}}finally{K()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
150
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
151
|
+
*
|
|
152
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
153
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
154
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
155
|
+
*/var s8=1399285583,RY=79764919,jJ=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let K=0;K<8;K++)J=J&2147483648?J<<1^RY:J<<1;jJ[$]=J>>>0&4294967295}var VJ=($)=>{let J=E($),K=J.getUint32(22,!0);J.setUint32(22,0,!0);let Y=0;for(let Z=0;Z<$.length;Z++){let X=$[Z];Y=(Y<<8^jJ[Y>>>24^X])>>>0}return J.setUint32(22,K,!0),Y},NJ=($,J,K)=>{let Y=0,Z=null;if($.length>0){if(J.codec==="vorbis"){H(J.vorbisInfo);let X=J.vorbisInfo.modeBlockflags.length,W=(1<<M$(X-1))-1<<1,G=($[0]&W)>>1;if(G>=J.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let U=K,q=J.vorbisInfo.modeBlockflags[G];if(Z=J.vorbisInfo.blocksizes[q],q===1){let j=(W|1)+1,V=$[0]&j?1:0;U=J.vorbisInfo.blocksizes[V]}Y=U!==null?U+Z>>2:0}else if(J.codec==="opus")Y=b$($).durationInSamples}return{durationInSamples:Y,vorbisBlockSize:Z}},HJ=($)=>{let J="audio/ogg";if($.codecStrings){let K=[...new Set($.codecStrings)];J+=`; codecs="${K.join(", ")}"`}return J};/*!
|
|
156
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
157
|
+
*
|
|
158
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
159
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
160
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
161
|
+
*/var P0=27,p0=282,AJ=p0+65025,Y1=($)=>{let J=$.filePos;if(u0($)!==s8)return null;$.skip(1);let Y=T($),Z=RJ($),X=u0($),Q=u0($),W=u0($),G=T($),U=new Uint8Array(G);for(let N=0;N<G;N++)U[N]=T($);let q=27+G,j=U.reduce((N,A)=>N+A,0),V=q+j;return{headerStartPos:J,totalSize:V,dataStartPos:J+q,dataSize:j,headerType:Y,granulePosition:Z,serialNumber:X,sequenceNumber:Q,checksum:W,lacingValues:U}},OJ=($,J)=>{while($.filePos<J-3){let K=u0($),Y=K&255,Z=K>>>8&255,X=K>>>16&255,Q=K>>>24&255,W=79;if(Y!==79&&Z!==79&&X!==79&&Q!==79)continue;if($.skip(-4),K===s8)return!0;$.skip(1)}return!1};/*!
|
|
162
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
163
|
+
*
|
|
164
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
165
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
166
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
167
|
+
*/class a8 extends s{constructor($){super($);this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,P0,p0);if(J instanceof Promise)J=await J;if(!J)break;let K=Y1(J);if(!K)break;if(!(K.headerType&2))break;this.bitstreams.push({serialNumber:K.serialNumber,bosPage:K,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),$=K.headerStartPos+K.totalSize}for(let J of this.bitstreams){let K=await this.readPacket(J.bosPage,0);if(!K)continue;if(K.data.byteLength>=7&&K.data[0]===1&&K.data[1]===118&&K.data[2]===111&&K.data[3]===114&&K.data[4]===98&&K.data[5]===105&&K.data[6]===115)await this.readVorbisMetadata(K,J);else if(K.data.byteLength>=8&&K.data[0]===79&&K.data[1]===112&&K.data[2]===117&&K.data[3]===115&&K.data[4]===72&&K.data[5]===101&&K.data[6]===97&&K.data[7]===100)await this.readOpusMetadata(K,J);if(J.codecInfo.codec!==null)this.tracks.push(new p(this.input,new _J(J,this)))}})()}async readVorbisMetadata($,J){let K=await this.findNextPacketStart($);if(!K)return;let Y=await this.readPacket(K.startPage,K.startSegmentIndex);if(!Y)return;if(K=await this.findNextPacketStart(Y),!K)return;let Z=await this.readPacket(K.startPage,K.startSegmentIndex);if(!Z)return;if(Y.data[0]!==3||Z.data[0]!==5)return;let X=[],Q=(q)=>{while(!0){if(X.push(Math.min(255,q)),q<255)break;q-=255}};Q($.data.length),Q(Y.data.length);let W=new Uint8Array(1+X.length+$.data.length+Y.data.length+Z.data.length);W[0]=2,W.set(X,1),W.set($.data,1+X.length),W.set(Y.data,1+X.length+$.data.length),W.set(Z.data,1+X.length+$.data.length+Y.data.length),J.codecInfo.codec="vorbis",J.description=W,J.lastMetadataPacket=Z;let G=E($.data);J.numberOfChannels=G.getUint8(11),J.sampleRate=G.getUint32(12,!0);let U=G.getUint8(28);J.codecInfo.vorbisInfo={blocksizes:[1<<(U&15),1<<(U>>4)],modeBlockflags:f$(Z.data).modeBlockflags},U1(Y.data.subarray(7),this.metadataTags)}async readOpusMetadata($,J){let K=await this.findNextPacketStart($);if(!K)return;let Y=await this.readPacket(K.startPage,K.startSegmentIndex);if(!Y)return;J.codecInfo.codec="opus",J.description=$.data,J.lastMetadataPacket=Y;let Z=E$($.data);J.numberOfChannels=Z.outputChannelCount,J.sampleRate=f0,J.codecInfo.opusInfo={preSkip:Z.preSkip},U1(Y.data.subarray(8),this.metadataTags)}async readPacket($,J){H(J<$.lacingValues.length);let K=0;for(let q=0;q<J;q++)K+=$.lacingValues[q];let Y=$,Z=K,X=J,Q=[];$:while(!0){let q=this.reader.requestSlice(Y.dataStartPos,Y.dataSize);if(q instanceof Promise)q=await q;H(q);let j=v(q,Y.dataSize);while(!0){if(X===Y.lacingValues.length){Q.push(j.subarray(K,Z));break}let N=Y.lacingValues[X];if(Z+=N,N<255){Q.push(j.subarray(K,Z));break $}X++}let V=Y.headerStartPos+Y.totalSize;while(!0){let N=this.reader.requestSliceRange(V,P0,p0);if(N instanceof Promise)N=await N;if(!N)return null;let A=Y1(N);if(!A)return null;if(Y=A,Y.serialNumber===$.serialNumber)break;V=Y.headerStartPos+Y.totalSize}K=0,Z=0,X=0}let W=Q.reduce((q,j)=>q+j.length,0),G=new Uint8Array(W),U=0;for(let q=0;q<Q.length;q++){let j=Q[q];G.set(j,U),U+=j.length}return{data:G,endPage:Y,endSegmentIndex:X}}async findNextPacketStart($){if($.endSegmentIndex<$.endPage.lacingValues.length-1)return{startPage:$.endPage,startSegmentIndex:$.endSegmentIndex+1};if(!!($.endPage.headerType&4))return null;let K=$.endPage.headerStartPos+$.endPage.totalSize;while(!0){let Y=this.reader.requestSliceRange(K,P0,p0);if(Y instanceof Promise)Y=await Y;if(!Y)return null;let Z=Y1(Y);if(!Z)return null;if(Z.serialNumber===$.endPage.serialNumber)return{startPage:Z,startSegmentIndex:0};K=Z.headerStartPos+Z.totalSize}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.getCodecParameterString()));return HJ({codecStrings:$.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((K)=>K.computeDuration()));return Math.max(0,...J)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class _J{constructor($,J){this.bitstream=$,this.demuxer=J,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new U0,this.internalSampleRate=$.codecInfo.codec==="opus"?f0:$.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return H(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return d}async getFirstTimestamp(){return 0}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}granulePositionToTimestampInSamples($){if(this.bitstream.codecInfo.codec==="opus")return H(this.bitstream.codecInfo.opusInfo),$-this.bitstream.codecInfo.opusInfo.preSkip;return $}createEncodedPacketFromOggPacket($,J,K){if(!$)return null;let{durationInSamples:Y,vorbisBlockSize:Z}=NJ($.data,this.bitstream.codecInfo,J.vorbisLastBlocksize),X=new f(K.metadataOnly?u:$.data,"key",Math.max(0,J.timestampInSamples)/this.internalSampleRate,Y/this.internalSampleRate,$.endPage.headerStartPos+$.endSegmentIndex,$.data.byteLength);return this.encodedPacketToMetadata.set(X,{packet:$,timestampInSamples:J.timestampInSamples,durationInSamples:Y,vorbisLastBlockSize:J.vorbisLastBlocksize,vorbisBlockSize:Z}),X}async getFirstPacket($){H(this.bitstream.lastMetadataPacket);let J=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!J)return null;let K=0;if(this.bitstream.codecInfo.codec==="opus")H(this.bitstream.codecInfo.opusInfo),K-=this.bitstream.codecInfo.opusInfo.preSkip;let Y=await this.demuxer.readPacket(J.startPage,J.startSegmentIndex);return this.createEncodedPacketFromOggPacket(Y,{timestampInSamples:K,vorbisLastBlocksize:null},$)}async getNextPacket($,J){let K=this.encodedPacketToMetadata.get($);if(!K)throw Error("Packet was not created from this track.");let Y=await this.demuxer.findNextPacketStart(K.packet);if(!Y)return null;let Z=K.timestampInSamples+K.durationInSamples,X=await this.demuxer.readPacket(Y.startPage,Y.startSegmentIndex);return this.createEncodedPacketFromOggPacket(X,{timestampInSamples:Z,vorbisLastBlocksize:K.vorbisBlockSize},J)}async getPacket($,J){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential($,J);let K=y0($*this.internalSampleRate,14);if(K===0)return this.getFirstPacket(J);if(K<0)return null;H(this.bitstream.lastMetadataPacket);let Y=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!Y)return null;let Z=Y.startPage,X=this.demuxer.reader.fileSize,Q=[Z];$:while(Z.headerStartPos+Z.totalSize<X){let O=Z.headerStartPos,F=Math.floor((O+X)/2),_=F;while(!0){let w=Math.min(_+AJ,X-P0),P=this.demuxer.reader.requestSlice(_,w-_);if(P instanceof Promise)P=await P;if(H(P),!OJ(P,w)){X=F+P0;continue $}let L=this.demuxer.reader.requestSliceRange(P.filePos,P0,p0);if(L instanceof Promise)L=await L;H(L);let h=Y1(L);H(h);let o=!1;if(h.serialNumber===this.bitstream.serialNumber)o=!0;else{let x=this.demuxer.reader.requestSlice(h.headerStartPos,h.totalSize);if(x instanceof Promise)x=await x;H(x);let v0=v(x,h.totalSize);o=VJ(v0)===h.checksum}if(!o){_=h.headerStartPos+4;continue}if(o&&h.serialNumber!==this.bitstream.serialNumber){_=h.headerStartPos+h.totalSize;continue}if(h.granulePosition===-1){_=h.headerStartPos+h.totalSize;continue}if(this.granulePositionToTimestampInSamples(h.granulePosition)>K)X=h.headerStartPos;else Z=h,Q.push(h);continue $}}let W=Y.startPage;for(let O of Q){if(O.granulePosition===Z.granulePosition)break;if(!W||O.headerStartPos>W.headerStartPos)W=O}let G=W,U=[G];while(!0){if(G.serialNumber===this.bitstream.serialNumber&&G.granulePosition===Z.granulePosition)break;let O=G.headerStartPos+G.totalSize,F=this.demuxer.reader.requestSliceRange(O,P0,p0);if(F instanceof Promise)F=await F;H(F);let _=Y1(F);if(H(_),G=_,G.serialNumber===this.bitstream.serialNumber)U.push(G)}H(G.granulePosition!==-1);let q=null,j,V,N=G,A=0;if(G.headerStartPos===Y.startPage.headerStartPos)j=this.granulePositionToTimestampInSamples(0),V=!0,q=0;else{j=0,V=!1;for(let _=G.lacingValues.length-1;_>=0;_--)if(G.lacingValues[_]<255){q=_+1;break}if(q===null)throw Error("Invalid page with granule position: no packets end on this page.");A=q-1;let O={data:u,endPage:N,endSegmentIndex:A};if(await this.demuxer.findNextPacketStart(O)){let _=FJ(U,G,q);H(_);let w=zJ(U,_.page,_.segmentIndex);if(w)G=w.page,q=w.segmentIndex}else while(!0){let _=FJ(U,G,q);if(!_)break;let w=zJ(U,_.page,_.segmentIndex);if(!w)break;if(G=w.page,q=w.segmentIndex,_.page.headerStartPos!==N.headerStartPos){N=_.page,A=_.segmentIndex;break}}}let R=null,z=null;while(G!==null){H(q!==null);let O=await this.demuxer.readPacket(G,q);if(!O)break;if(!(G.headerStartPos===Y.startPage.headerStartPos&&q<Y.startSegmentIndex)){let w=this.createEncodedPacketFromOggPacket(O,{timestampInSamples:j,vorbisLastBlocksize:z?.vorbisBlockSize??null},J);H(w);let P=this.encodedPacketToMetadata.get(w);if(H(P),!V&&O.endPage.headerStartPos===N.headerStartPos&&O.endSegmentIndex===A)j=this.granulePositionToTimestampInSamples(G.granulePosition),V=!0,w=this.createEncodedPacketFromOggPacket(O,{timestampInSamples:j-P.durationInSamples,vorbisLastBlocksize:z?.vorbisBlockSize??null},J),H(w),P=this.encodedPacketToMetadata.get(w),H(P);else j+=P.durationInSamples;if(R=w,z=P,V&&(Math.max(j,0)>K||Math.max(P.timestampInSamples,0)===K))break}let _=await this.demuxer.findNextPacketStart(O);if(!_)break;G=_.startPage,q=_.startSegmentIndex}return R}async getPacketSequential($,J){let K=await this.sequentialScanMutex.acquire();try{let Y=y0($*this.internalSampleRate,14);$=Y/this.internalSampleRate;let Z=S(this.sequentialScanCache,Y,(W)=>W.timestampInSamples),X;if(Z!==-1){let W=this.sequentialScanCache[Z];X=this.createEncodedPacketFromOggPacket(W.packet,{timestampInSamples:W.timestampInSamples,vorbisLastBlocksize:W.vorbisLastBlockSize},J)}else X=await this.getFirstPacket(J);let Q=0;while(X&&X.timestamp<$){let W=await this.getNextPacket(X,J);if(!W||W.timestamp>$)break;if(X=W,Q++,Q===100){Q=0;let G=this.encodedPacketToMetadata.get(X);if(H(G),this.sequentialScanCache.length>0)H(r(this.sequentialScanCache).timestampInSamples<=G.timestampInSamples);this.sequentialScanCache.push(G)}}return X}finally{K()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}var zJ=($,J,K)=>{let Y=J,Z=K;$:while(!0){Z--;for(Z;Z>=0;Z--)if(Y.lacingValues[Z]<255){Z++;break $}if(H(Z===-1),!(Y.headerType&1)){Z=0;break}let Q=L8($,(W)=>W.headerStartPos<Y.headerStartPos);if(!Q)return null;Y=Q,Z=Y.lacingValues.length}if(H(Z!==-1),Z===Y.lacingValues.length){let X=$[$.indexOf(Y)+1];H(X),Y=X,Z=0}return{page:Y,segmentIndex:Z}},FJ=($,J,K)=>{if(K>0)return{page:J,segmentIndex:K-1};let Y=L8($,(Z)=>Z.headerStartPos<J.headerStartPos);if(!Y)return null;return{page:Y,segmentIndex:Y.lacingValues.length-1}};/*!
|
|
168
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
169
|
+
*
|
|
170
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
171
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
172
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
173
|
+
*/var D0;(function($){$[$.PCM=1]="PCM",$[$.IEEE_FLOAT=3]="IEEE_FLOAT",$[$.ALAW=6]="ALAW",$[$.MULAW=7]="MULAW",$[$.EXTENSIBLE=65534]="EXTENSIBLE"})(D0||(D0={}));class e8 extends s{constructor($){super($);this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=this.reader.requestSlice(0,12);if($ instanceof Promise)$=await $;H($);let J=k($,4),K=J!=="RIFX",Y=J==="RF64",Z=w0($,K),X=Y?this.reader.fileSize:Math.min(Z+8,this.reader.fileSize??1/0);if(k($,4)!=="WAVE")throw Error("Invalid WAVE file - wrong format");let W=0,G=null,U=$.filePos;while(X===null||U<X){let j=this.reader.requestSlice(U,8);if(j instanceof Promise)j=await j;if(!j)break;let V=k(j,4),N=w0(j,K),A=j.filePos;if(Y&&W===0&&V!=="ds64")throw Error('Invalid RF64 file: First chunk must be "ds64".');if(V==="fmt ")await this.parseFmtChunk(A,N,K);else if(V==="data"){if(G??=N,this.dataStart=j.filePos,this.dataSize=Math.min(G,(X??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(V==="ds64"){let R=this.reader.requestSlice(A,N);if(R instanceof Promise)R=await R;if(!R)break;let z=t8(R,K);G=t8(R,K),X=Math.min(z+8,this.reader.fileSize??1/0)}else if(V==="LIST")await this.parseListChunk(A,N,K);else if(V==="ID3 "||V==="id3 ")await this.parseId3Chunk(A,N);U=A+N+(N&1),W++}if(!this.audioInfo)throw Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw Error('Invalid WAVE file - missing "data" chunk');let q=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/q)*q,this.tracks.push(new p(this.input,new CJ(this)))})()}async parseFmtChunk($,J,K){let Y=this.reader.requestSlice($,J);if(Y instanceof Promise)Y=await Y;if(!Y)return;let Z=X1(Y,K),X=X1(Y,K),Q=w0(Y,K);Y.skip(4);let W=X1(Y,K),G;if(J===14)G=8;else G=X1(Y,K);if(J>=18&&Z!==357){let U=X1(Y,K),q=J-18;if(Math.min(q,U)>=22&&Z===D0.EXTENSIBLE){Y.skip(6);let V=v(Y,16);Z=V[0]|V[1]<<8}}if(Z===D0.MULAW||Z===D0.ALAW)G=8;this.audioInfo={format:Z,numberOfChannels:X,sampleRate:Q,sampleSizeInBytes:Math.ceil(G/8),blockSizeInBytes:W}}async parseListChunk($,J,K){let Y=this.reader.requestSlice($,J);if(Y instanceof Promise)Y=await Y;if(!Y)return;let Z=k(Y,4);if(Z!=="INFO"&&Z!=="INF0")return;let X=Y.filePos;while(X<=$+J-8){Y.filePos=X;let Q=k(Y,4),W=w0(Y,K),G=v(Y,W),U=0;for(let j=0;j<G.length;j++){if(G[j]===0)break;U++}let q=String.fromCharCode(...G.subarray(0,U));switch(this.metadataTags.raw??={},this.metadataTags.raw[Q]=q,Q){case"INAM":case"TITL":this.metadataTags.title??=q;break;case"TIT3":this.metadataTags.description??=q;break;case"IART":this.metadataTags.artist??=q;break;case"IPRD":this.metadataTags.album??=q;break;case"IPRT":case"ITRK":case"TRCK":{let j=q.split("/"),V=Number.parseInt(j[0],10),N=j[1]&&Number.parseInt(j[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"ICRD":case"IDIT":{let j=new Date(q);if(!Number.isNaN(j.getTime()))this.metadataTags.date??=j}break;case"YEAR":{let j=Number.parseInt(q,10);if(Number.isInteger(j)&&j>0)this.metadataTags.date??=new Date(j,0,1)}break;case"IGNR":case"GENR":this.metadataTags.genre??=q;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=q;break}X+=8+W+(W&1)}}async parseId3Chunk($,J){let K=this.reader.requestSlice($,J);if(K instanceof Promise)K=await K;if(!K)return;let Y=g0(K);if(Y){let Z=K.slice($+10,Y.size);X8(Z,Y,this.metadataTags)}}getCodec(){if(H(this.audioInfo),this.audioInfo.format===D0.MULAW)return"ulaw";if(this.audioInfo.format===D0.ALAW)return"alaw";if(this.audioInfo.format===D0.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";else if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";else if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";else if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===D0.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32"}return null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}var K1=2048;class CJ{constructor($){this.demuxer=$}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let $=this.demuxer.getCodec();if(!$)return null;return H(this.demuxer.audioInfo),{codec:$,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getNumberOfChannels(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return d}async getFirstTimestamp(){return 0}async getPacketAtIndex($,J){H(this.demuxer.audioInfo);let K=$*K1*this.demuxer.audioInfo.blockSizeInBytes;if(K>=this.demuxer.dataSize)return null;let Y=Math.min(K1*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-K);if(this.demuxer.reader.fileSize===null){let W=this.demuxer.reader.requestSlice(this.demuxer.dataStart+K,Y);if(W instanceof Promise)W=await W;if(!W)return null}let Z;if(J.metadataOnly)Z=u;else{let W=this.demuxer.reader.requestSlice(this.demuxer.dataStart+K,Y);if(W instanceof Promise)W=await W;H(W),Z=v(W,Y)}let X=$*K1/this.demuxer.audioInfo.sampleRate,Q=Y/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max($,X),new f(Z,"key",X,Q,$,Y)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getPacket($,J){H(this.demuxer.audioInfo);let K=Math.floor(Math.min($*this.demuxer.audioInfo.sampleRate/K1,(this.demuxer.dataSize-1)/(K1*this.demuxer.audioInfo.blockSizeInBytes))),Y=await this.getPacketAtIndex(K,J);if(Y)return Y;if(K===0)return null;H(this.demuxer.reader.fileSize===null);let Z=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,J);while(Z){let X=await this.getNextPacket(Z,J);if(!X)break;Z=X}return Z}getNextPacket($,J){H(this.demuxer.audioInfo);let K=Math.round($.timestamp*this.demuxer.audioInfo.sampleRate/K1);return this.getPacketAtIndex(K+1,J)}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
174
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
175
|
+
*
|
|
176
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
177
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
178
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
179
|
+
*/var Z1=7,Q1=9,_1=($)=>{let J=$.filePos,K=v($,9),Y=new b(K);if(Y.readBits(12)!==4095)return null;if(Y.skipBits(1),Y.readBits(2)!==0)return null;let Q=Y.readBits(1),W=Y.readBits(2)+1,G=Y.readBits(4);if(G===15)return null;Y.skipBits(1);let U=Y.readBits(3);if(U===0)throw Error("ADTS frames with channel configuration 0 are not supported.");Y.skipBits(1),Y.skipBits(1),Y.skipBits(1),Y.skipBits(1);let q=Y.readBits(13);Y.skipBits(11);let j=Y.readBits(2)+1;if(j!==1)throw Error("ADTS frames with more than one AAC frame are not supported.");let V=null;if(Q===1)$.filePos-=2;else V=Y.readBits(16);return{objectType:W,samplingFrequencyIndex:G,channelConfiguration:U,frameLength:q,numberOfAacFrames:j,crcCheck:V,startPos:J}};/*!
|
|
180
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
181
|
+
*
|
|
182
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
183
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
184
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
185
|
+
*/var $$=1024;class J$ extends s{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new U0,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();H(this.firstFrameHeader),this.tracks=[new p(this.input,new DJ(this))]})()}async advanceReader(){let $=this.reader.requestSliceRange(this.lastLoadedPos,Z1,Q1);if($ instanceof Promise)$=await $;if(!$){this.lastSampleLoaded=!0;return}let J=_1($);if(!J){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&J.startPos+J.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}if(!this.firstFrameHeader)this.firstFrameHeader=J;let K=q1[J.samplingFrequencyIndex];H(K!==void 0);let Y=$$/K,Z=J.crcCheck?Q1:Z1,X={timestamp:this.nextTimestampInSamples/K,duration:Y,dataStart:J.startPos+Z,dataSize:J.frameLength-Z};this.loadedSamples.push(X),this.nextTimestampInSamples+=$$,this.lastLoadedPos=J.startPos+J.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getMetadataTags(){return{}}}class DJ{constructor($){this.demuxer=$}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/$$}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return null}getLanguageCode(){return d}getCodec(){return"aac"}getInternalCodecId(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){H(this.demuxer.firstFrameHeader);let $=v8[this.demuxer.firstFrameHeader.channelConfiguration];return H($!==void 0),$}getSampleRate(){H(this.demuxer.firstFrameHeader);let $=q1[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return H($!==void 0),$}async getDecoderConfig(){H(this.demuxer.firstFrameHeader);let $=new Uint8Array(3),J=new b($),{objectType:K,samplingFrequencyIndex:Y,channelConfiguration:Z}=this.demuxer.firstFrameHeader;if(K>31)J.writeBits(5,31),J.writeBits(6,K-32);else J.writeBits(5,K);return J.writeBits(4,Y),J.writeBits(4,Z),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:$.subarray(0,Math.ceil((J.pos-1)/8))}}async getPacketAtIndex($,J){if($===-1)return null;let K=this.demuxer.loadedSamples[$];if(!K)return null;let Y;if(J.metadataOnly)Y=u;else{let Z=this.demuxer.reader.requestSlice(K.dataStart,K.dataSize);if(Z instanceof Promise)Z=await Z;if(!Z)return null;Y=v(Z,K.dataSize)}return new f(Y,"key",K.timestamp,K.duration,$,K.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let K=await this.demuxer.readingMutex.acquire();try{let Y=l0(this.demuxer.loadedSamples,$.timestamp,(X)=>X.timestamp);if(Y===-1)throw Error("Packet was not created from this track.");let Z=Y+1;while(Z>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(Z,J)}finally{K()}}async getPacket($,J){let K=await this.demuxer.readingMutex.acquire();try{while(!0){let Y=S(this.demuxer.loadedSamples,$,(Z)=>Z.timestamp);if(Y===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(Y,J);if(Y>=0&&Y+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(Y,J);await this.demuxer.advanceReader()}}finally{K()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
186
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
187
|
+
*
|
|
188
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
189
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
190
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
191
|
+
*/var wJ=($)=>{if($===0)return null;else if($===1)return 192;else if($>=2&&$<=5)return 144*2**$;else if($===6)return"uncommon-u8";else if($===7)return"uncommon-u16";else if($>=8&&$<=15)return 2**$;else return null},MJ=($,J)=>{switch($){case 0:return J;case 1:return 88200;case 2:return 176400;case 3:return 192000;case 4:return 8000;case 5:return 16000;case 6:return 22050;case 7:return 24000;case 8:return 32000;case 9:return 44100;case 10:return 48000;case 11:return 96000;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},LJ=($)=>{let J=0,K=new b(v($,1));while(K.readBits(1)===1)J++;if(J===0)return K.readBits(7);let Y=[],Z=J-1,X=new b(v($,Z)),Q=8-J-1;for(let G=0;G<Q;G++)Y.unshift(K.readBits(1));for(let G=0;G<Z;G++)for(let U=0;U<8;U++){let q=X.readBits(1);if(U<2)continue;Y.unshift(q)}return Y.reduce((G,U,q)=>{return G|U<<q},0)},TJ=($,J)=>{if(J==="uncommon-u16")return m($)+1;else if(J==="uncommon-u8")return T($)+1;else if(typeof J==="number")return J;else W0(J),H(!1)},BJ=($,J)=>{if(J==="uncommon-u16")return m($);if(J==="uncommon-u16-10")return m($)*10;if(J==="uncommon-u8")return T($);if(typeof J==="number")return J;return null},PJ=($)=>{let K=0;for(let Y of $){K^=Y;for(let Z=0;Z<8;Z++){if((K&128)!==0)K=K<<1^7;else K<<=1;K&=255}}return K};/*!
|
|
192
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
193
|
+
*
|
|
194
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
195
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
196
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
197
|
+
*/class Y$ extends s{constructor($){super($);this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new U0,this.lastSampleLoaded=!1,this.reader=$._reader}async computeDuration(){return await this.readMetadata(),H(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),H(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let $=4;return this.metadataPromise??=(async()=>{while(this.reader.fileSize===null||$<this.reader.fileSize){let J=this.reader.requestSlice($,4);if(J instanceof Promise)J=await J;if($+=4,J===null)throw Error(`Metadata block at position ${$} is too small! Corrupted file.`);H(J);let K=T(J),Y=T0(J),Z=(K&128)!==0;switch(K&127){case N0.STREAMINFO:{let Q=this.reader.requestSlice($,Y);if(Q instanceof Promise)Q=await Q;if(H(Q),Q===null)throw Error(`StreamInfo block at position ${$} is too small! Corrupted file.`);let W=v(Q,34),G=new b(W),U=G.readBits(16),q=G.readBits(16),j=G.readBits(24),V=G.readBits(24),N=G.readBits(20),A=G.readBits(3)+1;G.readBits(5);let R=G.readBits(36);G.skipBits(128);let z=new Uint8Array(42);z.set(new Uint8Array([102,76,97,67]),0),z.set(new Uint8Array([128,0,0,34]),4),z.set(W,8),this.audioInfo={numberOfChannels:A,sampleRate:N,totalSamples:R,minimumBlockSize:U,maximumBlockSize:q,minimumFrameSize:j,maximumFrameSize:V,description:z},this.track=new p(this.input,new vJ(this));break}case N0.VORBIS_COMMENT:{let Q=this.reader.requestSlice($,Y);if(Q instanceof Promise)Q=await Q;H(Q),U1(v(Q,Y),this.metadataTags);break}case N0.PICTURE:{let Q=this.reader.requestSlice($,Y);if(Q instanceof Promise)Q=await Q;H(Q);let W=M(Q),G=M(Q),U=l.decode(v(Q,G)),q=M(Q),j=l.decode(v(Q,q));Q.skip(16);let V=M(Q),N=v(Q,V);this.metadataTags.images??=[],this.metadataTags.images.push({data:N,mimeType:U,kind:W===3?"coverFront":W===4?"coverBack":"unknown",description:j});break}default:break}if($+=Y,Z){this.lastLoadedPos=$;break}}})()}async readNextFlacFrame({startPos:$,isFirstPacket:J}){H(this.audioInfo);let K=6,Y=16,Z=this.audioInfo.maximumFrameSize+Y,X=await this.reader.requestSliceRange($,this.audioInfo.minimumFrameSize,Z);if(!X)return null;let Q=this.readFlacFrameHeader({slice:X,isFirstPacket:J});if(!Q)return null;X.filePos=$+this.audioInfo.minimumFrameSize;while(!0){if(X.filePos>X.end-K)return{num:Q.num,blockSize:Q.blockSize,sampleRate:Q.sampleRate,size:X.end-$,isLastFrame:!0};if(T(X)===255){let G=T(X),U=this.blockingBit===1?249:248;if(G!==U){X.skip(-1);continue}X.skip(-2);let q=X.filePos-$;if(!this.readFlacFrameHeader({slice:X,isFirstPacket:!1})){X.skip(-1);continue}return{num:Q.num,blockSize:Q.blockSize,sampleRate:Q.sampleRate,size:q,isLastFrame:!1}}}}readFlacFrameHeader({slice:$,isFirstPacket:J}){let K=$.filePos,Y=v($,4),Z=new b(Y);if(Z.readBits(15)!==32764)return null;if(this.blockingBit===null){H(J);let R=Z.readBits(1);this.blockingBit=R}else if(this.blockingBit===1){if(H(!J),Z.readBits(1)!==1)return null}else if(this.blockingBit===0){if(H(!J),Z.readBits(1)!==0)return null}else throw Error("Invalid blocking bit");let Q=wJ(Z.readBits(4));if(!Q)return null;H(this.audioInfo);let W=MJ(Z.readBits(4),this.audioInfo.sampleRate);if(!W)return null;if(Z.readBits(4),Z.readBits(3),Z.readBits(1)!==0)return null;let U=LJ($),q=TJ($,Q),j=BJ($,W);if(j===null)return null;let V=$.filePos-K,N=T($);$.skip(-V),$.skip(-1);let A=PJ(v($,V));if(N!==A)return null;return{num:U,blockSize:q,sampleRate:j}}async advanceReader(){await this.readMetadata(),H(this.lastLoadedPos!==null),H(this.audioInfo);let $=this.lastLoadedPos,J=await this.readNextFlacFrame({startPos:$,isFirstPacket:this.loadedSamples.length===0});if(!J){this.lastSampleLoaded=!0;return}let K=this.loadedSamples[this.loadedSamples.length-1],Z={blockOffset:K?K.blockOffset+K.blockSize:0,blockSize:J.blockSize,byteOffset:$,byteSize:J.size};if(this.lastLoadedPos=this.lastLoadedPos+J.size,this.loadedSamples.push(Z),J.isLastFrame){this.lastSampleLoaded=!0;return}}}class vJ{constructor($){this.demuxer=$}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let $=await this.getPacket(1/0,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getSampleRate(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return d}getTimeResolution(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}async getFirstTimestamp(){return 0}async getDecoderConfig(){return H(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket($,J){if(H(this.demuxer.audioInfo),$<0)throw Error("Timestamp cannot be negative");let K=await this.demuxer.readingMutex.acquire();try{while(!0){let Y=S(this.demuxer.loadedSamples,$,(W)=>W.blockOffset/this.demuxer.audioInfo.sampleRate);if(Y===-1){await this.demuxer.advanceReader();continue}let Z=this.demuxer.loadedSamples[Y],X=Z.blockOffset/this.demuxer.audioInfo.sampleRate,Q=Z.blockSize/this.demuxer.audioInfo.sampleRate;if(X+Q<=$){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,J);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(Y,J)}}finally{K()}}async getNextPacket($,J){let K=await this.demuxer.readingMutex.acquire();try{let Y=$.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&Y>=this.demuxer.loadedSamples.length)return null;while(Y>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(Y,J)}finally{K()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}async getPacketAtIndex($,J){let K=this.demuxer.loadedSamples[$];if(!K)return null;let Y;if(J.metadataOnly)Y=u;else{let Q=this.demuxer.reader.requestSlice(K.byteOffset,K.byteSize);if(Q instanceof Promise)Q=await Q;if(!Q)return null;Y=v(Q,K.byteSize)}H(this.demuxer.audioInfo);let Z=K.blockOffset/this.demuxer.audioInfo.sampleRate,X=K.blockSize/this.demuxer.audioInfo.sampleRate;return new f(Y,"key",Z,X,$,K.byteSize)}async getFirstPacket($){while(this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,$)}}/*!
|
|
198
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
199
|
+
*
|
|
200
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
201
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
202
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
203
|
+
*/class Z0{}class Z8 extends Z0{async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;if(J.skip(4),k(J,4)!=="ftyp")return null;return k(J,4)}_createDemuxer($){return new u8($)}}class K$ extends Z8{async _canReadInput($){let J=await this._getMajorBrand($);return!!J&&J!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class X$ extends Z8{async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Q8 extends Z0{async isSupportedEBMLOfDocType($,J){let K=$._reader.requestSlice(0,Y0);if(K instanceof Promise)K=await K;if(!K)return!1;let Y=l8(K);if(Y===null)return!1;if(Y<1||Y>8)return!1;if(y(K,Y)!==C.EBML)return!1;let X=d8(K);if(X===null)return!1;let Q=$._reader.requestSlice(K.filePos,X);if(Q instanceof Promise)Q=await Q;if(!Q)return!1;let W=K.filePos;while(Q.filePos<=W+X-a){let G=K0(Q);if(!G)break;let{id:U,size:q}=G,j=Q.filePos;if(q===null)return!1;switch(U){case C.EBMLVersion:if(y(Q,q)!==1)return!1;break;case C.EBMLReadVersion:if(y(Q,q)!==1)return!1;break;case C.DocType:if(B0(Q,q)!==J)return!1;break;case C.DocTypeVersion:if(y(Q,q)>4)return!1;break}Q.filePos=j+q}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new n8($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Z$ extends Q8{_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Q$ extends Z0{async _canReadInput($){let J=$._reader.requestSlice(0,10);if(J instanceof Promise)J=await J;if(!J)return!1;let K=0,Y=!1;while(!0){let G=$._reader.requestSlice(K,J1);if(G instanceof Promise)G=await G;if(!G)break;let U=g0(G);if(!U)break;Y=!0,K=G.filePos+U.size}let Z=await F1($._reader,K,K+4096);if(!Z)return!1;if(Y)return!0;K=Z.startPos+Z.header.totalSize;let X=await F1($._reader,K,K+Y8);if(!X)return!1;let Q=Z.header,W=X.header;if(Q.channel!==W.channel||Q.sampleRate!==W.sampleRate)return!1;return!0}_createDemuxer($){return new i8($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class W$ extends Z0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let K=k(J,4);if(K!=="RIFF"&&K!=="RIFX"&&K!=="RF64")return!1;return J.skip(4),k(J,4)==="WAVE"}_createDemuxer($){return new e8($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class G$ extends Z0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return k(J,4)==="OggS"}_createDemuxer($){return new a8($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class q$ extends Z0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return k(J,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new Y$($)}}class U$ extends Z0{async _canReadInput($){let J=$._reader.requestSliceRange(0,Z1,Q1);if(J instanceof Promise)J=await J;if(!J)return!1;let K=_1(J);if(!K)return!1;if(J=$._reader.requestSliceRange(K.frameLength,Z1,Q1),J instanceof Promise)J=await J;if(!J)return!1;let Y=_1(J);if(!Y)return!1;return K.objectType===Y.objectType&&K.samplingFrequencyIndex===Y.samplingFrequencyIndex&&K.channelConfiguration===Y.channelConfiguration}_createDemuxer($){return new J$($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}var hJ=new K$,xJ=new X$,yJ=new Q8,SJ=new Z$,EJ=new Q$,bJ=new W$,fJ=new G$,IJ=new U$,kJ=new q$,j$=[hJ,xJ,yJ,SJ,bJ,fJ,kJ,EJ,IJ];var gJ=(()=>({}));/*!
|
|
204
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
205
|
+
*
|
|
206
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
207
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
208
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
209
|
+
*/var zY=typeof gJ<"u"?gJ:void 0;class q0{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new c;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new c;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}}class W8 extends q0{constructor($){if(!($ instanceof ArrayBuffer)&&!ArrayBuffer.isView($))throw TypeError("buffer must be an ArrayBuffer or ArrayBufferView.");super();this._onreadCalled=!1,this._bytes=$0($),this._view=E($)}_retrieveSize(){return this._bytes.byteLength}_read(){if(!this._onreadCalled)this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0;return{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class G8 extends q0{constructor($,J={}){if(!($ instanceof Blob))throw TypeError("blob must be a Blob.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!M0(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._readers=new WeakMap,this._blob=$,this._orchestrator=new V8({maxCacheSize:J.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:N$.fileSystem})}_retrieveSize(){let $=this._blob.size;return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){let J=this._readers.get($);if(J===void 0){if("stream"in this._blob)J=this._blob.slice($.currentPos).stream().getReader();else J=null;this._readers.set($,J)}while($.currentPos<$.targetPos&&!$.aborted)if(J){let{done:K,value:Y}=await J.read();if(K){if(this._orchestrator.forgetWorker($),$.currentPos<$.targetPos)throw Error("Blob reader stopped unexpectedly before all requested data was read.");break}this.onread?.($.currentPos,$.currentPos+Y.length),this._orchestrator.supplyWorkerData($,Y)}else{let K=await this._blob.slice($.currentPos,$.targetPos).arrayBuffer();this.onread?.($.currentPos,$.currentPos+K.byteLength),this._orchestrator.supplyWorkerData($,new Uint8Array(K))}$.running=!1}_dispose(){this._orchestrator.dispose()}}var uJ=524288,FY=($,J,K)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))){let Z=null;try{if(typeof window<"u"&&typeof window.location<"u")Z=new URL(K instanceof Request?K.url:K,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&Z!==null&&Z!==window.location.origin)return null}return Math.min(2**($-2),16)};class q8 extends q0{constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!M0(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");super();this._existingResponses=new WeakMap,this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??FY,this._orchestrator=new V8({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:N$.network})}async _retrieveSize(){let $=new AbortController,J=await B8(this._options.fetchFn??fetch,this._url,T8(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:$.signal}),this._getRetryDelay);if(!J.ok)throw Error(`Error fetching ${String(this._url)}: ${J.status} ${J.statusText}`);let K,Y;if(J.status===206)Y=this._getPartialLengthFromRangeResponse(J),K=this._orchestrator.createWorker(0,Math.min(Y,uJ));else{let Z=J.headers.get("Content-Length");if(Z)Y=Number(Z),K=this._orchestrator.createWorker(0,Y),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw Error(`HTTP response (status ${J.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=Y,this._existingResponses.set(K,{response:J,abortController:$}),this._orchestrator.runWorker(K),Y}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while(!$.aborted){let J=this._existingResponses.get($);this._existingResponses.delete($);let K=J?.abortController,Y=J?.response;if(!K)K=new AbortController,Y=await B8(this._options.fetchFn??fetch,this._url,T8(this._options.requestInit??{},{headers:{Range:`bytes=${$.currentPos}-`},signal:K.signal}),this._getRetryDelay);if(H(Y),!Y.ok)throw Error(`Error fetching ${String(this._url)}: ${Y.status} ${Y.statusText}`);if($.currentPos>0&&Y.status!==206)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");let Z=this._getPartialLengthFromRangeResponse(Y),X=$.targetPos-$.currentPos;if(Z<X)throw Error(`HTTP response unexpectedly too short: Needed at least ${X} bytes, got only ${Z}.`);if(!Y.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let Q=Y.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){K.abort(),$.running=!1;return}let W;try{W=await Q.read()}catch(q){let j=this._getRetryDelay(1,q,this._url);if(j!==null){console.error("Error while reading response stream. Attempting to resume.",q),await new Promise((V)=>setTimeout(V,1000*j));break}else throw q}let{done:G,value:U}=W;if(G){if(this._orchestrator.forgetWorker($),$.currentPos<$.targetPos)throw Error("Response stream reader stopped unexpectedly before all requested data was read.");$.running=!1;return}this.onread?.($.currentPos,$.currentPos+U.length),this._orchestrator.supplyWorkerData($,U)}}$.running=!1}_getPartialLengthFromRangeResponse($){let J=$.headers.get("Content-Range");if(J){let K=/\/(\d+)/.exec(J);if(K)return Number(K[1]);else throw Error(`Invalid Content-Range header: ${J}`)}else{let K=$.headers.get("Content-Length");if(K)return Number(K);else throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}}_dispose(){this._orchestrator.dispose()}}class U8 extends q0{constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!M0(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._fileHandle=null,this._streamSource=new V$({getSize:async()=>{return this._fileHandle=await zY.fs.open($,"r"),(await this._fileHandle.stat()).size},read:async(K,Y)=>{H(this._fileHandle);let Z=new Uint8Array(Y-K);return await this._fileHandle.read(Z,0,Y-K,K),Z},maxCacheSize:J.maxCacheSize,prefetchProfile:"fileSystem"})}_read($,J){return this._streamSource._read($,J)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class V$ extends q0{constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(typeof $.getSize!=="function")throw TypeError("options.getSize must be a function.");if(typeof $.read!=="function")throw TypeError("options.read must be a function.");if($.dispose!==void 0&&typeof $.dispose!=="function")throw TypeError("options.dispose, when provided, must be a function.");if($.maxCacheSize!==void 0&&(!M0($.maxCacheSize)||$.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if($.prefetchProfile&&!["none","fileSystem","network"].includes($.prefetchProfile))throw TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._options=$,this._orchestrator=new V8({maxCacheSize:$.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:N$[$.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let $=this._options.getSize();if($ instanceof Promise)return $.then((J)=>{if(!Number.isInteger(J)||J<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=J,J});else{if(!Number.isInteger($)||$<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=$,$}}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while($.currentPos<$.targetPos&&!$.aborted){let{currentPos:J,targetPos:K}=$,Y=this._options.read($.currentPos,K);if(Y instanceof Promise)Y=await Y;if(Y instanceof Uint8Array){if(Y=$0(Y),Y.length!==K-$.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${K-$.currentPos} bytes, but got ${Y.length}.`);this.onread?.($.currentPos,$.currentPos+Y.length),this._orchestrator.supplyWorkerData($,Y)}else if(Y instanceof ReadableStream){let Z=Y.getReader();while($.currentPos<K&&!$.aborted){let{done:X,value:Q}=await Z.read();if(X){if($.currentPos<K)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${K-J} bytes, but got ${$.currentPos-J}`);break}if(!(Q instanceof Uint8Array))throw TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");let W=$0(Q);this.onread?.($.currentPos,$.currentPos+W.length),this._orchestrator.supplyWorkerData($,W)}}else throw TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}$.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}class j8 extends q0{constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!M0(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=$,this._maxCacheSize=J.maxCacheSize??16777216}_retrieveSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let K=S(this._cache,$,(U)=>U.start),Y=K!==-1?this._cache[K]:null;if(Y&&Y.start<=$&&J<=Y.end)return{bytes:Y.bytes,view:Y.view,offset:Y.start};let Z=$,X=new Uint8Array(J-$);if(K!==-1)for(let U=K;U<this._cache.length;U++){let q=this._cache[U];if(q.start>=J)break;let j=Math.max($,q.start);if(j>Z)this._throwDueToCacheMiss();let V=Math.min(J,q.end);if(j<V)X.set(q.bytes.subarray(j-q.start,V-q.start),j-$),Z=V}if(Z===J)return{bytes:X,view:E(X),offset:$};if(this._currentIndex>Z)this._throwDueToCacheMiss();let{promise:Q,resolve:W,reject:G}=n();if(this._pendingSlices.push({start:$,end:J,bytes:X,resolve:W,reject:G}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((U)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((q)=>q.reject(U)),this._pendingSlices.length=0;else throw U});return Q}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let Z of this._pendingSlices)Z.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let K=this._currentIndex,Y=this._currentIndex+J.byteLength;for(let Z=0;Z<this._pendingSlices.length;Z++){let X=this._pendingSlices[Z],Q=Math.max(K,X.start),W=Math.min(Y,X.end);if(Q<W){if(X.bytes.set(J.subarray(Q-K,W-K),Q-X.start),W===X.end)X.resolve({bytes:X.bytes,view:E(X.bytes),offset:X.start}),this._pendingSlices.splice(Z,1),Z--}}this._cache.push({start:K,end:Y,bytes:J,view:E(J),age:0});while(this._cache.length>0){let Z=this._cache[0];if(this._maxRequestedIndex-Z.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}var N$={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,K)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let Z of K){let Q=Math.max((Z.startPos+Z.targetPos)/2,Z.targetPos-8388608);if(y1($,J,Q,Z.targetPos)){let W=Z.targetPos-Z.startPos,G=Math.ceil((W+1)/8388608)*8388608,U=2**Math.ceil(Math.log2(W+1)),q=Math.min(U,G);J=Math.max(J,Z.startPos+q)}}return J=Math.max(J,$+uJ),{start:$,end:J}}};class V8{constructor($){this.options=$,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read($,J){H(this.fileSize!==null);let K=this.options.prefetchProfile($,J,this.workers),Y=Math.max(K.start,0),Z=Math.min(K.end,this.fileSize);H(Y<=$&&J<=Z);let X=null,Q=S(this.cache,$,(O)=>O.start),W=Q!==-1?this.cache[Q]:null;if(W&&W.start<=$&&J<=W.end)W.age=this.nextAge++,X={bytes:W.bytes,view:W.view,offset:W.start};let G=S(this.cache,Y,(O)=>O.start),U=X?null:new Uint8Array(J-$),q=0,j=Y,V=[];if(G!==-1){for(let O=G;O<this.cache.length;O++){let F=this.cache[O];if(F.start>=Z)break;if(F.end<=Y)continue;let _=Math.max(Y,F.start),w=Math.min(Z,F.end);if(H(_<=w),j<_)V.push({start:j,end:_});if(j=w,U){let P=Math.max($,F.start),D=Math.min(J,F.end);if(P<D){let L=P-$;if(U.set(F.bytes.subarray(P-F.start,D-F.start),L),L===q)q=D-$}}F.age=this.nextAge++}if(j<Z)V.push({start:j,end:Z})}else V.push({start:Y,end:Z});if(U&&q>=U.length)X={bytes:U,view:E(U),offset:$};if(V.length===0)return H(X),X;let{promise:N,resolve:A,reject:R}=n(),z=[];for(let O of V){let F=Math.max($,O.start),_=Math.min(J,O.end);if(F===O.start&&_===O.end)z.push(O);else if(F<_)z.push({start:F,end:_})}for(let O of V){let F=U&&{start:$,bytes:U,holes:z,resolve:A,reject:R},_=!1;for(let w of this.workers)if(y1(O.start-131072,O.start,w.currentPos,w.targetPos)){if(w.targetPos=Math.max(w.targetPos,O.end),_=!0,F&&!w.pendingSlices.includes(F))w.pendingSlices.push(F);if(!w.running)this.runWorker(w);break}if(!_){let w=this.createWorker(O.start,O.end);if(F)w.pendingSlices=[F];this.runWorker(w)}}if(!X)H(U),X=N.then((O)=>({bytes:O,view:E(O),offset:$}));return X}createWorker($,J){let K={startPos:$,currentPos:$,targetPos:J,running:!1,aborted:!1,pendingSlices:[],age:this.nextAge++};this.workers.push(K);while(this.workers.length>this.options.maxWorkerCount){let Y=0,Z=this.workers[0];for(let X=1;X<this.workers.length;X++){let Q=this.workers[X];if(Q.age<Z.age)Y=X,Z=Q}if(Z.running&&Z.pendingSlices.length>0)break;Z.aborted=!0,this.workers.splice(Y,1)}return K}runWorker($){H(!$.running),H($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((K)=>K.reject(J)),$.pendingSlices.length=0;else throw J})}supplyWorkerData($,J){if(this.disposed)return;let K=$.currentPos,Y=K+J.length;this.insertIntoCache({start:K,end:Y,bytes:J,view:E(J),age:this.nextAge++}),$.currentPos+=J.length,$.targetPos=Math.max($.targetPos,$.currentPos);for(let Z=0;Z<$.pendingSlices.length;Z++){let X=$.pendingSlices[Z],Q=Math.max(K,X.start),W=Math.min(Y,X.start+X.bytes.length);if(Q<W)X.bytes.set(J.subarray(Q-K,W-K),Q-X.start);for(let G=0;G<X.holes.length;G++){let U=X.holes[G];if(K<=U.start&&Y>U.start)U.start=Y;if(U.end<=U.start)X.holes.splice(G,1),G--}if(X.holes.length===0)X.resolve(X.bytes),$.pendingSlices.splice(Z,1),Z--}for(let Z=0;Z<this.workers.length;Z++){let X=this.workers[Z];if($===X||X.running)continue;if(y1(K,Y,X.currentPos,X.targetPos))this.workers.splice(Z,1),Z--}}forgetWorker($){let J=this.workers.indexOf($);H(J!==-1),this.workers.splice(J,1)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=S(this.cache,$.start,(K)=>K.start)+1;if(J>0){let K=this.cache[J-1];if(K.end>=$.end)return;if(K.end>$.start){let Y=new Uint8Array($.end-K.start);Y.set(K.bytes,0),Y.set($.bytes,$.start-K.start),this.currentCacheSize+=$.end-K.end,K.bytes=Y,K.view=E(Y),K.end=$.end,J--,$=K}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let K=J+1;K<this.cache.length;K++){let Y=this.cache[K];if($.end<=Y.start)break;if($.end>=Y.end){this.cache.splice(K,1),this.currentCacheSize-=Y.bytes.length,K--;continue}let Z=new Uint8Array(Y.end-$.start);Z.set($.bytes,0),Z.set(Y.bytes,Y.start-$.start),this.currentCacheSize-=$.end-Y.start,$.bytes=Z,$.view=E(Z),$.end=Y.end,this.cache.splice(K,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let K=0,Y=this.cache[0];for(let Z=1;Z<this.cache.length;Z++){let X=this.cache[Z];if(X.age<Y.age)K=Z,Y=X}if(this.currentCacheSize-Y.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(K,1),this.currentCacheSize-=Y.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}/*!
|
|
210
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
211
|
+
*
|
|
212
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
213
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
214
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
215
|
+
*/S1();class N8{get disposed(){return this._disposed}constructor($){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Array.isArray($.formats)||$.formats.some((J)=>!(J instanceof Z0)))throw TypeError("options.formats must be an array of InputFormat.");if(!($.source instanceof q0))throw TypeError("options.source must be a Source.");if($.source._disposed)throw Error("options.source must not be disposed.");this._formats=$.formats,this._source=$.source,this._reader=new H$($.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let $ of this._formats)if(await $._canReadInput(this))return this._format=$,$._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),H(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter((J)=>J.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter((J)=>J.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find((J)=>J.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find((J)=>J.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(this._disposed)return;this._disposed=!0,this._source._disposed=!0,this._source._dispose()}[Symbol.dispose](){this.dispose()}}class c extends Error{constructor($="Input has been disposed."){super($);this.name="InputDisposedError"}}/*!
|
|
216
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
217
|
+
*
|
|
218
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
219
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
220
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
221
|
+
*/class H${constructor($){this.source=$}requestSlice($,J){if(this.source._disposed)throw new c;if(this.fileSize!==null&&$+J>this.fileSize)return null;let K=$+J,Y=this.source._read($,K);if(Y instanceof Promise)return Y.then((Z)=>{if(!Z)return null;return new k0(Z.bytes,Z.view,Z.offset,$,K)});else{if(!Y)return null;return new k0(Y.bytes,Y.view,Y.offset,$,K)}}requestSliceRange($,J,K){if(this.source._disposed)throw new c;if(this.fileSize!==null)return this.requestSlice($,x0(this.fileSize-$,J,K));else{let Y=this.requestSlice($,K),Z=(X)=>{if(X)return X;let Q=(G)=>{return H(G!==null),this.requestSlice($,x0(G-$,J,K))},W=this.source._retrieveSize();if(W instanceof Promise)return W.then(Q);else return Q(W)};if(Y instanceof Promise)return Y.then(Z);else return Z(Y)}}}class k0{constructor($,J,K,Y,Z){this.bytes=$,this.view=J,this.offset=K,this.start=Y,this.end=Z,this.bufferPos=Y-K}static tempFromBytes($){return new k0($,E($),0,0,$.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos($){this.bufferPos=$-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip($){this.bufferPos+=$}slice($,J=this.end-$){if($<this.start||$+J>this.end)throw RangeError("Slicing outside of original slice.");return new k0(this.bytes,this.view,this.offset,$,$+J)}}var t=($,J)=>{if($.filePos<$.start||$.filePos+J>$.end)throw RangeError(`Tried reading [${$.filePos}, ${$.filePos+J}), but slice is [${$.start}, ${$.end}). This is likely an internal error, please report it alongside the file that caused it.`)},v=($,J)=>{t($,J);let K=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,K},T=($)=>{return t($,1),$.view.getUint8($.bufferPos++)},X1=($,J)=>{t($,2);let K=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,K},m=($)=>{t($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},T0=($)=>{t($,3);let J=h0($.view,$.bufferPos,!1);return $.bufferPos+=3,J},O1=($)=>{t($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},w0=($,J)=>{t($,4);let K=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,K},M=($)=>{t($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},u0=($)=>{t($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},F0=($)=>{t($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},_Y=($)=>{t($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},t8=($,J)=>{let K,Y;if(J)K=w0($,!0),Y=w0($,!0);else Y=w0($,!1),K=w0($,!1);return Y*4294967296+K},e=($)=>{let J=M($),K=M($);return J*4294967296+K},s$=($)=>{let J=F0($),K=M($);return J*4294967296+K},RJ=($)=>{let J=u0($);return _Y($)*4294967296+J},e$=($)=>{t($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},s1=($)=>{t($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},k=($,J)=>{t($,J);let K="";for(let Y=0;Y<J;Y++)K+=String.fromCharCode($.bytes[$.bufferPos++]);return K};/*!
|
|
222
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
223
|
+
*
|
|
224
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
225
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
226
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
227
|
+
*/class pJ{cache=new Map;maxSize;constructor($){this.maxSize=$}get($){let J=this.cache.get($);if(J!==void 0)this.cache.delete($),this.cache.set($,J);return J}set($,J){if(this.cache.has($))this.cache.delete($);else if(this.cache.size>=this.maxSize){let K=this.cache.keys().next().value;if(K!==void 0)this.cache.delete(K)}this.cache.set($,J)}clear(){this.cache.clear()}get size(){return this.cache.size}}class mJ{id;type="video";duration;width;height;data;disposed=!1;constructor($,J,K,Y,Z){this.id=$,this.data=J,this.duration=K,this.width=Y,this.height=Z}async getFrameAt($){if(this.disposed)return null;let J=this.data.frameIntervalMs,K=Math.floor($*1000/J)*J,Y=this.data.frameCache.get(K);if(Y)return Y.canvas;try{let Z=await this.data.canvasSink.getCanvas($);if(!Z)return null;return this.data.frameCache.set(K,Z),Z.canvas}catch{return null}}getAudioBufferSink(){return this.data.audioBufferSink}hasAudio(){return this.data.audioBufferSink!==null}clearCache(){this.data.frameCache.clear()}dispose(){if(this.disposed)return;this.disposed=!0,this.data.frameCache.clear(),this.data.input.dispose()}}class lJ{id;type="image";duration=1/0;width;height;data;disposed=!1;constructor($,J){this.id=$,this.data=J,this.width=J.image.width,this.height=J.image.height}async getFrameAt($){if(this.disposed)return null;return this.data.image}dispose(){if(this.disposed)return;if(this.disposed=!0,"close"in this.data.image)this.data.image.close()}}class dJ{id;type="audio";duration;width=0;height=0;data;disposed=!1;constructor($,J,K){this.id=$,this.data=J,this.duration=K}async getFrameAt($){return null}getAudioBufferSink(){return this.data.audioBufferSink}dispose(){if(this.disposed)return;this.disposed=!0,this.data.input.dispose()}}class A${sources=new Map;audioContext=null;nextId=0;constructor($){this.audioContext=$??null}generateId(){return`source_${this.nextId++}`}async loadVideo($,J={}){let K=J.id??this.generateId(),Y=this.createInput($),Z=await Y.getVideoTracks();if(Z.length===0)throw Y.dispose(),Error("Source has no video track");let X=Z[0];if(!await X.canDecode())throw Y.dispose(),Error(`Cannot decode video track with codec: ${X.codec}`);let W=new n1(X,{poolSize:4}),G=await X.computeDuration(),U=30;try{let z=await X.computePacketStats(100);if(z.averagePacketRate>0)U=z.averagePacketRate}catch{}let q=1000/U,j=X.displayWidth*X.displayHeight,V=j>2073600?15:j>921600?30:60,N=null,A=null;try{let z=await Y.getAudioTracks();if(z.length>0){if(N=z[0],await N.canDecode())A=new H1(N)}}catch{}let R=new mJ(K,{input:Y,videoTrack:X,canvasSink:W,frameCache:new pJ(V),frameIntervalMs:q,audioTrack:N,audioBufferSink:A},G,X.displayWidth,X.displayHeight);return this.sources.set(K,R),R}async loadImage($){let J=this.generateId(),K;if(typeof $!=="string")K=await createImageBitmap($);else if(typeof Image>"u"){let Z=await fetch($);if(!Z.ok)throw Error(`Failed to load image: ${$}`);let X=await Z.blob();K=await createImageBitmap(X)}else K=await new Promise((Z,X)=>{let Q=new Image;Q.onload=()=>Z(Q),Q.onerror=()=>X(Error(`Failed to load image: ${$}`)),Q.crossOrigin="anonymous",Q.src=$});let Y=new lJ(J,{image:K});return this.sources.set(J,Y),Y}async loadAudio($,J={}){let K=J.id??this.generateId(),Y=this.createInput($),Z=await Y.getAudioTracks();if(Z.length===0)throw Y.dispose(),Error("Source has no audio track");let X=Z[0];if(!await X.canDecode())throw Y.dispose(),Error(`Cannot decode audio track with codec: ${X.codec}`);let W=await X.computeDuration(),G=new H1(X),U=new dJ(K,{input:Y,audioTrack:X,audioBufferSink:G},W);return this.sources.set(K,U),U}createInput($){let J;if($ instanceof File||$ instanceof Blob)J=new G8($);else if($ instanceof ArrayBuffer||$ instanceof Uint8Array)J=new W8($);else if(typeof $==="string"||$ instanceof URL){let K=$ instanceof URL?$.href:$;if(typeof window>"u"&&!K.startsWith("http"))J=new U8(K);else J=new q8(K)}else if(typeof ReadableStream<"u"&&$ instanceof ReadableStream)J=new j8($);else throw Error("Unsupported source type");return new N8({source:J,formats:j$})}getSource($){return this.sources.get($)}hasSource($){return this.sources.has($)}unloadSource($){let J=this.sources.get($);if(J)return J.dispose(),this.sources.delete($),!0;return!1}getAllSources(){return Array.from(this.sources.values())}clear(){for(let $ of this.sources.values())$.dispose();this.sources.clear()}dispose(){if(this.clear(),this.audioContext&&this.audioContext.state!=="closed")this.audioContext.close();this.audioContext=null}}class O${worker;nextId=1;pending=new Map;ready;constructor($){let J=typeof $.worker==="boolean"?{}:$.worker??{},K=J.type??"module",Y=J.url??new URL("./compositor-worker.js",import.meta.url);this.worker=new Worker(Y,{type:K}),this.worker.onmessage=(Q)=>{let{id:W,ok:G,result:U,error:q}=Q.data,j=this.pending.get(W);if(!j)return;if(this.pending.delete(W),G)j.resolve(U);else j.reject(Error(q??"Worker error"))},this.worker.onerror=(Q)=>{let W=Q.error instanceof Error?Q.error:Error("Worker error");for(let G of this.pending.values())G.reject(W);this.pending.clear()};let Z=$.canvas.transferControlToOffscreen(),X={canvas:Z,width:$.width,height:$.height,backgroundColor:$.backgroundColor};this.ready=this.call("init",X,[Z])}postMessage($,J,K){let Y=this.nextId++;return this.worker.postMessage({id:Y,kind:$,payload:J},K??[]),Y}call($,J,K){let Y=this.postMessage($,J,K);return new Promise((Z,X)=>{this.pending.set(Y,{resolve:Z,reject:X})})}async loadSource($,J){await this.ready;let K={source:$,options:J};return this.call("loadSource",K)}async loadImage($){await this.ready;let J={source:$};return this.call("loadImage",J)}async loadAudio($,J){await this.ready;let K={source:$,options:J};return this.call("loadAudio",K)}async unloadSource($){await this.ready;let J={id:$};return this.call("unloadSource",J)}async render($){await this.ready;let J={frame:$};return this.call("render",J)}async clear(){return await this.ready,this.call("clear")}async resize($,J){await this.ready;let K={width:$,height:J};return this.call("resize",K)}async exportFrame($,J){await this.ready;let K={frame:$,options:J};return this.call("exportFrame",K)}dispose(){try{this.worker.postMessage({id:this.nextId++,kind:"dispose"})}catch{}this.worker.terminate(),this.pending.clear()}}class R${canvas;ctx=null;width;height;backgroundColor;sourcePool;audioManager=null;workerClient=null;workerSources=new Map;workerAudioSources=new Map;emitter;state;animationFrameId=null;lastFrameTime=0;lastRenderTime=0;previewOptions=null;disposed=!1;renderBuffers={visibleLayers:[],framePromises:[],frameImages:[]};lastTimeUpdateEmit=0;timeUpdateThrottleMs=100;renderPending=!1;activeAudioSourceIds=new Set;audioScratch={nextActiveSourceIds:new Set,newSourceIds:[],newSourceTimes:[]};registeredAudioSources=new Set;constructor($){this.canvas=$.canvas,this.width=$.width??(this.canvas.width||1920),this.height=$.height??(this.canvas.height||1080),this.backgroundColor=$.backgroundColor??"#000000",this.emitter=new H8({maxListeners:50}),this.state={playing:!1,currentTime:0,duration:0,seeking:!1},this.canvas.width=this.width,this.canvas.height=this.height;let J=typeof $.worker==="boolean"?$.worker:$.worker?$.worker.enabled??!0:!1,K=J&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof this.canvas.transferControlToOffscreen==="function"&&!(this.canvas instanceof OffscreenCanvas);if(J&&!K)throw Error("Worker compositor requires HTMLCanvasElement, OffscreenCanvas, and Worker support");if(this.sourcePool=new A$,K)try{this.workerClient=new O$({canvas:this.canvas,width:this.width,height:this.height,backgroundColor:this.backgroundColor,worker:$.worker??!0})}catch(Y){console.warn("[Compositor] Worker initialization failed, falling back to main thread rendering:",Y),this.workerClient=null}if($.enableAudio!==!1)this.audioManager=new A8;if(!this.workerClient){if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)throw Error("Failed to get 2D context for compositor canvas");this.clear()}}async loadSource($,J){if(this.checkDisposed(),this.workerClient){let Y=await this.workerClient.loadSource($,J),Z=this.createWorkerSource(Y);if(this.audioManager&&Y.hasAudio)await this.loadWorkerAudio($,Z.id);return this.emitter.emit("sourceloaded",{id:Z.id,source:Z}),Z}let K=await this.sourcePool.loadVideo($,J);return this.registerSourceAudio(K),this.emitter.emit("sourceloaded",{id:K.id,source:K}),K}async loadImage($){if(this.checkDisposed(),this.workerClient){let K=await this.workerClient.loadImage($),Y=this.createWorkerSource(K);return this.emitter.emit("sourceloaded",{id:Y.id,source:Y}),Y}let J=await this.sourcePool.loadImage($);return this.emitter.emit("sourceloaded",{id:J.id,source:J}),J}async loadAudio($,J){if(this.checkDisposed(),this.workerClient){let Y=await this.workerClient.loadAudio($,J),Z=this.createWorkerSource(Y);if(this.audioManager)await this.loadWorkerAudio($,Z.id);return this.emitter.emit("sourceloaded",{id:Z.id,source:Z}),Z}let K=await this.sourcePool.loadAudio($,J);return this.registerSourceAudio(K),this.emitter.emit("sourceloaded",{id:K.id,source:K}),K}unloadSource($){if(this.workerClient){if(!this.workerSources.get($))return!1;return this.workerClient.unloadSource($),this.workerSources.delete($),this.unloadWorkerAudio($),this.emitter.emit("sourceunloaded",{id:$}),!0}if(this.registeredAudioSources.has($))this.audioManager?.unregisterSource($),this.registeredAudioSources.delete($);let J=this.sourcePool.unloadSource($);if(J)this.emitter.emit("sourceunloaded",{id:$});return J}registerSourceAudio($){if(!this.audioManager)return;if(this.registeredAudioSources.has($.id))return;let J=$.getAudioBufferSink?.();if(J)this.audioManager.registerSource($,J),this.registeredAudioSources.add($.id)}processAudioLayers($,J){if(!this.audioManager)return;let K=this.audioScratch.newSourceIds,Y=this.audioScratch.newSourceTimes,Z=this.audioScratch.nextActiveSourceIds,X=this.activeAudioSourceIds;K.length=0,Y.length=0,Z.clear();for(let Q=0;Q<$.length;Q++){let W=$[Q];if(W.muted)continue;let G=W.source.id;if(!this.audioManager.hasSource(G))continue;if(Z.add(G),!X.has(G))K.push(G),Y.push(W.sourceTime??J)}if(X.size>0)X.clear();for(let Q of Z)X.add(Q);this.audioManager.processAudioLayers($,J);for(let Q=0;Q<K.length;Q++)this.audioManager.startSourcePlayback(K[Q],Y[Q])}getSource($){if(this.workerClient)return this.workerSources.get($);return this.sourcePool.getSource($)}getAllSources(){if(this.workerClient)return Array.from(this.workerSources.values());return this.sourcePool.getAllSources()}async render($){if(this.checkDisposed(),this.workerClient){let U=this.serializeWorkerFrame($);return this.workerClient.render(U)}let J=this.ctx;if(!J)return!1;let{visibleLayers:K,framePromises:Y,frameImages:Z}=this.renderBuffers;K.length=0,Y.length=0,Z.length=0;let X=!1,Q=-1/0,W=$.layers;for(let U=0;U<W.length;U++){let q=W[U];if(q.visible===!1)continue;let j=q.zIndex??0;if(j<Q)X=!0;Q=j,K.push(q)}if(K.length===0)return J.fillStyle=this.backgroundColor,J.fillRect(0,0,this.width,this.height),!0;if(X)K.sort((U,q)=>(U.zIndex??0)-(q.zIndex??0));for(let U=0;U<K.length;U++){let q=K[U],j=q.sourceTime??$.time;Y[U]=q.source.getFrameAt(j)}let G=await Promise.all(Y);for(let U=0;U<G.length;U++)Z[U]=G[U]??null;J.fillStyle=this.backgroundColor,J.fillRect(0,0,this.width,this.height);for(let U=0;U<K.length;U++){let q=Z[U];if(q)this.renderLayer(q,K[U])}return!0}renderLayer($,J){let K=this.ctx;if(!K)return;let Y=J.transform,Z=J.source.width??this.width,X=J.source.height??this.height;if(!Y){K.drawImage($,0,0,Z,X);return}let Q=Y.width??Z,W=Y.height??X,G=Y.x??0,U=Y.y??0,q=Y.rotation??0,j=Y.scaleX??1,V=Y.scaleY??1,N=Y.opacity??1,A=N!==1;if(!A&&!(q!==0||j!==1||V!==1)){K.drawImage($,G,U,Q,W);return}let z=Y.anchorX??0.5,O=Y.anchorY??0.5;if(K.save(),A)K.globalAlpha=N;if(K.translate(G+Q*z,U+W*O),q!==0)K.rotate(q*Math.PI/180);if(j!==1||V!==1)K.scale(j,V);K.drawImage($,-Q*z,-W*O,Q,W),K.restore()}createWorkerSource($){let J={id:$.id,type:$.type,duration:$.duration,width:$.width,height:$.height,async getFrameAt(){throw Error("getFrameAt is not available when worker rendering is enabled")},getAudioBufferSink(){return null},hasAudio(){return $.hasAudio??!1},dispose(){}};return this.workerSources.set(J.id,J),J}async loadWorkerAudio($,J){if(!this.audioManager)return;if(this.workerAudioSources.has(J))this.unloadWorkerAudio(J);try{let K=await this.sourcePool.loadAudio($,{id:J});this.workerAudioSources.set(J,K),this.registerSourceAudio(K)}catch{}}unloadWorkerAudio($){if(!this.audioManager)return;if(this.workerAudioSources.has($))this.audioManager.unregisterSource($),this.registeredAudioSources.delete($),this.sourcePool.unloadSource($),this.workerAudioSources.delete($)}serializeWorkerFrame($){if(!this.workerClient)throw Error("Worker compositor not initialized");let J=$.layers,K=Array(J.length);for(let Y=0;Y<J.length;Y++){let Z=J[Y],X=Z.source.id;if(!this.workerSources.has(X))throw Error(`Layer source ${X} is not managed by this compositor`);K[Y]={sourceId:X,sourceTime:Z.sourceTime,transform:Z.transform,visible:Z.visible,zIndex:Z.zIndex}}return{time:$.time,layers:K}}clear(){if(this.workerClient){this.workerClient.clear();return}if(!this.ctx)return;this.ctx.fillStyle=this.backgroundColor,this.ctx.fillRect(0,0,this.width,this.height)}preview($){this.checkDisposed(),this.previewOptions=$,this.state.duration=$.duration,this.lastRenderTime=0,this.emitter.emit("compositionchange",void 0)}async play(){if(this.checkDisposed(),this.state.playing)return;if(!this.previewOptions)throw Error("No preview configured. Call preview() first.");if(this.state.playing=!0,this.lastFrameTime=performance.now(),this.lastRenderTime=this.lastFrameTime,this.emitter.emit("play",void 0),this.audioManager)this.activeAudioSourceIds.clear(),await this.audioManager.play(this.state.currentTime);this.startRenderLoop()}pause(){if(this.checkDisposed(),!this.state.playing)return;if(this.state.playing=!1,this.stopRenderLoop(),this.audioManager)this.audioManager.pause();this.emitter.emit("pause",void 0)}async seek($){if(this.checkDisposed(),!this.previewOptions)return;let J=Math.max(0,Math.min($,this.state.duration));if(this.state.seeking=!0,this.emitter.emit("seeking",{time:J}),this.state.currentTime=J,this.audioManager)await this.audioManager.seek(J);let K=this.previewOptions.getComposition(J);await this.render(K),this.state.seeking=!1,this.emitter.emit("seeked",{time:J}),this.emitter.emit("timeupdate",{currentTime:J})}startRenderLoop(){if(this.animationFrameId!==null)return;let $=()=>{if(!this.state.playing||!this.previewOptions)return;this.animationFrameId=requestAnimationFrame($);let J=performance.now(),K=(J-this.lastFrameTime)/1000;if(this.lastFrameTime=J,this.state.currentTime+=K,this.state.currentTime>=this.state.duration)if(this.previewOptions.loop)this.state.currentTime=0;else{this.state.currentTime=this.state.duration,this.pause(),this.emitter.emit("ended",void 0);return}let Y=this.previewOptions.fps??0,Z=Y>0?1000/Y:0;if(!this.renderPending&&(Z===0||J-this.lastRenderTime>=Z)){this.renderPending=!0,this.lastRenderTime=J;let Q=this.previewOptions.getComposition(this.state.currentTime);if(this.audioManager)this.processAudioLayers(Q.audio??[],this.state.currentTime);this.render(Q).catch(()=>{}).finally(()=>{this.renderPending=!1})}if(J-this.lastTimeUpdateEmit>=this.timeUpdateThrottleMs)this.lastTimeUpdateEmit=J,this.emitter.emit("timeupdate",{currentTime:this.state.currentTime})};this.animationFrameId=requestAnimationFrame($)}stopRenderLoop(){if(this.animationFrameId!==null)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}async exportFrame($,J={}){if(this.checkDisposed(),!this.previewOptions)return null;let K=this.previewOptions.getComposition($);if(this.workerClient){let Y=this.serializeWorkerFrame(K);return this.workerClient.exportFrame(Y,J)}if(await this.render(K),"toBlob"in this.canvas)return new Promise((Y)=>{this.canvas.toBlob((Z)=>Y(Z),`image/${J.format??"png"}`,J.quality)});else return this.canvas.convertToBlob({type:`image/${J.format??"png"}`,quality:J.quality})}get currentTime(){return this.state.currentTime}get duration(){return this.state.duration}get playing(){return this.state.playing}get paused(){return!this.state.playing}get seeking(){return this.state.seeking}getWidth(){return this.width}getHeight(){return this.height}resize($,J){if(this.checkDisposed(),this.width=$,this.height=J,this.canvas.width=$,this.canvas.height=J,this.workerClient){this.workerClient.resize($,J);return}this.clear()}on($,J){return this.emitter.on($,J)}once($,J){return this.emitter.once($,J)}off($,J){this.emitter.off($,J)}setVolume($){this.audioManager?.setMasterVolume($)}setMuted($){this.audioManager?.setMasterMuted($)}getAudioContext(){if(!this.audioManager)throw Error("Audio is disabled for this compositor");return this.audioManager.getAudioContext()}checkDisposed(){if(this.disposed)throw Error("Compositor has been disposed")}dispose(){if(this.disposed)return;this.disposed=!0,this.stopRenderLoop(),this.audioManager?.dispose(),this.workerClient?.dispose(),this.workerClient=null,this.sourcePool.dispose(),this.registeredAudioSources.clear(),this.activeAudioSourceIds.clear(),this.audioScratch.nextActiveSourceIds.clear(),this.audioScratch.newSourceIds.length=0,this.audioScratch.newSourceTimes.length=0,this.workerSources.clear(),this.workerAudioSources.clear(),this.emitter.removeAllListeners(),this.ctx=null,this.previewOptions=null}}var oJ=self,g=null,C1=null,z$=($)=>({id:$.id,type:$.type,duration:$.duration,width:$.width,height:$.height,hasAudio:$.type==="audio"?!0:$.hasAudio?$.hasAudio():!1}),cJ=($)=>{if(!g)throw Error("Compositor not initialized");let J=Array($.layers.length);for(let K=0;K<$.layers.length;K++){let Y=$.layers[K],Z=g.getSource(Y.sourceId);if(!Z)throw Error(`Unknown source: ${Y.sourceId}`);J[K]={source:Z,sourceTime:Y.sourceTime,transform:Y.transform,visible:Y.visible,zIndex:Y.zIndex}}return{time:$.time,layers:J}},Q0=($,J)=>{oJ.postMessage($,J??[])};oJ.onmessage=async($)=>{let{id:J,kind:K,payload:Y}=$.data;try{switch(K){case"init":{let Z=Y;C1=Z.canvas,g=new R$({canvas:C1,width:Z.width,height:Z.height,backgroundColor:Z.backgroundColor,enableAudio:!1}),Q0({id:J,ok:!0});return}case"loadSource":{let{source:Z,options:X}=Y;if(!g)throw Error("Compositor not initialized");let Q=await g.loadSource(Z,X);Q0({id:J,ok:!0,result:z$(Q)});return}case"loadImage":{let{source:Z}=Y;if(!g)throw Error("Compositor not initialized");let X=await g.loadImage(Z);Q0({id:J,ok:!0,result:z$(X)});return}case"loadAudio":{let{source:Z,options:X}=Y;if(!g)throw Error("Compositor not initialized");let Q=await g.loadAudio(Z,X);Q0({id:J,ok:!0,result:z$(Q)});return}case"unloadSource":{if(!g)throw Error("Compositor not initialized");let{id:Z}=Y,X=g.unloadSource(Z);Q0({id:J,ok:!0,result:X});return}case"render":{if(!g)throw Error("Compositor not initialized");let{frame:Z}=Y,X=cJ(Z),Q=await g.render(X);Q0({id:J,ok:!0,result:Q});return}case"clear":{if(!g)throw Error("Compositor not initialized");g.clear(),Q0({id:J,ok:!0,result:!0});return}case"resize":{if(!g)throw Error("Compositor not initialized");let{width:Z,height:X}=Y;g.resize(Z,X),Q0({id:J,ok:!0,result:!0});return}case"exportFrame":{if(!g||!C1)throw Error("Compositor not initialized");let{frame:Z,options:X}=Y,Q=cJ(Z);await g.render(Q);let W=`image/${X?.format??"png"}`,G=await C1.convertToBlob({type:W,quality:X?.quality});Q0({id:J,ok:!0,result:G});return}case"dispose":{g?.dispose(),g=null,C1=null,Q0({id:J,ok:!0,result:!0});return}default:throw Error(`Unknown worker command: ${K}`)}}catch(Z){let X=Z instanceof Error?Z.message:"Worker error";Q0({id:J,ok:!1,error:X})}};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class y{events=new Map;maxListeners;captureRejections;emitCache=[];constructor(O={}){this.maxListeners=O.maxListeners??10,this.captureRejections=O.captureRejections??!1}on(O,$){if(!this.events.has(O))this.events.set(O,new Set);let A=this.events.get(O);if(!A)return()=>{};if(A.size>=this.maxListeners)console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${A.size} ${String(O)} listeners added. Use emitter.setMaxListeners() to increase limit`);let j=$;return A.add(j),()=>{A.delete(j)}}once(O,$){let A=(j)=>{this.off(O,A),$(j)};return this.on(O,A)}off(O,$){let A=this.events.get(O);if(!A)return;if($){let j=$;A.delete(j)}else A.clear()}emit(O,$){let A=this.events.get(O);if(!A||A.size===0)return;let j=this.emitCache;j.length=0;for(let Q of A)j.push(Q);for(let Q=0;Q<j.length;Q++){let V=j[Q];try{let J=V($);if(this.captureRejections&&NO(J))this.handlePromiseRejection(J)}catch(J){if(this.captureRejections&&this.events.has("error"))this.emit("error",J);else throw J}}}handlePromiseRejection(O){O.catch(($)=>{if(this.events.has("error"))this.emit("error",$);else throw $})}removeAllListeners(O){if(O)this.events.delete(O);else this.events.clear()}setMaxListeners(O){this.maxListeners=O}getMaxListeners(){return this.maxListeners}listeners(O){let $=this.events.get(O);return $?Array.from($):[]}listenerCount(O){let $=this.events.get(O);return $?$.size:0}eventNames(){return Array.from(this.events.keys())}}function NO(O){if(!O||typeof O!=="object"&&typeof O!=="function")return!1;let $=O;return typeof $.then==="function"&&typeof $.catch==="function"}class n{audioContext;masterGain;activeSources=new Map;activeSourceIdsScratch=new Set;playing=!1;disposed=!1;playbackId=0;startContextTime=0;startMediaTime=0;pauseTime=0;masterVolume=1;masterMuted=!1;constructor(O={}){if(O.audioContext)this.audioContext=O.audioContext;else{let $=globalThis,A=$.AudioContext||$.webkitAudioContext;if(!A)throw Error("AudioContext is not supported in this environment");this.audioContext=new A}this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination)}registerSource(O,$){if(this.disposed)return;let A=this.audioContext.createGain(),j=this.audioContext.createStereoPanner();A.connect(j),j.connect(this.masterGain),this.activeSources.set(O.id,{sourceId:O.id,bufferSink:$,iterator:null,gainNode:A,panNode:j,queuedNodes:new Set,volume:1,pan:0,muted:!1,startSourceTime:0,currentSourceTime:0,iteratorStartTime:0,lastScheduledTime:0})}unregisterSource(O){let $=this.activeSources.get(O);if(!$)return;this.stopSourceAudio($),$.gainNode.disconnect(),$.panNode.disconnect(),this.activeSources.delete(O)}hasSource(O){return this.activeSources.has(O)}processAudioLayers(O,$){if(this.disposed||!this.playing)return;let A=this.activeSourceIdsScratch;A.clear();for(let j of O){let Q=j.source.id;A.add(Q);let V=this.activeSources.get(Q);if(!V)continue;let J=j.volume??1,K=j.pan??0,Z=j.muted??!1,U=j.sourceTime??$;if(V.volume!==J||V.muted!==Z)V.volume=J,V.muted=Z,V.gainNode.gain.value=Z?0:J*J;if(V.pan!==K)V.pan=K,V.panNode.pan.value=Math.max(-1,Math.min(1,K));if(Math.abs(U-V.currentSourceTime)>0.5&&V.iterator!==null)this.restartSourceIterator(V,U);V.currentSourceTime=U}for(let[j,Q]of this.activeSources)if(!A.has(j)&&Q.iterator!==null)this.stopSourceAudio(Q)}async play(O=this.pauseTime){if(this.playing||this.disposed)return;if(this.audioContext.state==="suspended")await this.audioContext.resume();this.playbackId++,this.playing=!0,this.startContextTime=this.audioContext.currentTime,this.startMediaTime=O,this.pauseTime=O}startSourcePlayback(O,$){let A=this.activeSources.get(O);if(!A||A.iterator!==null)return;this.restartSourceIterator(A,$)}restartSourceIterator(O,$){this.stopSourceAudio(O),O.startSourceTime=$,O.currentSourceTime=$,O.iteratorStartTime=this.audioContext.currentTime,O.iterator=O.bufferSink.buffers($),O.lastScheduledTime=$,this.scheduleSourceBuffers(O,this.playbackId)}async scheduleSourceBuffers(O,$){let A=O.iterator;if(!A)return;try{for await(let{buffer:j,timestamp:Q}of A){if($!==this.playbackId||this.disposed||!this.playing)break;let V=this.audioContext.createBufferSource();V.buffer=j,V.connect(O.gainNode);let J=Q-O.startSourceTime,K=O.iteratorStartTime+J;if(K>=this.audioContext.currentTime)V.start(K);else{let G=this.audioContext.currentTime-K;if(G<j.duration)V.start(this.audioContext.currentTime,G);else continue}O.queuedNodes.add(V),V.onended=()=>{O.queuedNodes.delete(V)},O.lastScheduledTime=Q;let Z=this.audioContext.currentTime-O.iteratorStartTime;if(Q-O.startSourceTime-Z>1)await this.waitForCatchup(O,Q)}}catch{}}async waitForCatchup(O,$){return new Promise((A)=>{let j=setInterval(()=>{if(!this.playing||this.disposed){clearInterval(j),A();return}let Q=this.audioContext.currentTime-O.iteratorStartTime;if($-O.startSourceTime-Q<1)clearInterval(j),A()},100)})}pause(){if(!this.playing)return;this.pauseTime=this.getCurrentTime(),this.playing=!1;for(let O of this.activeSources.values())this.stopSourceAudio(O)}stop(){this.pause(),this.pauseTime=0,this.startContextTime=0,this.startMediaTime=0}async seek(O){let $=this.playing;if(this.pause(),this.pauseTime=O,this.startMediaTime=O,$)await this.play(O)}stopSourceAudio(O){for(let $ of O.queuedNodes)try{$.stop()}catch{}if(O.queuedNodes.clear(),O.iterator)O.iterator.return(),O.iterator=null}getCurrentTime(){if(this.playing)return this.startMediaTime+(this.audioContext.currentTime-this.startContextTime);return this.pauseTime}setMasterVolume(O){this.masterVolume=Math.max(0,Math.min(1,O)),this.updateMasterGain()}setMasterMuted(O){this.masterMuted=O,this.updateMasterGain()}updateMasterGain(){let O=this.masterMuted?0:this.masterVolume;this.masterGain.gain.value=O*O}getAudioContext(){return this.audioContext}isPlaying(){return this.playing}dispose(){if(this.disposed)return;this.disposed=!0,this.playbackId++,this.stop();for(let O of this.activeSources.values())this.stopSourceAudio(O),O.gainNode.disconnect(),O.panNode.disconnect();if(this.activeSources.clear(),this.masterGain.disconnect(),this.audioContext.state!=="closed")this.audioContext.close()}}import{ALL_FORMATS as DO,AudioBufferSink as JO,BlobSource as MO,BufferSource as _O,CanvasSink as EO,FilePathSource as qO,Input as CO,ReadableStreamSource as RO,UrlSource as WO}from"mediabunny";class KO{cache=new Map;maxSize;constructor(O){this.maxSize=O}get(O){let $=this.cache.get(O);if($!==void 0)this.cache.delete(O),this.cache.set(O,$);return $}set(O,$){if(this.cache.has(O))this.cache.delete(O);else if(this.cache.size>=this.maxSize){let A=this.cache.keys().next().value;if(A!==void 0)this.cache.delete(A)}this.cache.set(O,$)}clear(){this.cache.clear()}get size(){return this.cache.size}}class UO{id;type="video";duration;width;height;data;disposed=!1;constructor(O,$,A,j,Q){this.id=O,this.data=$,this.duration=A,this.width=j,this.height=Q}async getFrameAt(O){if(this.disposed)return null;let $=this.data.frameIntervalMs,A=Math.floor(O*1000/$)*$,j=this.data.frameCache.get(A);if(j)return j.canvas;try{let Q=await this.data.canvasSink.getCanvas(O);if(!Q)return null;return this.data.frameCache.set(A,Q),Q.canvas}catch{return null}}getAudioBufferSink(){return this.data.audioBufferSink}hasAudio(){return this.data.audioBufferSink!==null}clearCache(){this.data.frameCache.clear()}dispose(){if(this.disposed)return;this.disposed=!0,this.data.frameCache.clear(),this.data.input.dispose()}}class ZO{id;type="image";duration=1/0;width;height;data;disposed=!1;constructor(O,$){this.id=O,this.data=$,this.width=$.image.width,this.height=$.image.height}async getFrameAt(O){if(this.disposed)return null;return this.data.image}dispose(){if(this.disposed)return;if(this.disposed=!0,"close"in this.data.image)this.data.image.close()}}class GO{id;type="audio";duration;width=0;height=0;data;disposed=!1;constructor(O,$,A){this.id=O,this.data=$,this.duration=A}async getFrameAt(O){return null}getAudioBufferSink(){return this.data.audioBufferSink}dispose(){if(this.disposed)return;this.disposed=!0,this.data.input.dispose()}}class x{sources=new Map;audioContext=null;nextId=0;constructor(O){this.audioContext=O??null}generateId(){return`source_${this.nextId++}`}async loadVideo(O,$={}){let A=$.id??this.generateId(),j=this.createInput(O),Q=await j.getVideoTracks();if(Q.length===0)throw j.dispose(),Error("Source has no video track");let V=Q[0];if(!await V.canDecode())throw j.dispose(),Error(`Cannot decode video track with codec: ${V.codec}`);let K=new EO(V,{poolSize:4}),Z=await V.computeDuration(),U=30;try{let Y=await V.computePacketStats(100);if(Y.averagePacketRate>0)U=Y.averagePacketRate}catch{}let G=1000/U,L=V.displayWidth*V.displayHeight,P=L>2073600?15:L>921600?30:60,M=null,X=null;try{let Y=await j.getAudioTracks();if(Y.length>0){if(M=Y[0],await M.canDecode())X=new JO(M)}}catch{}let E=new UO(A,{input:j,videoTrack:V,canvasSink:K,frameCache:new KO(P),frameIntervalMs:G,audioTrack:M,audioBufferSink:X},Z,V.displayWidth,V.displayHeight);return this.sources.set(A,E),E}async loadImage(O){let $=this.generateId(),A;if(typeof O!=="string")A=await createImageBitmap(O);else if(typeof Image>"u"){let Q=await fetch(O);if(!Q.ok)throw Error(`Failed to load image: ${O}`);let V=await Q.blob();A=await createImageBitmap(V)}else A=await new Promise((Q,V)=>{let J=new Image;J.onload=()=>Q(J),J.onerror=()=>V(Error(`Failed to load image: ${O}`)),J.crossOrigin="anonymous",J.src=O});let j=new ZO($,{image:A});return this.sources.set($,j),j}async loadAudio(O,$={}){let A=$.id??this.generateId(),j=this.createInput(O),Q=await j.getAudioTracks();if(Q.length===0)throw j.dispose(),Error("Source has no audio track");let V=Q[0];if(!await V.canDecode())throw j.dispose(),Error(`Cannot decode audio track with codec: ${V.codec}`);let K=await V.computeDuration(),Z=new JO(V),U=new GO(A,{input:j,audioTrack:V,audioBufferSink:Z},K);return this.sources.set(A,U),U}createInput(O){let $;if(O instanceof File||O instanceof Blob)$=new MO(O);else if(O instanceof ArrayBuffer||O instanceof Uint8Array)$=new _O(O);else if(typeof O==="string"||O instanceof URL){let A=O instanceof URL?O.href:O;if(typeof window>"u"&&!A.startsWith("http"))$=new qO(A);else $=new WO(A)}else if(typeof ReadableStream<"u"&&O instanceof ReadableStream)$=new RO(O);else throw Error("Unsupported source type");return new CO({source:$,formats:DO})}getSource(O){return this.sources.get(O)}hasSource(O){return this.sources.has(O)}unloadSource(O){let $=this.sources.get(O);if($)return $.dispose(),this.sources.delete(O),!0;return!1}getAllSources(){return Array.from(this.sources.values())}clear(){for(let O of this.sources.values())O.dispose();this.sources.clear()}dispose(){if(this.clear(),this.audioContext&&this.audioContext.state!=="closed")this.audioContext.close();this.audioContext=null}}class s{worker;nextId=1;pending=new Map;ready;constructor(O){let $=typeof O.worker==="boolean"?{}:O.worker??{},A=$.type??"module",j=$.url??new URL("./compositor-worker.js",import.meta.url);this.worker=new Worker(j,{type:A}),this.worker.onmessage=(J)=>{let{id:K,ok:Z,result:U,error:G}=J.data,L=this.pending.get(K);if(!L)return;if(this.pending.delete(K),Z)L.resolve(U);else L.reject(Error(G??"Worker error"))},this.worker.onerror=(J)=>{let K=J.error instanceof Error?J.error:Error("Worker error");for(let Z of this.pending.values())Z.reject(K);this.pending.clear()};let Q=O.canvas.transferControlToOffscreen(),V={canvas:Q,width:O.width,height:O.height,backgroundColor:O.backgroundColor};this.ready=this.call("init",V,[Q])}postMessage(O,$,A){let j=this.nextId++;return this.worker.postMessage({id:j,kind:O,payload:$},A??[]),j}call(O,$,A){let j=this.postMessage(O,$,A);return new Promise((Q,V)=>{this.pending.set(j,{resolve:Q,reject:V})})}async loadSource(O,$){await this.ready;let A={source:O,options:$};return this.call("loadSource",A)}async loadImage(O){await this.ready;let $={source:O};return this.call("loadImage",$)}async loadAudio(O,$){await this.ready;let A={source:O,options:$};return this.call("loadAudio",A)}async unloadSource(O){await this.ready;let $={id:O};return this.call("unloadSource",$)}async render(O){await this.ready;let $={frame:O};return this.call("render",$)}async clear(){return await this.ready,this.call("clear")}async resize(O,$){await this.ready;let A={width:O,height:$};return this.call("resize",A)}async exportFrame(O,$){await this.ready;let A={frame:O,options:$};return this.call("exportFrame",A)}dispose(){try{this.worker.postMessage({id:this.nextId++,kind:"dispose"})}catch{}this.worker.terminate(),this.pending.clear()}}class i{canvas;ctx=null;width;height;backgroundColor;sourcePool;audioManager=null;workerClient=null;workerSources=new Map;workerAudioSources=new Map;emitter;state;animationFrameId=null;lastFrameTime=0;lastRenderTime=0;previewOptions=null;disposed=!1;renderBuffers={visibleLayers:[],framePromises:[],frameImages:[]};lastTimeUpdateEmit=0;timeUpdateThrottleMs=100;renderPending=!1;activeAudioSourceIds=new Set;audioScratch={nextActiveSourceIds:new Set,newSourceIds:[],newSourceTimes:[]};registeredAudioSources=new Set;constructor(O){this.canvas=O.canvas,this.width=O.width??(this.canvas.width||1920),this.height=O.height??(this.canvas.height||1080),this.backgroundColor=O.backgroundColor??"#000000",this.emitter=new y({maxListeners:50}),this.state={playing:!1,currentTime:0,duration:0,seeking:!1},this.canvas.width=this.width,this.canvas.height=this.height;let $=typeof O.worker==="boolean"?O.worker:O.worker?O.worker.enabled??!0:!1,A=$&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof this.canvas.transferControlToOffscreen==="function"&&!(this.canvas instanceof OffscreenCanvas);if($&&!A)throw Error("Worker compositor requires HTMLCanvasElement, OffscreenCanvas, and Worker support");if(this.sourcePool=new x,A)this.workerClient=new s({canvas:this.canvas,width:this.width,height:this.height,backgroundColor:this.backgroundColor,worker:O.worker??!0});if(O.enableAudio!==!1)this.audioManager=new n;if(!this.workerClient){if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)throw Error("Failed to get 2D context for compositor canvas");this.clear()}}async loadSource(O,$){if(this.checkDisposed(),this.workerClient){let j=await this.workerClient.loadSource(O,$),Q=this.createWorkerSource(j);if(this.audioManager&&j.hasAudio)await this.loadWorkerAudio(O,Q.id);return this.emitter.emit("sourceloaded",{id:Q.id,source:Q}),Q}let A=await this.sourcePool.loadVideo(O,$);return this.registerSourceAudio(A),this.emitter.emit("sourceloaded",{id:A.id,source:A}),A}async loadImage(O){if(this.checkDisposed(),this.workerClient){let A=await this.workerClient.loadImage(O),j=this.createWorkerSource(A);return this.emitter.emit("sourceloaded",{id:j.id,source:j}),j}let $=await this.sourcePool.loadImage(O);return this.emitter.emit("sourceloaded",{id:$.id,source:$}),$}async loadAudio(O,$){if(this.checkDisposed(),this.workerClient){let j=await this.workerClient.loadAudio(O,$),Q=this.createWorkerSource(j);if(this.audioManager)await this.loadWorkerAudio(O,Q.id);return this.emitter.emit("sourceloaded",{id:Q.id,source:Q}),Q}let A=await this.sourcePool.loadAudio(O,$);return this.registerSourceAudio(A),this.emitter.emit("sourceloaded",{id:A.id,source:A}),A}unloadSource(O){if(this.workerClient){if(!this.workerSources.get(O))return!1;return this.workerClient.unloadSource(O),this.workerSources.delete(O),this.unloadWorkerAudio(O),this.emitter.emit("sourceunloaded",{id:O}),!0}if(this.registeredAudioSources.has(O))this.audioManager?.unregisterSource(O),this.registeredAudioSources.delete(O);let $=this.sourcePool.unloadSource(O);if($)this.emitter.emit("sourceunloaded",{id:O});return $}registerSourceAudio(O){if(!this.audioManager)return;if(this.registeredAudioSources.has(O.id))return;let $=O.getAudioBufferSink?.();if($)this.audioManager.registerSource(O,$),this.registeredAudioSources.add(O.id)}processAudioLayers(O,$){if(!this.audioManager)return;let A=this.audioScratch.newSourceIds,j=this.audioScratch.newSourceTimes,Q=this.audioScratch.nextActiveSourceIds,V=this.activeAudioSourceIds;A.length=0,j.length=0,Q.clear();for(let J=0;J<O.length;J++){let K=O[J];if(K.muted)continue;let Z=K.source.id;if(!this.audioManager.hasSource(Z))continue;if(Q.add(Z),!V.has(Z))A.push(Z),j.push(K.sourceTime??$)}if(V.size>0)V.clear();for(let J of Q)V.add(J);this.audioManager.processAudioLayers(O,$);for(let J=0;J<A.length;J++)this.audioManager.startSourcePlayback(A[J],j[J])}getSource(O){if(this.workerClient)return this.workerSources.get(O);return this.sourcePool.getSource(O)}getAllSources(){if(this.workerClient)return Array.from(this.workerSources.values());return this.sourcePool.getAllSources()}async render(O){if(this.checkDisposed(),this.workerClient){let U=this.serializeWorkerFrame(O);return this.workerClient.render(U)}let $=this.ctx;if(!$)return!1;let{visibleLayers:A,framePromises:j,frameImages:Q}=this.renderBuffers;A.length=0,j.length=0,Q.length=0;let V=!1,J=-1/0,K=O.layers;for(let U=0;U<K.length;U++){let G=K[U];if(G.visible===!1)continue;let L=G.zIndex??0;if(L<J)V=!0;J=L,A.push(G)}if(A.length===0)return $.fillStyle=this.backgroundColor,$.fillRect(0,0,this.width,this.height),!0;if(V)A.sort((U,G)=>(U.zIndex??0)-(G.zIndex??0));for(let U=0;U<A.length;U++){let G=A[U],L=G.sourceTime??O.time;j[U]=G.source.getFrameAt(L)}let Z=await Promise.all(j);for(let U=0;U<Z.length;U++)Q[U]=Z[U]??null;$.fillStyle=this.backgroundColor,$.fillRect(0,0,this.width,this.height);for(let U=0;U<A.length;U++){let G=Q[U];if(G)this.renderLayer(G,A[U])}return!0}renderLayer(O,$){let A=this.ctx;if(!A)return;let j=$.transform,Q=$.source.width??this.width,V=$.source.height??this.height;if(!j){A.drawImage(O,0,0,Q,V);return}let J=j.width??Q,K=j.height??V,Z=j.x??0,U=j.y??0,G=j.rotation??0,L=j.scaleX??1,P=j.scaleY??1,M=j.opacity??1,X=M!==1;if(!X&&!(G!==0||L!==1||P!==1)){A.drawImage(O,Z,U,J,K);return}let Y=j.anchorX??0.5,q=j.anchorY??0.5;if(A.save(),X)A.globalAlpha=M;if(A.translate(Z+J*Y,U+K*q),G!==0)A.rotate(G*Math.PI/180);if(L!==1||P!==1)A.scale(L,P);A.drawImage(O,-J*Y,-K*q,J,K),A.restore()}createWorkerSource(O){let $={id:O.id,type:O.type,duration:O.duration,width:O.width,height:O.height,async getFrameAt(){throw Error("getFrameAt is not available when worker rendering is enabled")},getAudioBufferSink(){return null},hasAudio(){return O.hasAudio??!1},dispose(){}};return this.workerSources.set($.id,$),$}async loadWorkerAudio(O,$){if(!this.audioManager)return;if(this.workerAudioSources.has($))this.unloadWorkerAudio($);try{let A=await this.sourcePool.loadAudio(O,{id:$});this.workerAudioSources.set($,A),this.registerSourceAudio(A)}catch{}}unloadWorkerAudio(O){if(!this.audioManager)return;if(this.workerAudioSources.has(O))this.audioManager.unregisterSource(O),this.registeredAudioSources.delete(O),this.sourcePool.unloadSource(O),this.workerAudioSources.delete(O)}serializeWorkerFrame(O){if(!this.workerClient)throw Error("Worker compositor not initialized");let $=O.layers,A=Array($.length);for(let j=0;j<$.length;j++){let Q=$[j],V=Q.source.id;if(!this.workerSources.has(V))throw Error(`Layer source ${V} is not managed by this compositor`);A[j]={sourceId:V,sourceTime:Q.sourceTime,transform:Q.transform,visible:Q.visible,zIndex:Q.zIndex}}return{time:O.time,layers:A}}clear(){if(this.workerClient){this.workerClient.clear();return}if(!this.ctx)return;this.ctx.fillStyle=this.backgroundColor,this.ctx.fillRect(0,0,this.width,this.height)}preview(O){this.checkDisposed(),this.previewOptions=O,this.state.duration=O.duration,this.lastRenderTime=0,this.emitter.emit("compositionchange",void 0)}async play(){if(this.checkDisposed(),this.state.playing)return;if(!this.previewOptions)throw Error("No preview configured. Call preview() first.");if(this.state.playing=!0,this.lastFrameTime=performance.now(),this.lastRenderTime=this.lastFrameTime,this.emitter.emit("play",void 0),this.audioManager)await this.audioManager.play(this.state.currentTime);this.startRenderLoop()}pause(){if(this.checkDisposed(),!this.state.playing)return;if(this.state.playing=!1,this.stopRenderLoop(),this.audioManager)this.audioManager.pause();this.emitter.emit("pause",void 0)}async seek(O){if(this.checkDisposed(),!this.previewOptions)return;let $=Math.max(0,Math.min(O,this.state.duration));if(this.state.seeking=!0,this.emitter.emit("seeking",{time:$}),this.state.currentTime=$,this.audioManager)await this.audioManager.seek($);let A=this.previewOptions.getComposition($);await this.render(A),this.state.seeking=!1,this.emitter.emit("seeked",{time:$}),this.emitter.emit("timeupdate",{currentTime:$})}startRenderLoop(){if(this.animationFrameId!==null)return;let O=()=>{if(!this.state.playing||!this.previewOptions)return;this.animationFrameId=requestAnimationFrame(O);let $=performance.now(),A=($-this.lastFrameTime)/1000;if(this.lastFrameTime=$,this.state.currentTime+=A,this.state.currentTime>=this.state.duration)if(this.previewOptions.loop)this.state.currentTime=0;else{this.state.currentTime=this.state.duration,this.pause(),this.emitter.emit("ended",void 0);return}let j=this.previewOptions.fps??0,Q=j>0?1000/j:0;if(!this.renderPending&&(Q===0||$-this.lastRenderTime>=Q)){this.renderPending=!0,this.lastRenderTime=$;let J=this.previewOptions.getComposition(this.state.currentTime);if(this.audioManager)this.processAudioLayers(J.audio??[],this.state.currentTime);this.render(J).catch(()=>{}).finally(()=>{this.renderPending=!1})}if($-this.lastTimeUpdateEmit>=this.timeUpdateThrottleMs)this.lastTimeUpdateEmit=$,this.emitter.emit("timeupdate",{currentTime:this.state.currentTime})};this.animationFrameId=requestAnimationFrame(O)}stopRenderLoop(){if(this.animationFrameId!==null)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}async exportFrame(O,$={}){if(this.checkDisposed(),!this.previewOptions)return null;let A=this.previewOptions.getComposition(O);if(this.workerClient){let j=this.serializeWorkerFrame(A);return this.workerClient.exportFrame(j,$)}if(await this.render(A),"toBlob"in this.canvas)return new Promise((j)=>{this.canvas.toBlob((Q)=>j(Q),`image/${$.format??"png"}`,$.quality)});else return this.canvas.convertToBlob({type:`image/${$.format??"png"}`,quality:$.quality})}get currentTime(){return this.state.currentTime}get duration(){return this.state.duration}get playing(){return this.state.playing}get paused(){return!this.state.playing}get seeking(){return this.state.seeking}getWidth(){return this.width}getHeight(){return this.height}resize(O,$){if(this.checkDisposed(),this.width=O,this.height=$,this.canvas.width=O,this.canvas.height=$,this.workerClient){this.workerClient.resize(O,$);return}this.clear()}on(O,$){return this.emitter.on(O,$)}once(O,$){return this.emitter.once(O,$)}off(O,$){this.emitter.off(O,$)}setVolume(O){this.audioManager?.setMasterVolume(O)}setMuted(O){this.audioManager?.setMasterMuted(O)}getAudioContext(){if(!this.audioManager)throw Error("Audio is disabled for this compositor");return this.audioManager.getAudioContext()}checkDisposed(){if(this.disposed)throw Error("Compositor has been disposed")}dispose(){if(this.disposed)return;this.disposed=!0,this.stopRenderLoop(),this.audioManager?.dispose(),this.workerClient?.dispose(),this.workerClient=null,this.sourcePool.dispose(),this.registeredAudioSources.clear(),this.activeAudioSourceIds.clear(),this.audioScratch.nextActiveSourceIds.clear(),this.audioScratch.newSourceIds.length=0,this.audioScratch.newSourceTimes.length=0,this.workerSources.clear(),this.workerAudioSources.clear(),this.emitter.removeAllListeners(),this.ctx=null,this.previewOptions=null}}import{CanvasSink as FO,VideoSampleSink as SO}from"mediabunny";class S{canvas;ctx=null;isInitialized=!1;rotation=0;constructor(O){this.canvas=O.canvas,this.rotation=O.rotation??0,this.initialize()}initialize(){try{if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)return!1;return this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.isInitialized=!0,!0}catch{return!1}}isReady(){return this.isInitialized&&this.ctx!==null}render(O){if(!this.isReady()||!this.ctx)return!1;try{let{width:$,height:A}=O;if($===0||A===0)return!1;let j=this.canvas.width,Q=this.canvas.height;if(j===0||Q===0)return!1;let V=this.rotation===90||this.rotation===270,J=V?A:$,K=V?$:A,Z=Math.min(j/J,Q/K),U=Math.round(J*Z),G=Math.round(K*Z),L=Math.round((j-U)/2),P=Math.round((Q-G)/2);if(this.ctx.fillStyle="black",this.ctx.fillRect(0,0,j,Q),this.ctx.save(),this.ctx.translate(L+U/2,P+G/2),this.rotation!==0)this.ctx.rotate(this.rotation*Math.PI/180);if(V)this.ctx.drawImage(O,0,0,$,A,-G/2,-U/2,G,U);else this.ctx.drawImage(O,0,0,$,A,-U/2,-G/2,U,G);return this.ctx.restore(),!0}catch{return!1}}clear(){if(!this.isReady()||!this.ctx)return;this.ctx.fillStyle="black",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)}setRotation(O){this.rotation=O}getRotation(){return this.rotation}dispose(){this.ctx=null,this.isInitialized=!1}}class t{resources;isInitialized=!1;canvas;textureWidth=0;textureHeight=0;options;boundHandleContextLost=null;boundHandleContextRestored=null;rotation=0;positionsArray=new Float32Array(8);vertexShaderSource=`
|
|
1
|
+
class y{events=new Map;maxListeners;captureRejections;emitCache=[];constructor(O={}){this.maxListeners=O.maxListeners??10,this.captureRejections=O.captureRejections??!1}on(O,$){if(!this.events.has(O))this.events.set(O,new Set);let A=this.events.get(O);if(!A)return()=>{};if(A.size>=this.maxListeners)console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${A.size} ${String(O)} listeners added. Use emitter.setMaxListeners() to increase limit`);let j=$;return A.add(j),()=>{A.delete(j)}}once(O,$){let A=(j)=>{this.off(O,A),$(j)};return this.on(O,A)}off(O,$){let A=this.events.get(O);if(!A)return;if($){let j=$;A.delete(j)}else A.clear()}emit(O,$){let A=this.events.get(O);if(!A||A.size===0)return;let j=this.emitCache;j.length=0;for(let Q of A)j.push(Q);for(let Q=0;Q<j.length;Q++){let V=j[Q];try{let J=V($);if(this.captureRejections&&NO(J))this.handlePromiseRejection(J)}catch(J){if(this.captureRejections&&this.events.has("error"))this.emit("error",J);else throw J}}}handlePromiseRejection(O){O.catch(($)=>{if(this.events.has("error"))this.emit("error",$);else throw $})}removeAllListeners(O){if(O)this.events.delete(O);else this.events.clear()}setMaxListeners(O){this.maxListeners=O}getMaxListeners(){return this.maxListeners}listeners(O){let $=this.events.get(O);return $?Array.from($):[]}listenerCount(O){let $=this.events.get(O);return $?$.size:0}eventNames(){return Array.from(this.events.keys())}}function NO(O){if(!O||typeof O!=="object"&&typeof O!=="function")return!1;let $=O;return typeof $.then==="function"&&typeof $.catch==="function"}class n{audioContext;masterGain;activeSources=new Map;activeSourceIdsScratch=new Set;playing=!1;disposed=!1;playbackId=0;startContextTime=0;startMediaTime=0;pauseTime=0;masterVolume=1;masterMuted=!1;constructor(O={}){if(O.audioContext)this.audioContext=O.audioContext;else{let $=globalThis,A=$.AudioContext||$.webkitAudioContext;if(!A)throw Error("AudioContext is not supported in this environment");this.audioContext=new A}this.masterGain=this.audioContext.createGain(),this.masterGain.connect(this.audioContext.destination)}registerSource(O,$){if(this.disposed)return;let A=this.audioContext.createGain(),j=this.audioContext.createStereoPanner();A.connect(j),j.connect(this.masterGain),this.activeSources.set(O.id,{sourceId:O.id,bufferSink:$,iterator:null,gainNode:A,panNode:j,queuedNodes:new Set,volume:1,pan:0,muted:!1,startSourceTime:0,currentSourceTime:0,iteratorStartTime:0,lastScheduledTime:0})}unregisterSource(O){let $=this.activeSources.get(O);if(!$)return;this.stopSourceAudio($),$.gainNode.disconnect(),$.panNode.disconnect(),this.activeSources.delete(O)}hasSource(O){return this.activeSources.has(O)}processAudioLayers(O,$){if(this.disposed||!this.playing)return;let A=this.activeSourceIdsScratch;A.clear();for(let j of O){let Q=j.source.id;A.add(Q);let V=this.activeSources.get(Q);if(!V)continue;let J=j.volume??1,K=j.pan??0,Z=j.muted??!1,U=j.sourceTime??$;if(V.volume!==J||V.muted!==Z)V.volume=J,V.muted=Z,V.gainNode.gain.value=Z?0:J*J;if(V.pan!==K)V.pan=K,V.panNode.pan.value=Math.max(-1,Math.min(1,K));if(Math.abs(U-V.currentSourceTime)>0.5&&V.iterator!==null)this.restartSourceIterator(V,U);V.currentSourceTime=U}for(let[j,Q]of this.activeSources)if(!A.has(j)&&Q.iterator!==null)this.stopSourceAudio(Q)}async play(O=this.pauseTime){if(this.playing||this.disposed)return;if(this.audioContext.state==="suspended")await this.audioContext.resume();this.playbackId++,this.playing=!0,this.startContextTime=this.audioContext.currentTime,this.startMediaTime=O,this.pauseTime=O}startSourcePlayback(O,$){let A=this.activeSources.get(O);if(!A||A.iterator!==null)return;this.restartSourceIterator(A,$)}restartSourceIterator(O,$){this.stopSourceAudio(O),O.startSourceTime=$,O.currentSourceTime=$,O.iteratorStartTime=this.audioContext.currentTime,O.iterator=O.bufferSink.buffers($),O.lastScheduledTime=$,this.scheduleSourceBuffers(O,this.playbackId)}async scheduleSourceBuffers(O,$){let A=O.iterator;if(!A)return;try{for await(let{buffer:j,timestamp:Q}of A){if($!==this.playbackId||this.disposed||!this.playing)break;let V=this.audioContext.createBufferSource();V.buffer=j,V.connect(O.gainNode);let J=Q-O.startSourceTime,K=O.iteratorStartTime+J;if(K>=this.audioContext.currentTime)V.start(K);else{let G=this.audioContext.currentTime-K;if(G<j.duration)V.start(this.audioContext.currentTime,G);else continue}O.queuedNodes.add(V),V.onended=()=>{O.queuedNodes.delete(V)},O.lastScheduledTime=Q;let Z=this.audioContext.currentTime-O.iteratorStartTime;if(Q-O.startSourceTime-Z>1)await this.waitForCatchup(O,Q)}}catch{}}async waitForCatchup(O,$){return new Promise((A)=>{let j=setInterval(()=>{if(!this.playing||this.disposed){clearInterval(j),A();return}let Q=this.audioContext.currentTime-O.iteratorStartTime;if($-O.startSourceTime-Q<1)clearInterval(j),A()},100)})}pause(){if(!this.playing)return;this.pauseTime=this.getCurrentTime(),this.playing=!1;for(let O of this.activeSources.values())this.stopSourceAudio(O)}stop(){this.pause(),this.pauseTime=0,this.startContextTime=0,this.startMediaTime=0}async seek(O){let $=this.playing;if(this.pause(),this.pauseTime=O,this.startMediaTime=O,$)await this.play(O)}stopSourceAudio(O){for(let $ of O.queuedNodes)try{$.stop()}catch{}if(O.queuedNodes.clear(),O.iterator)O.iterator.return(),O.iterator=null}getCurrentTime(){if(this.playing)return this.startMediaTime+(this.audioContext.currentTime-this.startContextTime);return this.pauseTime}setMasterVolume(O){this.masterVolume=Math.max(0,Math.min(1,O)),this.updateMasterGain()}setMasterMuted(O){this.masterMuted=O,this.updateMasterGain()}updateMasterGain(){let O=this.masterMuted?0:this.masterVolume;this.masterGain.gain.value=O*O}getAudioContext(){return this.audioContext}isPlaying(){return this.playing}dispose(){if(this.disposed)return;this.disposed=!0,this.playbackId++,this.stop();for(let O of this.activeSources.values())this.stopSourceAudio(O),O.gainNode.disconnect(),O.panNode.disconnect();if(this.activeSources.clear(),this.masterGain.disconnect(),this.audioContext.state!=="closed")this.audioContext.close()}}import{ALL_FORMATS as DO,AudioBufferSink as JO,BlobSource as MO,BufferSource as _O,CanvasSink as EO,FilePathSource as qO,Input as CO,ReadableStreamSource as RO,UrlSource as WO}from"mediabunny";class KO{cache=new Map;maxSize;constructor(O){this.maxSize=O}get(O){let $=this.cache.get(O);if($!==void 0)this.cache.delete(O),this.cache.set(O,$);return $}set(O,$){if(this.cache.has(O))this.cache.delete(O);else if(this.cache.size>=this.maxSize){let A=this.cache.keys().next().value;if(A!==void 0)this.cache.delete(A)}this.cache.set(O,$)}clear(){this.cache.clear()}get size(){return this.cache.size}}class UO{id;type="video";duration;width;height;data;disposed=!1;constructor(O,$,A,j,Q){this.id=O,this.data=$,this.duration=A,this.width=j,this.height=Q}async getFrameAt(O){if(this.disposed)return null;let $=this.data.frameIntervalMs,A=Math.floor(O*1000/$)*$,j=this.data.frameCache.get(A);if(j)return j.canvas;try{let Q=await this.data.canvasSink.getCanvas(O);if(!Q)return null;return this.data.frameCache.set(A,Q),Q.canvas}catch{return null}}getAudioBufferSink(){return this.data.audioBufferSink}hasAudio(){return this.data.audioBufferSink!==null}clearCache(){this.data.frameCache.clear()}dispose(){if(this.disposed)return;this.disposed=!0,this.data.frameCache.clear(),this.data.input.dispose()}}class ZO{id;type="image";duration=1/0;width;height;data;disposed=!1;constructor(O,$){this.id=O,this.data=$,this.width=$.image.width,this.height=$.image.height}async getFrameAt(O){if(this.disposed)return null;return this.data.image}dispose(){if(this.disposed)return;if(this.disposed=!0,"close"in this.data.image)this.data.image.close()}}class GO{id;type="audio";duration;width=0;height=0;data;disposed=!1;constructor(O,$,A){this.id=O,this.data=$,this.duration=A}async getFrameAt(O){return null}getAudioBufferSink(){return this.data.audioBufferSink}dispose(){if(this.disposed)return;this.disposed=!0,this.data.input.dispose()}}class x{sources=new Map;audioContext=null;nextId=0;constructor(O){this.audioContext=O??null}generateId(){return`source_${this.nextId++}`}async loadVideo(O,$={}){let A=$.id??this.generateId(),j=this.createInput(O),Q=await j.getVideoTracks();if(Q.length===0)throw j.dispose(),Error("Source has no video track");let V=Q[0];if(!await V.canDecode())throw j.dispose(),Error(`Cannot decode video track with codec: ${V.codec}`);let K=new EO(V,{poolSize:4}),Z=await V.computeDuration(),U=30;try{let Y=await V.computePacketStats(100);if(Y.averagePacketRate>0)U=Y.averagePacketRate}catch{}let G=1000/U,L=V.displayWidth*V.displayHeight,P=L>2073600?15:L>921600?30:60,M=null,X=null;try{let Y=await j.getAudioTracks();if(Y.length>0){if(M=Y[0],await M.canDecode())X=new JO(M)}}catch{}let E=new UO(A,{input:j,videoTrack:V,canvasSink:K,frameCache:new KO(P),frameIntervalMs:G,audioTrack:M,audioBufferSink:X},Z,V.displayWidth,V.displayHeight);return this.sources.set(A,E),E}async loadImage(O){let $=this.generateId(),A;if(typeof O!=="string")A=await createImageBitmap(O);else if(typeof Image>"u"){let Q=await fetch(O);if(!Q.ok)throw Error(`Failed to load image: ${O}`);let V=await Q.blob();A=await createImageBitmap(V)}else A=await new Promise((Q,V)=>{let J=new Image;J.onload=()=>Q(J),J.onerror=()=>V(Error(`Failed to load image: ${O}`)),J.crossOrigin="anonymous",J.src=O});let j=new ZO($,{image:A});return this.sources.set($,j),j}async loadAudio(O,$={}){let A=$.id??this.generateId(),j=this.createInput(O),Q=await j.getAudioTracks();if(Q.length===0)throw j.dispose(),Error("Source has no audio track");let V=Q[0];if(!await V.canDecode())throw j.dispose(),Error(`Cannot decode audio track with codec: ${V.codec}`);let K=await V.computeDuration(),Z=new JO(V),U=new GO(A,{input:j,audioTrack:V,audioBufferSink:Z},K);return this.sources.set(A,U),U}createInput(O){let $;if(O instanceof File||O instanceof Blob)$=new MO(O);else if(O instanceof ArrayBuffer||O instanceof Uint8Array)$=new _O(O);else if(typeof O==="string"||O instanceof URL){let A=O instanceof URL?O.href:O;if(typeof window>"u"&&!A.startsWith("http"))$=new qO(A);else $=new WO(A)}else if(typeof ReadableStream<"u"&&O instanceof ReadableStream)$=new RO(O);else throw Error("Unsupported source type");return new CO({source:$,formats:DO})}getSource(O){return this.sources.get(O)}hasSource(O){return this.sources.has(O)}unloadSource(O){let $=this.sources.get(O);if($)return $.dispose(),this.sources.delete(O),!0;return!1}getAllSources(){return Array.from(this.sources.values())}clear(){for(let O of this.sources.values())O.dispose();this.sources.clear()}dispose(){if(this.clear(),this.audioContext&&this.audioContext.state!=="closed")this.audioContext.close();this.audioContext=null}}class s{worker;nextId=1;pending=new Map;ready;constructor(O){let $=typeof O.worker==="boolean"?{}:O.worker??{},A=$.type??"module",j=$.url??new URL("./compositor-worker.js",import.meta.url);this.worker=new Worker(j,{type:A}),this.worker.onmessage=(J)=>{let{id:K,ok:Z,result:U,error:G}=J.data,L=this.pending.get(K);if(!L)return;if(this.pending.delete(K),Z)L.resolve(U);else L.reject(Error(G??"Worker error"))},this.worker.onerror=(J)=>{let K=J.error instanceof Error?J.error:Error("Worker error");for(let Z of this.pending.values())Z.reject(K);this.pending.clear()};let Q=O.canvas.transferControlToOffscreen(),V={canvas:Q,width:O.width,height:O.height,backgroundColor:O.backgroundColor};this.ready=this.call("init",V,[Q])}postMessage(O,$,A){let j=this.nextId++;return this.worker.postMessage({id:j,kind:O,payload:$},A??[]),j}call(O,$,A){let j=this.postMessage(O,$,A);return new Promise((Q,V)=>{this.pending.set(j,{resolve:Q,reject:V})})}async loadSource(O,$){await this.ready;let A={source:O,options:$};return this.call("loadSource",A)}async loadImage(O){await this.ready;let $={source:O};return this.call("loadImage",$)}async loadAudio(O,$){await this.ready;let A={source:O,options:$};return this.call("loadAudio",A)}async unloadSource(O){await this.ready;let $={id:O};return this.call("unloadSource",$)}async render(O){await this.ready;let $={frame:O};return this.call("render",$)}async clear(){return await this.ready,this.call("clear")}async resize(O,$){await this.ready;let A={width:O,height:$};return this.call("resize",A)}async exportFrame(O,$){await this.ready;let A={frame:O,options:$};return this.call("exportFrame",A)}dispose(){try{this.worker.postMessage({id:this.nextId++,kind:"dispose"})}catch{}this.worker.terminate(),this.pending.clear()}}class i{canvas;ctx=null;width;height;backgroundColor;sourcePool;audioManager=null;workerClient=null;workerSources=new Map;workerAudioSources=new Map;emitter;state;animationFrameId=null;lastFrameTime=0;lastRenderTime=0;previewOptions=null;disposed=!1;renderBuffers={visibleLayers:[],framePromises:[],frameImages:[]};lastTimeUpdateEmit=0;timeUpdateThrottleMs=100;renderPending=!1;activeAudioSourceIds=new Set;audioScratch={nextActiveSourceIds:new Set,newSourceIds:[],newSourceTimes:[]};registeredAudioSources=new Set;constructor(O){this.canvas=O.canvas,this.width=O.width??(this.canvas.width||1920),this.height=O.height??(this.canvas.height||1080),this.backgroundColor=O.backgroundColor??"#000000",this.emitter=new y({maxListeners:50}),this.state={playing:!1,currentTime:0,duration:0,seeking:!1},this.canvas.width=this.width,this.canvas.height=this.height;let $=typeof O.worker==="boolean"?O.worker:O.worker?O.worker.enabled??!0:!1,A=$&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof this.canvas.transferControlToOffscreen==="function"&&!(this.canvas instanceof OffscreenCanvas);if($&&!A)throw Error("Worker compositor requires HTMLCanvasElement, OffscreenCanvas, and Worker support");if(this.sourcePool=new x,A)try{this.workerClient=new s({canvas:this.canvas,width:this.width,height:this.height,backgroundColor:this.backgroundColor,worker:O.worker??!0})}catch(j){console.warn("[Compositor] Worker initialization failed, falling back to main thread rendering:",j),this.workerClient=null}if(O.enableAudio!==!1)this.audioManager=new n;if(!this.workerClient){if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)throw Error("Failed to get 2D context for compositor canvas");this.clear()}}async loadSource(O,$){if(this.checkDisposed(),this.workerClient){let j=await this.workerClient.loadSource(O,$),Q=this.createWorkerSource(j);if(this.audioManager&&j.hasAudio)await this.loadWorkerAudio(O,Q.id);return this.emitter.emit("sourceloaded",{id:Q.id,source:Q}),Q}let A=await this.sourcePool.loadVideo(O,$);return this.registerSourceAudio(A),this.emitter.emit("sourceloaded",{id:A.id,source:A}),A}async loadImage(O){if(this.checkDisposed(),this.workerClient){let A=await this.workerClient.loadImage(O),j=this.createWorkerSource(A);return this.emitter.emit("sourceloaded",{id:j.id,source:j}),j}let $=await this.sourcePool.loadImage(O);return this.emitter.emit("sourceloaded",{id:$.id,source:$}),$}async loadAudio(O,$){if(this.checkDisposed(),this.workerClient){let j=await this.workerClient.loadAudio(O,$),Q=this.createWorkerSource(j);if(this.audioManager)await this.loadWorkerAudio(O,Q.id);return this.emitter.emit("sourceloaded",{id:Q.id,source:Q}),Q}let A=await this.sourcePool.loadAudio(O,$);return this.registerSourceAudio(A),this.emitter.emit("sourceloaded",{id:A.id,source:A}),A}unloadSource(O){if(this.workerClient){if(!this.workerSources.get(O))return!1;return this.workerClient.unloadSource(O),this.workerSources.delete(O),this.unloadWorkerAudio(O),this.emitter.emit("sourceunloaded",{id:O}),!0}if(this.registeredAudioSources.has(O))this.audioManager?.unregisterSource(O),this.registeredAudioSources.delete(O);let $=this.sourcePool.unloadSource(O);if($)this.emitter.emit("sourceunloaded",{id:O});return $}registerSourceAudio(O){if(!this.audioManager)return;if(this.registeredAudioSources.has(O.id))return;let $=O.getAudioBufferSink?.();if($)this.audioManager.registerSource(O,$),this.registeredAudioSources.add(O.id)}processAudioLayers(O,$){if(!this.audioManager)return;let A=this.audioScratch.newSourceIds,j=this.audioScratch.newSourceTimes,Q=this.audioScratch.nextActiveSourceIds,V=this.activeAudioSourceIds;A.length=0,j.length=0,Q.clear();for(let J=0;J<O.length;J++){let K=O[J];if(K.muted)continue;let Z=K.source.id;if(!this.audioManager.hasSource(Z))continue;if(Q.add(Z),!V.has(Z))A.push(Z),j.push(K.sourceTime??$)}if(V.size>0)V.clear();for(let J of Q)V.add(J);this.audioManager.processAudioLayers(O,$);for(let J=0;J<A.length;J++)this.audioManager.startSourcePlayback(A[J],j[J])}getSource(O){if(this.workerClient)return this.workerSources.get(O);return this.sourcePool.getSource(O)}getAllSources(){if(this.workerClient)return Array.from(this.workerSources.values());return this.sourcePool.getAllSources()}async render(O){if(this.checkDisposed(),this.workerClient){let U=this.serializeWorkerFrame(O);return this.workerClient.render(U)}let $=this.ctx;if(!$)return!1;let{visibleLayers:A,framePromises:j,frameImages:Q}=this.renderBuffers;A.length=0,j.length=0,Q.length=0;let V=!1,J=-1/0,K=O.layers;for(let U=0;U<K.length;U++){let G=K[U];if(G.visible===!1)continue;let L=G.zIndex??0;if(L<J)V=!0;J=L,A.push(G)}if(A.length===0)return $.fillStyle=this.backgroundColor,$.fillRect(0,0,this.width,this.height),!0;if(V)A.sort((U,G)=>(U.zIndex??0)-(G.zIndex??0));for(let U=0;U<A.length;U++){let G=A[U],L=G.sourceTime??O.time;j[U]=G.source.getFrameAt(L)}let Z=await Promise.all(j);for(let U=0;U<Z.length;U++)Q[U]=Z[U]??null;$.fillStyle=this.backgroundColor,$.fillRect(0,0,this.width,this.height);for(let U=0;U<A.length;U++){let G=Q[U];if(G)this.renderLayer(G,A[U])}return!0}renderLayer(O,$){let A=this.ctx;if(!A)return;let j=$.transform,Q=$.source.width??this.width,V=$.source.height??this.height;if(!j){A.drawImage(O,0,0,Q,V);return}let J=j.width??Q,K=j.height??V,Z=j.x??0,U=j.y??0,G=j.rotation??0,L=j.scaleX??1,P=j.scaleY??1,M=j.opacity??1,X=M!==1;if(!X&&!(G!==0||L!==1||P!==1)){A.drawImage(O,Z,U,J,K);return}let Y=j.anchorX??0.5,q=j.anchorY??0.5;if(A.save(),X)A.globalAlpha=M;if(A.translate(Z+J*Y,U+K*q),G!==0)A.rotate(G*Math.PI/180);if(L!==1||P!==1)A.scale(L,P);A.drawImage(O,-J*Y,-K*q,J,K),A.restore()}createWorkerSource(O){let $={id:O.id,type:O.type,duration:O.duration,width:O.width,height:O.height,async getFrameAt(){throw Error("getFrameAt is not available when worker rendering is enabled")},getAudioBufferSink(){return null},hasAudio(){return O.hasAudio??!1},dispose(){}};return this.workerSources.set($.id,$),$}async loadWorkerAudio(O,$){if(!this.audioManager)return;if(this.workerAudioSources.has($))this.unloadWorkerAudio($);try{let A=await this.sourcePool.loadAudio(O,{id:$});this.workerAudioSources.set($,A),this.registerSourceAudio(A)}catch{}}unloadWorkerAudio(O){if(!this.audioManager)return;if(this.workerAudioSources.has(O))this.audioManager.unregisterSource(O),this.registeredAudioSources.delete(O),this.sourcePool.unloadSource(O),this.workerAudioSources.delete(O)}serializeWorkerFrame(O){if(!this.workerClient)throw Error("Worker compositor not initialized");let $=O.layers,A=Array($.length);for(let j=0;j<$.length;j++){let Q=$[j],V=Q.source.id;if(!this.workerSources.has(V))throw Error(`Layer source ${V} is not managed by this compositor`);A[j]={sourceId:V,sourceTime:Q.sourceTime,transform:Q.transform,visible:Q.visible,zIndex:Q.zIndex}}return{time:O.time,layers:A}}clear(){if(this.workerClient){this.workerClient.clear();return}if(!this.ctx)return;this.ctx.fillStyle=this.backgroundColor,this.ctx.fillRect(0,0,this.width,this.height)}preview(O){this.checkDisposed(),this.previewOptions=O,this.state.duration=O.duration,this.lastRenderTime=0,this.emitter.emit("compositionchange",void 0)}async play(){if(this.checkDisposed(),this.state.playing)return;if(!this.previewOptions)throw Error("No preview configured. Call preview() first.");if(this.state.playing=!0,this.lastFrameTime=performance.now(),this.lastRenderTime=this.lastFrameTime,this.emitter.emit("play",void 0),this.audioManager)this.activeAudioSourceIds.clear(),await this.audioManager.play(this.state.currentTime);this.startRenderLoop()}pause(){if(this.checkDisposed(),!this.state.playing)return;if(this.state.playing=!1,this.stopRenderLoop(),this.audioManager)this.audioManager.pause();this.emitter.emit("pause",void 0)}async seek(O){if(this.checkDisposed(),!this.previewOptions)return;let $=Math.max(0,Math.min(O,this.state.duration));if(this.state.seeking=!0,this.emitter.emit("seeking",{time:$}),this.state.currentTime=$,this.audioManager)await this.audioManager.seek($);let A=this.previewOptions.getComposition($);await this.render(A),this.state.seeking=!1,this.emitter.emit("seeked",{time:$}),this.emitter.emit("timeupdate",{currentTime:$})}startRenderLoop(){if(this.animationFrameId!==null)return;let O=()=>{if(!this.state.playing||!this.previewOptions)return;this.animationFrameId=requestAnimationFrame(O);let $=performance.now(),A=($-this.lastFrameTime)/1000;if(this.lastFrameTime=$,this.state.currentTime+=A,this.state.currentTime>=this.state.duration)if(this.previewOptions.loop)this.state.currentTime=0;else{this.state.currentTime=this.state.duration,this.pause(),this.emitter.emit("ended",void 0);return}let j=this.previewOptions.fps??0,Q=j>0?1000/j:0;if(!this.renderPending&&(Q===0||$-this.lastRenderTime>=Q)){this.renderPending=!0,this.lastRenderTime=$;let J=this.previewOptions.getComposition(this.state.currentTime);if(this.audioManager)this.processAudioLayers(J.audio??[],this.state.currentTime);this.render(J).catch(()=>{}).finally(()=>{this.renderPending=!1})}if($-this.lastTimeUpdateEmit>=this.timeUpdateThrottleMs)this.lastTimeUpdateEmit=$,this.emitter.emit("timeupdate",{currentTime:this.state.currentTime})};this.animationFrameId=requestAnimationFrame(O)}stopRenderLoop(){if(this.animationFrameId!==null)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}async exportFrame(O,$={}){if(this.checkDisposed(),!this.previewOptions)return null;let A=this.previewOptions.getComposition(O);if(this.workerClient){let j=this.serializeWorkerFrame(A);return this.workerClient.exportFrame(j,$)}if(await this.render(A),"toBlob"in this.canvas)return new Promise((j)=>{this.canvas.toBlob((Q)=>j(Q),`image/${$.format??"png"}`,$.quality)});else return this.canvas.convertToBlob({type:`image/${$.format??"png"}`,quality:$.quality})}get currentTime(){return this.state.currentTime}get duration(){return this.state.duration}get playing(){return this.state.playing}get paused(){return!this.state.playing}get seeking(){return this.state.seeking}getWidth(){return this.width}getHeight(){return this.height}resize(O,$){if(this.checkDisposed(),this.width=O,this.height=$,this.canvas.width=O,this.canvas.height=$,this.workerClient){this.workerClient.resize(O,$);return}this.clear()}on(O,$){return this.emitter.on(O,$)}once(O,$){return this.emitter.once(O,$)}off(O,$){this.emitter.off(O,$)}setVolume(O){this.audioManager?.setMasterVolume(O)}setMuted(O){this.audioManager?.setMasterMuted(O)}getAudioContext(){if(!this.audioManager)throw Error("Audio is disabled for this compositor");return this.audioManager.getAudioContext()}checkDisposed(){if(this.disposed)throw Error("Compositor has been disposed")}dispose(){if(this.disposed)return;this.disposed=!0,this.stopRenderLoop(),this.audioManager?.dispose(),this.workerClient?.dispose(),this.workerClient=null,this.sourcePool.dispose(),this.registeredAudioSources.clear(),this.activeAudioSourceIds.clear(),this.audioScratch.nextActiveSourceIds.clear(),this.audioScratch.newSourceIds.length=0,this.audioScratch.newSourceTimes.length=0,this.workerSources.clear(),this.workerAudioSources.clear(),this.emitter.removeAllListeners(),this.ctx=null,this.previewOptions=null}}import{CanvasSink as FO,VideoSampleSink as SO}from"mediabunny";class S{canvas;ctx=null;isInitialized=!1;rotation=0;constructor(O){this.canvas=O.canvas,this.rotation=O.rotation??0,this.initialize()}initialize(){try{if(this.ctx=this.canvas.getContext("2d",{alpha:!1,desynchronized:!0}),!this.ctx)return!1;return this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.isInitialized=!0,!0}catch{return!1}}isReady(){return this.isInitialized&&this.ctx!==null}render(O){if(!this.isReady()||!this.ctx)return!1;try{let{width:$,height:A}=O;if($===0||A===0)return!1;let j=this.canvas.width,Q=this.canvas.height;if(j===0||Q===0)return!1;let V=this.rotation===90||this.rotation===270,J=V?A:$,K=V?$:A,Z=Math.min(j/J,Q/K),U=Math.round(J*Z),G=Math.round(K*Z),L=Math.round((j-U)/2),P=Math.round((Q-G)/2);if(this.ctx.fillStyle="black",this.ctx.fillRect(0,0,j,Q),this.ctx.save(),this.ctx.translate(L+U/2,P+G/2),this.rotation!==0)this.ctx.rotate(this.rotation*Math.PI/180);if(V)this.ctx.drawImage(O,0,0,$,A,-G/2,-U/2,G,U);else this.ctx.drawImage(O,0,0,$,A,-U/2,-G/2,U,G);return this.ctx.restore(),!0}catch{return!1}}clear(){if(!this.isReady()||!this.ctx)return;this.ctx.fillStyle="black",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)}setRotation(O){this.rotation=O}getRotation(){return this.rotation}dispose(){this.ctx=null,this.isInitialized=!1}}class t{resources;isInitialized=!1;canvas;textureWidth=0;textureHeight=0;options;boundHandleContextLost=null;boundHandleContextRestored=null;rotation=0;positionsArray=new Float32Array(8);vertexShaderSource=`
|
|
2
2
|
attribute vec2 a_position;
|
|
3
3
|
attribute vec2 a_texCoord;
|
|
4
4
|
varying vec2 v_texCoord;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mediafox/core",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.9",
|
|
4
4
|
"description": "Framework-agnostic media player library powered by MediaBunny",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./compositor-worker": {
|
|
15
|
+
"import": "./dist/compositor-worker.js"
|
|
13
16
|
}
|
|
14
17
|
},
|
|
15
18
|
"files": [
|
|
@@ -18,7 +21,7 @@
|
|
|
18
21
|
"scripts": {
|
|
19
22
|
"dev": "bun run --watch src/index.ts",
|
|
20
23
|
"build": "bun run build:js && bun run build:types",
|
|
21
|
-
"build:js": "bun build src/index.ts --outdir=dist --target=browser --format=esm --minify --external mediabunny && bun build src/compositor/compositor-worker.ts --outdir=dist --target=browser --format=esm --minify
|
|
24
|
+
"build:js": "bun build src/index.ts --outdir=dist --target=browser --format=esm --minify --external mediabunny && bun build src/compositor/compositor-worker.ts --outdir=dist --target=browser --format=esm --minify",
|
|
22
25
|
"build:types": "tsc --emitDeclarationOnly",
|
|
23
26
|
"test": "bun test",
|
|
24
27
|
"lint": "biome lint ./src",
|