@motionscript/browser 0.1.0-alpha.0 → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +187 -0
- package/NOTICE +49 -0
- package/README.md +96 -24
- package/dist/asset-bytes.d.ts +14 -5
- package/dist/asset-bytes.d.ts.map +1 -1
- package/dist/asset-bytes.js +23 -5
- package/dist/asset-bytes.js.map +1 -1
- package/dist/audio/bus-graph.d.ts +12 -3
- package/dist/audio/bus-graph.d.ts.map +1 -1
- package/dist/audio/bus-graph.js +35 -31
- package/dist/audio/bus-graph.js.map +1 -1
- package/dist/audio/effect-graph.d.ts +62 -0
- package/dist/audio/effect-graph.d.ts.map +1 -0
- package/dist/audio/effect-graph.js +234 -0
- package/dist/audio/effect-graph.js.map +1 -0
- package/dist/audio/index.d.ts.map +1 -1
- package/dist/audio/index.js +2 -3
- package/dist/audio/index.js.map +1 -1
- package/dist/audio/loop-region.d.ts +31 -0
- package/dist/audio/loop-region.d.ts.map +1 -0
- package/dist/audio/loop-region.js +43 -0
- package/dist/audio/loop-region.js.map +1 -0
- package/dist/audio/mixer.d.ts +4 -4
- package/dist/audio/mixer.d.ts.map +1 -1
- package/dist/audio/mixer.js +43 -44
- package/dist/audio/mixer.js.map +1 -1
- package/dist/audio/player.d.ts +15 -9
- package/dist/audio/player.d.ts.map +1 -1
- package/dist/audio/player.js +60 -69
- package/dist/audio/player.js.map +1 -1
- package/dist/browser/THIRD_PARTY_LICENSES.txt +784 -0
- package/dist/browser/audio.js +1 -1
- package/dist/browser/chunks/chunk-F3AZKPHU.js +2 -0
- package/dist/browser/chunks/chunk-F3AZKPHU.js.map +7 -0
- package/dist/browser/chunks/chunk-KLXMRKTL.js +2 -0
- package/dist/browser/chunks/chunk-L5UFQACH.js +163 -0
- package/dist/browser/chunks/chunk-L5UFQACH.js.map +7 -0
- package/dist/browser/chunks/mediabunny-mp3-encoder-ZCIHVVTJ.js +14 -0
- package/dist/browser/chunks/mediabunny-mp3-encoder-ZCIHVVTJ.js.map +7 -0
- package/dist/browser/index.js +52 -1490
- package/dist/browser/index.js.map +4 -4
- package/dist/browser/manifest.json +21 -4
- package/dist/browser/ms_renderer_bg.wasm +0 -0
- package/dist/concat.d.ts +33 -7
- package/dist/concat.d.ts.map +1 -1
- package/dist/concat.js +117 -72
- package/dist/concat.js.map +1 -1
- package/dist/deliver.d.ts +10 -0
- package/dist/deliver.d.ts.map +1 -0
- package/dist/deliver.js +22 -0
- package/dist/deliver.js.map +1 -0
- package/dist/dynamic-nodes.d.ts.map +1 -1
- package/dist/dynamic-nodes.js +9 -12
- package/dist/dynamic-nodes.js.map +1 -1
- package/dist/engine.d.ts +43 -15
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +58 -36
- package/dist/engine.js.map +1 -1
- package/dist/export-audio.d.ts +36 -0
- package/dist/export-audio.d.ts.map +1 -0
- package/dist/export-audio.js +56 -0
- package/dist/export-audio.js.map +1 -0
- package/dist/exporter.d.ts +134 -15
- package/dist/exporter.d.ts.map +1 -1
- package/dist/exporter.js +135 -90
- package/dist/exporter.js.map +1 -1
- package/dist/formats.d.ts +36 -0
- package/dist/formats.d.ts.map +1 -0
- package/dist/formats.js +83 -0
- package/dist/formats.js.map +1 -0
- package/dist/frame-loop.d.ts +190 -0
- package/dist/frame-loop.d.ts.map +1 -0
- package/dist/frame-loop.js +304 -0
- package/dist/frame-loop.js.map +1 -0
- package/dist/index.d.ts +12 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -47
- package/dist/index.js.map +1 -1
- package/dist/mix-timeline-audio.d.ts +7 -7
- package/dist/mix-timeline-audio.d.ts.map +1 -1
- package/dist/mix-timeline-audio.js +11 -14
- package/dist/mix-timeline-audio.js.map +1 -1
- package/dist/parallel/export-parallel.d.ts +32 -0
- package/dist/parallel/export-parallel.d.ts.map +1 -0
- package/dist/parallel/export-parallel.js +114 -0
- package/dist/parallel/export-parallel.js.map +1 -0
- package/dist/parallel/governor.d.ts +57 -0
- package/dist/parallel/governor.d.ts.map +1 -0
- package/dist/parallel/governor.js +79 -0
- package/dist/parallel/governor.js.map +1 -0
- package/dist/parallel/lane.d.ts +45 -0
- package/dist/parallel/lane.d.ts.map +1 -0
- package/dist/parallel/lane.js +2 -0
- package/dist/parallel/lane.js.map +1 -0
- package/dist/parallel/lanes.d.ts +20 -0
- package/dist/parallel/lanes.d.ts.map +1 -0
- package/dist/parallel/lanes.js +152 -0
- package/dist/parallel/lanes.js.map +1 -0
- package/dist/parallel/plan.d.ts +23 -0
- package/dist/parallel/plan.d.ts.map +1 -0
- package/dist/parallel/plan.js +30 -0
- package/dist/parallel/plan.js.map +1 -0
- package/dist/parallel/run-lanes.d.ts +38 -0
- package/dist/parallel/run-lanes.d.ts.map +1 -0
- package/dist/parallel/run-lanes.js +164 -0
- package/dist/parallel/run-lanes.js.map +1 -0
- package/dist/parallel/session.d.ts +9 -0
- package/dist/parallel/session.d.ts.map +1 -0
- package/dist/parallel/session.js +79 -0
- package/dist/parallel/session.js.map +1 -0
- package/dist/renderer.d.ts +22 -0
- package/dist/renderer.d.ts.map +1 -0
- package/dist/renderer.js +23 -0
- package/dist/renderer.js.map +1 -0
- package/dist/screenshot.d.ts +6 -6
- package/dist/screenshot.d.ts.map +1 -1
- package/dist/screenshot.js +4 -5
- package/dist/screenshot.js.map +1 -1
- package/dist/still.d.ts +32 -24
- package/dist/still.d.ts.map +1 -1
- package/dist/still.js +54 -54
- package/dist/still.js.map +1 -1
- package/dist/ticker.d.ts +41 -9
- package/dist/ticker.d.ts.map +1 -1
- package/dist/ticker.js +113 -41
- package/dist/ticker.js.map +1 -1
- package/package.json +11 -10
- package/dist/audio/filter-graph.d.ts +0 -58
- package/dist/audio/filter-graph.d.ts.map +0 -1
- package/dist/audio/filter-graph.js +0 -235
- package/dist/audio/filter-graph.js.map +0 -1
- package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js +0 -2
- package/dist/browser/chunks/GLTFLoader-PGXD4V5B.js.map +0 -7
- package/dist/browser/chunks/SkeletonUtils-XYDMTGTM.js +0 -2
- package/dist/browser/chunks/chunk-CTLBXZSU.js +0 -4119
- package/dist/browser/chunks/chunk-CTLBXZSU.js.map +0 -7
- package/dist/browser/chunks/chunk-FQ32PDIU.js +0 -2
- package/dist/browser/chunks/chunk-FQ32PDIU.js.map +0 -7
- package/dist/browser/chunks/chunk-FY3BTKY4.js +0 -2
- package/dist/browser/chunks/chunk-FY3BTKY4.js.map +0 -7
- package/dist/browser/chunks/chunk-NSFLRI4P.js +0 -2
- package/dist/browser/chunks/chunk-NSFLRI4P.js.map +0 -7
- package/dist/browser/chunks/three.module-Z4EOVUWF.js +0 -2
- package/dist/browser/chunks/three.module-Z4EOVUWF.js.map +0 -7
- package/dist/decode/image-levels.d.ts +0 -137
- package/dist/decode/image-levels.d.ts.map +0 -1
- package/dist/decode/image-levels.js +0 -477
- package/dist/decode/image-levels.js.map +0 -1
- package/dist/decode/levels.d.ts +0 -37
- package/dist/decode/levels.d.ts.map +0 -1
- package/dist/decode/levels.js +0 -68
- package/dist/decode/levels.js.map +0 -1
- package/dist/decode/video-levels.d.ts +0 -37
- package/dist/decode/video-levels.d.ts.map +0 -1
- package/dist/decode/video-levels.js +0 -95
- package/dist/decode/video-levels.js.map +0 -1
- package/dist/getter.d.ts +0 -10
- package/dist/getter.d.ts.map +0 -1
- package/dist/getter.js +0 -38
- package/dist/getter.js.map +0 -1
- package/dist/measure-context.d.ts +0 -12
- package/dist/measure-context.d.ts.map +0 -1
- package/dist/measure-context.js +0 -12
- package/dist/measure-context.js.map +0 -1
- package/dist/output.d.ts +0 -7
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -6
- package/dist/output.js.map +0 -1
- package/dist/render-context.d.ts +0 -30
- package/dist/render-context.d.ts.map +0 -1
- package/dist/render-context.js +0 -55
- package/dist/render-context.js.map +0 -1
- package/dist/storage-adapter.d.ts +0 -367
- package/dist/storage-adapter.d.ts.map +0 -1
- package/dist/storage-adapter.js +0 -1278
- package/dist/storage-adapter.js.map +0 -1
- package/dist/three/renderer.d.ts +0 -48
- package/dist/three/renderer.d.ts.map +0 -1
- package/dist/three/renderer.js +0 -177
- package/dist/three/renderer.js.map +0 -1
- /package/dist/browser/chunks/{SkeletonUtils-XYDMTGTM.js.map → chunk-KLXMRKTL.js.map} +0 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
function p(r){if(!r)throw new Error("Assertion failed.")}var qt=r=>{let e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},Q=r=>r&&r[r.length-1],Tt=r=>r>=0&&r<2**32,B=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},lt=r=>{let e=B(r);return(e&1)===0?-(e>>1):e+1>>1},vo=(r,e,t,i)=>{for(let s=e;s<t;s++){let n=Math.floor(s/8),a=r[n],o=7-(s&7);a&=~(1<<o),a|=(i&1<<t-s-1)>>t-s-1<<o,r[n]=a}},ee=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),L=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),he=new TextDecoder,te=new TextEncoder,je=r=>{for(let e=0;e<r.length;e++)if(r.charCodeAt(e)>255)return!1;return!0},ta=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},or=ta(Ke),Xe={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},cr=ta(Xe),Qe={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},lr=ta(Qe),fs=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,vr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r),_e=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(s=>{let n=!1;e=()=>{n||(s(),this.pending--,n=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}},Ro=/^[0-9a-fA-F]+$/,Gt=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Fo=r=>{p(r.length%2===0);let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},ra=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),At=(r,e,t)=>{let i=0,s=r.length-1,n=-1;for(;i<=s;){let a=i+s>>1,o=t(r[a]);o===e?(n=a,s=a-1):o<e?i=a+1:s=a-1}return n},H=(r,e,t)=>{let i=0,s=r.length-1,n=-1;for(;i<=s;){let a=i+(s-i+1)/2|0;t(r[a])<=e?(n=a,i=a+1):s=a-1}return n},ia=(r,e,t)=>{let i=H(r,t(e),t);r.splice(i+1,0,e)},ne=()=>{let r,e;return{promise:new Promise((i,s)=>{r=i,e=s}),resolve:r,reject:e}},Bo=(r,e)=>{let t=r.indexOf(e);t!==-1&&r.splice(t,1)},sa=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Rr=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},Mo=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Do=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},le=r=>{throw new Error(`Unexpected value: ${r}`)},Ei=(r,e,t)=>{let i=r.getUint8(e),s=r.getUint8(e+1),n=r.getUint8(e+2);return t?i|s<<8|n<<16:i<<16|s<<8|n};var _i=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},Oo=(r,e,t,i)=>{t=ue(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),_i(r,e,t,i)};var ue=(r,e,t)=>Math.max(e,Math.min(t,r)),Z="und",St=r=>{let e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},Ii=(r,e)=>Math.round(r/e)*e,ut=(r,e)=>Math.round(r*e)/e,hs=(r,e)=>Math.floor(r/e)*e,na=(r,e)=>Math.floor(r*e)/e,Uo=r=>{let e=0;for(;r;)e++,r>>=1;return e},nu=/^[a-z]{3}$/,Fr=r=>nu.test(r),dt=1e6*(1+Number.EPSILON);var zo=(r,e)=>{let t=r<0?-1:1;r=Math.abs(r);let i=0,s=1,n=1,a=0,o=r;for(;;){let c=Math.floor(o),l=c*n+i,u=c*a+s;if(u>e)return{num:t*n,den:a};if(i=n,s=a,n=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*n,den:a}},Ht=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},Yn=null,jt=()=>Yn!==null?Yn:Yn=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Zn=null,vi=()=>Zn!==null?Zn:Zn=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),Jn=null,Ri=()=>Jn!==null?Jn:Jn=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),ea=null,No=()=>{if(ea!==null)return ea;if(typeof navigator>"u")return null;let r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?ea=Number(r[1]):null},ur=(r,e)=>r!==-1?r:e,ms=(r,e,t,i)=>r<=i&&t<=e,ft=function*(r){for(let e in r){let t=r[e];t!==void 0&&(yield{key:e,value:t})}},Vo=r=>{switch(r.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Fi=r=>{let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t};var ps=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},Br=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Bi=r=>typeof r=="number"&&!Number.isNaN(r),ht=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){let o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){let o=r.indexOf("://");if(o===-1)t=e;else{let c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{let o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let i="",s=t.indexOf("://");if(s!==-1){let o=t.indexOf("/",s+3);o!==-1&&(i=t.slice(0,o),t=t.slice(o))}let n=t.split("/"),a=[];for(let o of n)o===".."?a.pop():o!=="."&&a.push(o);return i+a.join("/")},dr=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},Mr=(r,e)=>{let t=-1,i=1/0;for(let s=0;s<r.length;s++){let n=e(r[s]);n<i&&(i=n,t=s)}return t};var xt=r=>{p(Number.isInteger(r.num)),p(Number.isInteger(r.den)),p(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){let s=e%t;e=t,t=s}let i=e||1;return{num:r.num/i,den:r.den/i}},aa=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};var oa=r=>new Promise(e=>setTimeout(e,r));var ca=r=>Array.isArray(r)?r:[r],Le=class{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);let s={fn:t,once:i?.once??!1};return this._listeners.get(e).add(s),()=>{this._listeners.get(e)?.delete(s)}}_emit(...e){let[t,i]=e,s=this._listeners.get(t);if(s)for(let n of s){try{n.fn(i)}catch(a){console.error(a)}n.once&&s.delete(n)}}};var gs=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var $e;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})($e||($e={}));var O=class r{constructor(){}static get level(){return r._level}static set level(e){if(e!==$e.Silent&&e!==$e.Errors&&e!==$e.Warnings&&e!==$e.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");r._level=e}static get _emitter(){return r._emitterInstance??=new Le}static on(e,t,i){return r._emitter.on(e,t,i)}static _error(...e){r._emitter._emit("error",e),r._level>=$e.Errors&&console.error(...e)}static _warn(...e){r._emitter._emit("warn",e),r._level>=$e.Warnings&&console.warn(...e)}static _info(...e){r._emitter._emit("info",e),r._level>=$e.Info&&console.info(...e)}};O._level=$e.Info;O._emitterInstance=null;var de=new Uint8Array(0),X=class r{constructor(e,t,i,s,n=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=s,this.sequenceNumber=n,e===de&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===de}get microsecondTimestamp(){return Math.trunc(dt*this.timestamp)}get microsecondDuration(){return Math.trunc(dt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let i=new Uint8Array(e.byteLength);return e.copyTo(i),new r(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new r(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}};var G=class r{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),s=(t&1<<i)>>i;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let i=this.pos+e;for(let s=this.pos;s<i;s++){let n=Math.floor(s/8),a=this.bytes[n],o=7-(s&7);a&=~(1<<o),a|=(t&1<<i-s-1)>>i-s-1<<o,this.bytes[n]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new r(this.bytes);return e.pos=this.pos,e}};var We=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mt=[-1,1,2,3,4,5,6,8],Dr=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new G(r),t=e.readBits(5);t===31&&(t=32+e.readBits(6));let i=e.readBits(4),s=null;i===15?s=e.readBits(24):i<We.length&&(s=We[i]);let n=e.readBits(4),a=null;return n>=1&&n<=7&&(a=mt[n]),{objectType:t,frequencyIndex:i,sampleRate:s,channelConfiguration:n,numberOfChannels:a}},Or=r=>{let e=We.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);let i=mt.indexOf(r.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let s=13;r.objectType>=32&&(s+=6),e===15&&(s+=24);let n=Math.ceil(s/8),a=new Uint8Array(n),o=new G(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,i),a};var ke=["avc","hevc","vp9","av1","vp8"],ae=["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"],Di=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ie=[...Di,...ae],pt=["webvtt"],Mi=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Lo=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Ct=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Wo=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Ho=".01.01.01.01.00",qo=".0.110.01.01.01.0",Go=(r,e,t,i)=>{if(r==="avc"){let n=Math.ceil(e/16)*Math.ceil(t/16),a=Mi.find(d=>n<=d.maxMacroblocks&&i<=d.maxBitrate)??Q(Mi),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){let o=e*t,c=Lo.find(u=>o<=u.maxPictureSize&&i<=u.maxBitrate)??Q(Lo);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){let n=e*t;return`vp09.00.${(Ct.find(c=>n<=c.maxPictureSize&&i<=c.maxBitrate)??Q(Ct)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){let n=e*t,a=Wo.find(l=>n<=l.maxPictureSize&&i<=l.maxBitrate)??Q(Wo);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)},jo=r=>{let e=r.split("."),t=Number(e[1]),i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,s,4,1,n]},ws=r=>{let e=r.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,f=0,h=e[4]?Number(e[4]):0,g=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(g<<3)+(m<<2)+w;return[s,c,y,0]},Ur=r=>{let{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(p(r.avcType!==null),s){let c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${r.avcType}.${Gt(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${Gt(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,f,h;if(n)c=n.generalProfileSpace,l=n.generalProfileIdc,u=ra(n.generalProfileCompatibilityFlags),d=n.generalTierFlag,f=n.generalLevelIdc,h=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let m=L(t),w=m.getUint8(1);c=w>>6&3,l=w&31,u=ra(m.getUint32(2)),d=w>>5&1,f=m.getUint8(12),h=[];for(let y=0;y<6;y++)h.push(m.getUint8(6+y))}let g="hev1.";for(g+=["","A","B","C"][c]+l,g+=".",g+=u.toString(16).toUpperCase(),g+=".",g+=d===0?"L":"H",g+=f;h.length>0&&h[h.length-1]===0;)h.pop();return h.length>0&&(g+=".",g+=h.map(m=>m.toString(16).toUpperCase()).join(".")),g}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let y=r.width*r.height,b=Q(Ct).level;for(let S of Ct)if(y<=S.maxPictureSize){b=S.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),f=a.colourPrimaries.toString().padStart(2,"0"),h=a.transferCharacteristics.toString().padStart(2,"0"),g=a.matrixCoefficients.toString().padStart(2,"0"),m=a.videoFullRangeFlag.toString().padStart(2,"0"),w=`vp09.${c}.${l}.${u}.${d}`;return w+=`.${f}.${h}.${g}.${m}`,w.endsWith(Ho)&&(w=w.slice(0,-Ho.length)),w}else if(e==="av1"){if(!o){let S=r.width*r.height,T=Q(Ct).level;for(let A of Ct)if(S<=A.maxPictureSize){T=A.level;break}return`av01.0.${T.toString().padStart(2,"0")}M.08`}let c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",h=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),g=i?.primaries?Ke[i.primaries]:1,m=i?.transfer?Xe[i.transfer]:1,w=i?.matrix?Qe[i.matrix]:1,y=i?.fullRange?1:0,b=`av01.${c}.${l}${u}.${d}`;return b+=`.${f}.${h.toString().padStart(3,"0")}`,b+=`.${g.toString().padStart(2,"0")}`,b+=`.${m.toString().padStart(2,"0")}`,b+=`.${w.toString().padStart(2,"0")}`,b+=`.${y}`,b.endsWith(qo)&&(b=b.slice(0,-qo.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},Ko=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(ae.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},zr=r=>{let{codec:e,codecDescription:t,aacCodecInfo:i}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let s;return i.objectType!==null?s=i.objectType:s=Dr(t).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&ae.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)};var Pt=48e3,Xo=/^pcm-([usf])(\d+)(be)?$/,xe=r=>{if(p(ae.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let e=Xo.exec(r);p(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";let i=Number(e[2])/8,s=e[3]!=="be",n=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:s,silentValue:n}},Et=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Xo.test(r)?r:r==="webvtt"?"webvtt":null,Qo=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},$o=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},au=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],ou=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,cu=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,lu=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,uu=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ys=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!au.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!vr(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let t=Object.keys(Ke);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);let i=Object.keys(Xe);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let s=Object.keys(Qe);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!ou.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!cu.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!lu.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!uu.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},du=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Nr=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!du.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!vr(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!ae.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ae.join(", ")}).`)},bs=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var ks=class{static supports(e,t){return!1}},Ts=class{static supports(e,t){return!1}},xs=[],la=[],Vr=[],Lr=[];var fu=r=>{if(r.prototype instanceof ks){let e=r;if(Vr.includes(e)){O._warn("Video encoder already registered.");return}Vr.push(e),As.clear()}else if(r.prototype instanceof Ts){let e=r;if(Lr.includes(e)){O._warn("Audio encoder already registered.");return}Lr.push(e),Ss.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var hu=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(s=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");s&&(i=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},mu=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,s=0;function n(){for(;i=e.stack.pop();)try{if(!i.async&&s===1)return s=0,e.stack.push(i),Promise.resolve().then(n);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});Br();var Yo=-1/0,Zo=-1/0,Vi=null;typeof FinalizationRegistry<"u"&&(Vi=new FinalizationRegistry(r=>{let e=performance.now();r.type==="video"?(e-Yo>=1e3&&(O._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Yo=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Zo>=1e3&&(O._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Zo=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));var _t=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},ua=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],pu=new Set(ua),Ye=class r{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(dt*this.timestamp)}get microsecondDuration(){return Math.trunc(dt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!pu.has(t.format))throw new TypeError("init.format must be one of: "+ua.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let s of t.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&aa(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=t._doNotCopy?ee(e):ee(e).slice(),this._layout=t.layout??yu(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let i=t.colorSpace??null;i===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?i={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:i={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Ni(i),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&aa(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Ni(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new r(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*dt),duration:Math.trunc((t.duration??0)*dt)||void 0}),t);let i=0,s=0;if("naturalWidth"in e?(i=e.naturalWidth,s=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,s=e.videoHeight):"width"in e&&(i=Number(e.width),s=Number(e.height)),!i||!s)throw new TypeError("Could not determine dimensions.");let n=new OffscreenCanvas(i,s),a=n.getContext("2d",{alpha:vi(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:i,height:s},this.squarePixelWidth=i,this.squarePixelHeight=s,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Ni({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof _t){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!ua.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=xt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Vi?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),this._data instanceof _t?new r(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ui(this._data)?new r(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(p(this._layout),new r(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new r(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Vi?.unregister(this),this._data instanceof _t?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ui(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ec(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Ui(this._data)?this._data.allocationSize(e):tc(this,e).allocationSize}async copyTo(e,t={}){if(!vr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ec(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(p(this._data!==null),Ui(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof _t){let l={stack:[],error:void 0,hasError:!1};try{let u=hu(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof r))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{mu(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}let i=tc(this,t);p(this.format);let s=ee(e);if(s.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${s.byteLength}`);let n=Ps(this.format),a;if(this._data instanceof _t){let l=this._data.getDataPlanes();if(l instanceof Promise&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)p(this._layout),p(this._layout.length===n.length),a=this._layout.map((l,u)=>{let d=Math.ceil(this.codedHeight/n[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{let u=this._data.getContext("2d");p(u);let d=u.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:ee(d.data),stride:4*this.codedWidth}]}let o=[],c=n.length;for(let l=0;l<c;l++){let u=i.computedLayouts[l],d=a[l].stride,f=a[l].data,h=u.sourceTop*d;h+=u.sourceLeftBytes;let g=u.destinationOffset,m=u.sourceWidthBytes,w={offset:g,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(g+m>s.byteLength)throw new Error("Destination buffer OOB write.");let b=f.subarray(h,h+m);s.set(b,g),h+=d,g+=u.destinationStride}o.push(w)}if(t.format!==void 0){let l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<i.allocationSize;d+=4){if(l){let f=s[d],h=s[d+2];s[d]=h,s[d+2]=f}u&&(s[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof _t){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let t=e.reduce((a,o)=>a+o.data.byteLength,0),i=new Uint8Array(t),s=0,n=[];for(let a of e)i.set(a.data,s),n.push(s),s+=a.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((a,o)=>({offset:n[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Ui(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,s,n,a,o,c,l){let u=0,d=0,f=this.displayWidth,h=this.displayHeight,g=0,m=0,w=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=i,f=s,h=n,g=a,m=o,c!==void 0?(w=c,y=l):(w=f,y=h)):(g=t,m=i,s!==void 0&&(w=s,y=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(g))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:h}=this._rotateSourceRegion(u,d,f,h,this.rotation));let b=this.toCanvasImageSource();e.save();let S=g+w/2,T=m+y/2;e.translate(S,T),e.rotate(this.rotation*Math.PI/180);let A=this.rotation%180===0?1:w/y;e.scale(1/A,A),e.drawImage(b,u,d,f,h,-w/2,-y/2,w,y),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Li(t.crop,"options.");let i=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,[a,o]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&(c=da(c,a,o));let l,u,d,f,{sx:h,sy:g,sWidth:m,sHeight:w}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,n);if(t.fit==="fill")l=0,u=0,d=i,f=s;else{let[b,S]=t.crop?[t.crop.width,t.crop.height]:[a,o],T=t.fit==="contain"?Math.min(i/b,s/S):Math.max(i/b,s/S);d=b*T,f=S*T,l=(i-d)/2,u=(s-f)/2}e.save();let y=n%180===0?1:d/f;e.translate(i/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/y,y),e.translate(-i/2,-s/2),e.drawImage(this.toCanvasImageSource(),h,g,m,w,l,u,d,f),e.restore()}_rotateSourceRegion(e,t,i,s,n){return n===90?[e,t,i,s]=[t,this.squarePixelHeight-e-i,s,i]:n===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-s]:n===270&&([e,t,i,s]=[this.squarePixelWidth-t-s,e,s,i]),{sx:e,sy:t,sWidth:i,sHeight:s}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof _t||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Li(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let t=qt(this.rotation+(e.rotate??0)),[i,s]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],n=e.crop;n&&(n=da(n,i,s));let a=n?n.width:i,o=n?n.height:s,c=a/o,l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=Ii(l,e.roundDimensionsTo??1),u=Ii(u,e.roundDimensionsTo??1);let d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:n??{left:0,top:0,width:i,height:s},alpha:e.alpha??"keep"};for(let m of gu){let w=m(this,d);if(w instanceof Promise&&(w=await w),w!==null)return w}let f=null,h=!1;for(let m of Oi)if(m.canvas.width===d.width&&m.canvas.height===d.height){f=m.canvas,m.age=Jo++;break}if(f===null){if(typeof OffscreenCanvas<"u")f=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");f=document.createElement("canvas"),f.width=d.width,f.height=d.height}h=!0,Oi.length>=wu&&Oi.splice(Mr(Oi,m=>m.age),1),Oi.push({canvas:f,age:Jo++})}let g=f.getContext("2d",{alpha:!0});if(!g)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return d.alpha==="discard"?(g.fillStyle="black",g.fillRect(0,0,d.width,d.height)):h||g.clearRect(0,0,d.width,d.height),this.drawWithFit(g,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new r(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}},gu=[];var wu=3,Oi=[],Jo=0,Ni=class{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let t=Object.keys(Ke);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let i=Object.keys(Xe);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);let s=Object.keys(Qe);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Ui=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,da=(r,e,t)=>{let i=Math.min(r.left,e),s=Math.min(r.top,t),n=Math.min(r.width,e-i),a=Math.min(r.height,t-s);return p(n>=0),p(a>=0),{left:i,top:s,width:n,height:a}},Li=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},ec=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},yu=(r,e,t)=>{let i=Ps(r),s=[],n=0;for(let a of i){let o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;s.push({offset:n,stride:l}),n+=u}return s},Ps=r=>{let e=(t,i,s,n,a)=>{let o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:s,heightDivisor:n},{sampleBytes:i,widthDivisor:s,heightDivisor:n}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:le(r),p(!1)}},tc=(r,e)=>{let t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,s=bu(t,i,r.codedWidth,r.codedHeight,r.format),n=e.layout,a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Tu(s,a,n)},bu=(r,e,t,i,s)=>{let n={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");n.x=e.x||0,n.y=e.y||0,n.width=e.width||0,n.height=e.height||0}if(!ku(s,n))throw new TypeError("visibleRect alignment is invalid for the format.");return n},ku=(r,e)=>{if(r===null)return!0;let t=Ps(r);for(let i=0;i<t.length;i++){let s=t[i],n=s.widthDivisor,a=s.heightDivisor;if((e.x||0)%n!==0||(e.y||0)%a!==0)return!1}return!0},Tu=(r,e,t)=>{let i=Ps(e),s=i.length;if(t!==void 0&&t.length!==s)throw new TypeError(`Layout must have ${s} planes.`);let n=0,a=[],o=[];for(let c=0;c<s;c++){let l=i[c],u=l.sampleBytes,d=l.widthDivisor,f=l.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(r.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(r.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,h.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){let w=t[c];if(w.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=w.offset,h.destinationStride=w.stride}else h.destinationOffset=n,h.destinationStride=h.sourceWidthBytes;let m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),n=Math.max(n,m);for(let w=0;w<c;w++){let y=a[w];if(!(o[c]<=y.destinationOffset||o[w]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:n,computedLayouts:a}},Cs=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),fr=class{constructor(){this._referenceCount=0}},gt=class r{get microsecondTimestamp(){return Math.trunc(dt*this.timestamp)}get microsecondDuration(){return Math.trunc(dt*this.duration)}constructor(e){if(this._closed=!1,zi(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof fr){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Cs.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Cs.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");let t=e.data.byteLength/(Kt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let s=this.numberOfFrames*this.numberOfChannels*Kt(this.format);if(i.byteLength<s)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Vi?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Cs.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(s>this.numberOfFrames-i)throw new RangeError("frameCount out of range");let n=Kt(t),a=hr(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?s:s*this.numberOfChannels)*n}copyTo(e,t){if(!vr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Cs.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:i,frameCount:s,frameOffset:n}=t,{planeIndex:a}=t,o=this.format,c=i??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=n??0;if(d>=l)throw new RangeError("frameOffset out of range");let f=s!==void 0?s:l-d;if(f>l-d)throw new RangeError("frameCount out of range");let h=Kt(c),g=hr(c);if(g&&a>=u)throw new RangeError("planeIndex out of range");if(!g&&a!==0)throw new RangeError("planeIndex out of range");let w=(g?f:f*u)*h;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");let y=L(e),b=ic(c);if(zi(this._data))jt()&&u>2&&c!==o?Au(this._data,y,o,c,u,a,d,f):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});else{let S=rc(o),T=Kt(o),A=hr(o),P;if(this._data instanceof fr){let C=x=>{let _=this._data.getDataPlane(x);if(!(_ instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let F=l*T*(A?1:u);if(_.byteLength!==F)throw new TypeError(`Data plane ${x} has invalid size. Expected exactly ${F} bytes, got ${_.byteLength} bytes.`);return _};if(A)if(g)P=C(a),a=0;else{P=new Uint8Array(l*T*u);for(let x=0;x<u;x++){let _=C(x);P.set(_,x*l*T)}}else P=C(0)}else P=this._data;let E=L(P);for(let C=0;C<f;C++)if(g){let x=C*h,_;A?_=(a*l+(C+d))*T:_=((C+d)*u+a)*T;let F=S(E,_);b(y,x,F)}else for(let x=0;x<u;x++){let F=(C*u+x)*h,I;A?I=(x*l+(C+d))*T:I=((C+d)*u+x)*T;let U=S(E,I);b(y,F,U)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof fr){let e=new r(this._data);return e.setTimestamp(this.timestamp),e}else if(zi(this._data)){let e=new r(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new r({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startSample out of range.");if(t>this.numberOfFrames)throw new RangeError("endSample out of range.");if(t<e)throw new RangeError("endSample must not be less than startSample.");if(this._closed)throw new Error("AudioSample is closed.");let i=t-e,s=Kt(this.format),n;if(hr(this.format)){let a=i*s;if(n=new Uint8Array(a*this.numberOfChannels),i>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(n.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:i})}else n=new Uint8Array(i*this.numberOfChannels*s),i>0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new r({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Vi?.unregister(this),this._data instanceof fr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):zi(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof fr?this._createAudioDataFromData():zi(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(hr(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s),c=0,l=a;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(s*u);for(let f=0;f<s;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new r({format:"f32-planar",sampleRate:n,numberOfFrames:u,numberOfChannels:s,timestamp:t+c/n,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s),c=0,l=a,u=[];for(;l>0;){let d=Math.min(o,l),f=new Float32Array(s*d);for(let g=0;g<s;g++)e.copyFromChannel(f.subarray(g*d,(g+1)*d),g,c);let h=new r({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:s,timestamp:t+c/n,data:f});u.push(h),c+=d,l-=d}return u}},Kt=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},hr=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},rc=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},ic=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,ue((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,ue(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,ue(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},zi=r=>typeof AudioData<"u"&&r instanceof AudioData,sc=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},Au=(r,e,t,i,s,n,a,o)=>{let c=rc(t),l=ic(i),u=Kt(t),d=Kt(i),f=hr(t);if(hr(i))if(f){let g=new ArrayBuffer(o*u),m=L(g);r.copyTo(g,{planeIndex:n,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){let y=w*u,b=w*d,S=c(m,y);l(e,b,S)}}else{let g=new ArrayBuffer(o*s*u),m=L(g);r.copyTo(g,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){let y=(w*s+n)*u,b=w*d,S=c(m,y);l(e,b,S)}}else if(f){let g=o*u,m=new ArrayBuffer(g),w=L(m);for(let y=0;y<s;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){let S=b*u,T=(b*s+y)*d,A=c(w,S);l(e,T,A)}}}else{let g=new ArrayBuffer(o*s*u),m=L(g);r.copyTo(g,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++)for(let y=0;y<s;y++){let b=w*s+y,S=b*u,T=b*d,A=c(m,S);l(e,T,A)}}},nc=(r,e)=>{let t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new gt({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};var As=new Map,Ss=new Map,ac=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!ke.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${ke.join(", ")}.`);if(!(r.bitrate instanceof ve)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Li(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");oc(r.codec,r)},oc=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Et(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},fa=r=>{let e=r.bitrate instanceof ve?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Go(r.codec,r.width,r.height,e),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...Qo(r.codec)}},cc=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Ie.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Ie.join(", ")}.`);if(r.bitrate===void 0&&!(ae.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof ve)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");lc(r.codec,r)},lc=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Et(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},ha=r=>{let e=r.bitrate instanceof ve?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??Ko(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...$o(r.codec)}},ve=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){let s=t*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(s/a,.95),d=o*c*n[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(ae.includes(e)||e==="flac")return;let i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let s=i*this._factor;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a)),Math.round(s/1e3)*1e3}},Su=new ve(.3),xu=new ve(.6),Cu=new ve(1),Pu=new ve(2),Eu=new ve(4);var _u=async(r,e={})=>{let{width:t=1280,height:i=720,bitrate:s=1e6,...n}=e;if(!ke.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(s instanceof ve)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");oc(r,n);let a=fa({codec:r,width:t,height:i,bitrate:s,framerate:void 0,...n,alpha:"discard"}),o=JSON.stringify(a),c=As.get(o);if(c)return c;let l=(async()=>Vr.some(f=>f.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(r==="avc"||r==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:vi()?new Promise(async f=>{try{let h=new VideoEncoder({output:()=>{},error:()=>f(!1)});h.configure(a);let g=new Uint8Array(t*i*4),m=new VideoFrame(g,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});h.encode(m),m.close(),await h.flush(),f(!0)}catch{f(!1)}}):!0)();return As.set(o,l),l},Iu=async(r,e={})=>{let{numberOfChannels:t=2,sampleRate:i=48e3,bitrate:s=128e3,...n}=e;if(!Ie.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(s instanceof ve)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");lc(r,n);let a=ha({codec:r,numberOfChannels:t,sampleRate:i,bitrate:s,...n}),o=JSON.stringify(a),c=Ss.get(o);if(c)return c;let l=(async()=>Lr.some(d=>d.supports(r,a))||ae.includes(r)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported(a)).supported===!0)();return Ss.set(o,l),l};var Ze=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}},mr=class{constructor(e,t,i,s){if(this.data=e,this.mimeType=t,this.name=i,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}},uc=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(let e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Ze)&&!(e instanceof mr)&&!gs(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Es=r=>r.title===void 0&&r.description===void 0&&r.artist===void 0&&r.album===void 0&&r.albumArtist===void 0&&r.trackNumber===void 0&&r.tracksTotal===void 0&&r.discNumber===void 0&&r.discsTotal===void 0&&r.genre===void 0&&r.date===void 0&&r.lyrics===void 0&&(!r.images||r.images.length===0)&&r.comment===void 0&&(r.raw===void 0||Object.keys(r.raw).length===0),we={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},dc=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var vu=[44100,48e3,32e3],_s=[-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],Xt=1483304551,Wr=1231971951,Is=(r,e,t,i,s)=>e===0?0:e===1?Math.floor(144*t/(i<<r))+s:e===2?Math.floor(144*t/i)+s:(Math.floor(12*t/i)+s)*4,fc=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,Qt=(r,e)=>r===3?e===3?21:36:e===3?13:21,pr=(r,e)=>{let t=r>>>24,i=r>>>16&255,s=r>>>8&255,n=r&255;if(t!==255&&i!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);let c=i>>3&3,l=i>>1&3,u=s>>4&15,d=(s>>2&3)%3,f=s>>1&1,h=n>>6&3,g=n>>4&3,m=n>>3&1,w=n>>2&1,y=n&3,b=_s[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};let S=b*1e3,T=vu[d]>>a+o,A=Is(a,l,S,T,f);if(e!==null&&e<A)return{header:null,bytesAdvanced:1};let P;return c===3?P=l===3?384:1152:l===3?P=384:l===2?P=1152:P=576,{header:{totalSize:A,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:S,frequencyIndex:d,sampleRate:T,channel:h,modeExtension:g,copyright:m,original:w,emphasis:y,audioSamplesInFrame:P},bytesAdvanced:1}},hc=r=>{let e=127,t=0,i=r;for(;(e^2147483647)!==0;)t=i&~e,t<<=1,t|=i&e,e=(e+1<<8)-1,i=t;return t},vs=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t},It;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(It||(It={}));var $t=r=>r===3?1:2;var gr=[48e3,44100,32e3],ma=[24e3,22050,16e3];var pe;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(pe||(pe={}));var fe;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(fe||(fe={}));var Hr=function*(r){let e=0,t=-1;for(;e<r.length-2;){let i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let s=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?s=4:r[e+1]===0&&r[e+2]===1&&(s=3),s===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+s,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},gc=function*(r,e){let t=0,i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let s;e===1?s=i.getUint8(t):e===2?s=i.getUint16(t,!1):e===3?s=Ei(i,t,!1):(p(e===4),s=i.getUint32(t,!1)),t+=e,yield{offset:t,length:s},t+=s}},ga=(r,e)=>{if(e.description){let s=(ee(e.description)[4]&3)+1;return gc(r,s)}else return Hr(r)},qr=r=>r&31,Rs=r=>{let e=[],t=r.length;for(let i=0;i<t;i++)i+2<t&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(0,0),i+=2):e.push(r[i]);return new Uint8Array(e)},pa=new Uint8Array([0,0,0,1]),wc=r=>{let e=r.reduce((s,n)=>s+pa.byteLength+n.byteLength,0),t=new Uint8Array(e),i=0;for(let s of r)t.set(pa,i),i+=pa.byteLength,t.set(s,i),i+=s.byteLength;return t},Fs=(r,e)=>{let t=r.reduce((n,a)=>n+e+a.byteLength,0),i=new Uint8Array(t),s=0;for(let n of r){let a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:_i(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,i.set(n,s),s+=n.byteLength}return i},yc=(r,e)=>{if(e.description){let s=(ee(e.description)[4]&3)+1;return Fs(r,s)}else return wc(r)},Gr=r=>{try{let e=[],t=[],i=[];for(let o of Hr(r)){let c=r.subarray(o.offset,o.offset+o.length),l=qr(c[0]);l===pe.SPS?e.push(c):l===pe.PPS?t.push(c):l===pe.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;let s=e[0],n=Hi(s);p(n!==null);let a=n.profileIdc===100||n.profileIdc===110||n.profileIdc===122||n.profileIdc===144;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?n.chromaFormatIdc:null,bitDepthLumaMinus8:a?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return O._error("Error building AVC Decoder Configuration Record:",e),null}},bc=r=>{let e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(let t of r.sequenceParameterSets){let i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}e.push(r.pictureParameterSets.length);for(let t of r.pictureParameterSets){let i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){p(r.chromaFormat!==null),p(r.bitDepthLumaMinus8!==null),p(r.bitDepthChromaMinus8!==null),p(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(let t of r.sequenceParameterSetExt){let i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}}return new Uint8Array(e)},kc=r=>{try{let e=L(r),t=0,i=e.getUint8(t++),s=e.getUint8(t++),n=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let h=0;h<c;h++){let g=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+g)),t+=g}let u=e.getUint8(t++),d=[];for(let h=0;h<u;h++){let g=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+g)),t+=g}let f={configurationVersion:i,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&t+4<=r.length){let h=e.getUint8(t++)&3,g=e.getUint8(t++)&7,m=e.getUint8(t++)&7,w=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=g,f.bitDepthChromaMinus8=m;let y=[];for(let b=0;b<w;b++){let S=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+S)),t+=S}f.sequenceParameterSetExt=y}return f}catch(e){return O._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Tc={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Hi=r=>{try{let e=new G(Rs(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();B(e);let a=1,o=0,c=0,l=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=B(e),a===3&&(l=e.readBits(1)),o=B(e),c=B(e),e.skipBits(1),e.readBits(1))){for(let I=0;I<(a!==3?8:12);I++)if(e.readBits(1)){let q=I<6?16:64,W=8,V=8;for(let ce=0;ce<q;ce++){if(V!==0){let Se=lt(e);V=(W+Se+256)%256}W=V===0?W:V}}}B(e);let u=B(e);if(u===0)B(e);else if(u===1){e.skipBits(1),lt(e),lt(e);let F=B(e);for(let I=0;I<F;I++)lt(e)}B(e),e.skipBits(1);let d=B(e),f=B(e),h=16*(d+1),g=16*(f+1),m=h,w=g,y=e.readBits(1);if(y||e.skipBits(1),e.skipBits(1),e.readBits(1)){let F=B(e),I=B(e),U=B(e),q=B(e),W,V;if((l===0?a:0)===0)W=1,V=2-y;else{let Se=a===3?1:2,ct=a===1?2:1;W=Se,V=ct*(2-y)}m-=W*(F+I),w-=V*(U+q)}let S=2,T=2,A=2,P=0,E={num:1,den:1},C=null,x=null;if(e.readBits(1)){if(e.readBits(1)){let ct=e.readBits(8);if(ct===255)E={num:e.readBits(16),den:e.readBits(16)};else{let Io=Tc[ct];Io&&(E=Io)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),P=e.readBits(1),e.readBits(1)&&(S=e.readBits(8),T=e.readBits(8),A=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let V=e.readBits(1);V&&mc(e);let ce=e.readBits(1);ce&&mc(e),(V||ce)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),B(e),B(e),B(e),B(e),C=B(e),x=B(e))}if(C===null){p(x===null);let F=s&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&F)C=0,x=0;else{let I=d+1,U=f+1,q=(2-y)*U,W=Mi.find(ce=>ce.level>=n)??Q(Mi),V=Math.min(Math.floor(W.maxDpbMbs/(I*q)),16);C=V,x=V}}return p(x!==null),{profileIdc:i,constraintFlags:s,levelIdc:n,frameMbsOnlyFlag:y,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:g,displayWidth:m,displayHeight:w,pixelAspectRatio:E,colourPrimaries:S,matrixCoefficients:A,transferCharacteristics:T,fullRangeFlag:P,numReorderFrames:C,maxDecFrameBuffering:x}}catch(e){return O._error("Error parsing AVC SPS:",e),null}},mc=r=>{let e=B(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)B(r),B(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Ru=(r,e)=>{if(e.description){let s=(ee(e.description)[21]&3)+1;return Fs(r,s)}else return wc(r)},Wi=(r,e)=>{if(e.description){let s=(ee(e.description)[21]&3)+1;return gc(r,s)}else return Hr(r)},Yt=r=>r>>1&63,wa=r=>{try{let e=new G(Rs(r));e.skipBits(16),e.readBits(4);let t=e.readBits(3),i=e.readBits(1),{general_profile_space:s,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Fu(e,t);B(e);let u=B(e),d=0;u===3&&(d=e.readBits(1));let f=B(e),h=B(e),g=f,m=h;if(e.readBits(1)){let I=B(e),U=B(e),q=B(e),W=B(e),V=1,ce=1,Se=d===0?u:0;Se===1?(V=2,ce=2):Se===2&&(V=2,ce=1),g-=(I+U)*V,m-=(q+W)*ce}let w=B(e),y=B(e);B(e);let S=e.readBits(1)?0:t,T=0;for(let I=S;I<=t;I++)B(e),T=B(e),B(e);B(e),B(e),B(e),B(e),B(e),B(e),e.readBits(1)&&e.readBits(1)&&Bu(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),B(e),B(e),e.skipBits(1));let A=B(e);if(Mu(e,A),e.readBits(1)){let I=B(e);for(let U=0;U<I;U++)B(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let P=2,E=2,C=2,x=0,_=0,F={num:1,den:1};if(e.readBits(1)){let I=Ou(e,t);F=I.pixelAspectRatio,P=I.colourPrimaries,E=I.transferCharacteristics,C=I.matrixCoefficients,x=I.fullRangeFlag,_=I.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:m,pixelAspectRatio:F,colourPrimaries:P,transferCharacteristics:E,matrixCoefficients:C,fullRangeFlag:x,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:w,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:_}}catch(e){return O._error("Error parsing HEVC SPS:",e),null}},jr=r=>{try{let e=[],t=[],i=[],s=[];for(let l of Hr(r)){let u=r.subarray(l.offset,l.offset+l.length),d=Yt(u[0]);d===fe.VPS_NUT?e.push(u):d===fe.SPS_NUT?t.push(u):d===fe.PPS_NUT?i.push(u):(d===fe.PREFIX_SEI_NUT||d===fe.SUFFIX_SEI_NUT)&&s.push(u)}if(t.length===0||i.length===0)return null;let n=wa(t[0]);if(!n)return null;let a=0;if(i.length>0){let l=i[0],u=new G(Rs(l));u.skipBits(16),B(u),B(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),B(u),B(u),lt(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&B(u),lt(u),lt(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);let d=u.readBits(1),f=u.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}let o=[...e.length?[{arrayCompleteness:1,nalUnitType:fe.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:fe.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:fe.PPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Yt(s[0][0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return O._error("Error building HEVC Decoder Configuration Record:",e),null}},Fu=(r,e)=>{let t=r.readBits(2),i=r.readBits(1),s=r.readBits(5),n=0;for(let u=0;u<32;u++)n=n<<1|r.readBits(1);let a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);let o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},Bu=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))B(r);else{let s=Math.min(64,1<<4+(e<<1));e>1&<(r);for(let n=0;n<s;n++)lt(r)}},Mu=(r,e)=>{let t=[];for(let i=0;i<e;i++)t[i]=Du(r,i,e,t)},Du=(r,e,t,i)=>{let s=0,n=0,a=0;if(e!==0&&(n=r.readBits(1)),n){if(e===t){let c=B(r);a=e-(c+1)}else a=e-1;r.readBits(1),B(r);let o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);s=i[a]}else{let o=B(r),c=B(r);for(let l=0;l<o;l++)B(r),r.readBits(1);for(let l=0;l<c;l++)B(r),r.readBits(1);s=o+c}return s},Ou=(r,e)=>{let t=2,i=2,s=2,n=0,a=0,o={num:1,den:1};if(r.readBits(1)){let c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{let l=Tc[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),n=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),s=r.readBits(8))),r.readBits(1)&&(B(r),B(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(B(r),B(r),B(r),B(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&B(r),r.readBits(1)&&Uu(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=B(r),B(r),B(r),B(r),B(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:s,fullRangeFlag:n,minSpatialSegmentationIdc:a}},Uu=(r,e,t)=>{let i=!1,s=!1,n=!1;e&&(i=r.readBits(1)===1,s=r.readBits(1)===1,(i||s)&&(n=r.readBits(1)===1,n&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),n&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5)));for(let a=0;a<=t;a++){let o=r.readBits(1)===1,c=!0;o||(c=r.readBits(1)===1);let l=!1;c?B(r):l=r.readBits(1)===1;let u=1;l||(u=B(r)+1),i&&pc(r,u,n),s&&pc(r,u,n)}},pc=(r,e,t)=>{for(let i=0;i<e;i++)B(r),B(r),t&&(B(r),B(r)),r.readBits(1)},Ac=r=>{let e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(let t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(let i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let s=0;s<i.length;s++)e.push(i[s])}}return new Uint8Array(e)};var Ce;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Ce||(Ce={}));var Sc=(r,e)=>{let t=new Set,i=Ce.audAllowed;for(let n of Wi(r,e)){if(i===Ce.noMoreDataAllowed){t.add(n.offset);continue}let a=Yt(r[n.offset]);if(i===Ce.eoBitstreamAllowed&&a!==37){t.add(n.offset);continue}let o=!1;a===35?i>Ce.audAllowed?o=!0:i=Ce.beforeFirstVcl:a<=31?i>Ce.afterFirstVcl?o=!0:i=Ce.afterFirstVcl:a===36?i!==Ce.afterFirstVcl?o=!0:i=Ce.eoBitstreamAllowed:a===37?i<Ce.afterFirstVcl?o=!0:i=Ce.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>Ce.beforeFirstVcl?o=!0:i=Ce.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<Ce.afterFirstVcl&&(o=!0),o&&t.add(n.offset)}if(t.size===0)return null;let s=[];for(let n of Wi(r,e))t.has(n.offset)||s.push(r.subarray(n.offset,n.offset+n.length));return Ru(s,e)},Bs=r=>{let e=new G(r);if(e.readBits(2)!==2)return null;let i=e.readBits(1),n=(e.readBits(1)<<1)+i;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);let u=e.readBits(3),d=0,f=0;if(u!==7)if(f=e.readBits(1),n===1||n===3){let E=e.readBits(1),C=e.readBits(1);d=!E&&!C?3:E&&!C?2:1,e.skipBits(1)}else d=1;else d=3,f=1;let h=e.readBits(16),g=e.readBits(16),m=h+1,w=g+1,y=m*w,b=Q(Ct).level;for(let P of Ct)if(y<=P.maxPictureSize){b=P.level;break}return{profile:n,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},xc=function*(r){let e=new G(r),t=()=>{let i=0;for(let s=0;s<8;s++){let n=e.readAlignedByte();if(i|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);let i=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){let o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Ms=r=>{for(let{type:e,data:t}of xc(r)){if(e!==1)continue;let i=new G(t),s=i.readBits(3),n=i.readBits(1),a=i.readBits(1),o=0,c=0,l=0;if(a)o=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;let P=i.readBits(1);P&&(l=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));let E=i.readBits(5);for(let C=0;C<=E;C++){i.skipBits(12);let x=i.readBits(5);if(C===0&&(o=x),x>7){let F=i.readBits(1);C===0&&(c=F)}if(P&&i.readBits(1)){let I=l+1;i.skipBits(I),i.skipBits(I),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}let u=i.readBits(4),d=i.readBits(4),f=u+1;i.skipBits(f);let h=d+1;i.skipBits(h);let g=0;if(a?g=0:g=i.readBits(1),g&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!a){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let A=i.readBits(1);A&&(i.skipBits(1),i.skipBits(1));let P=i.readBits(1),E=0;P?E=2:E=i.readBits(1),E>0&&(i.readBits(1)||i.skipBits(1)),A&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);let m=i.readBits(1),w=8;s===2&&m?w=i.readBits(1)?12:10:s<=2&&(w=m?10:8);let y=0;s!==1&&(y=i.readBits(1));let b=1,S=1,T=0;return y||(s===0?(b=1,S=1):s===1?(b=0,S=0):w===12&&(b=i.readBits(1),b&&(S=i.readBits(1))),b&&S&&(T=i.readBits(2))),{profile:s,level:o,tier:c,bitDepth:w,monochrome:y,chromaSubsamplingX:b,chromaSubsamplingY:S,chromaSamplePosition:T}}return null},Kr=r=>{let e=L(r),t=e.getUint8(9),i=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18),o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},zu=[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],Cc=r=>{let e=r[0]>>3;return{durationInSamples:zu[e]}},Pc=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let t=r.length,i=new Uint8Array(t);for(let d=0;d<t;d++)i[d]=r[t-1-d];let s=new G(i),n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){let d=s.pos,f=s.readBits(8),h=s.readBits(16),g=s.readBits(16);if(f>63||h!==0||g!==0){s.pos=d;break}if(s.skipBits(1),a++,a>64)break;s.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;s.pos=0,s.skipBits(n);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)s.skipBits(40),u[d]=s.readBits(1);return{modeBlockflags:u}},Jt=(r,e,t)=>{switch(r){case"avc":{for(let i of ga(t,e)){let s=t[i.offset],n=qr(s);if(n>=pe.NON_IDR_SLICE&&n<=pe.SLICE_DPC)return"delta";if(n===pe.IDR)return"key";if(n===pe.SEI&&(!Ri()||No()>=144)){let a=t.subarray(i.offset,i.offset+i.length),o=Rs(a),c=1;do{let l=0;for(;;){let f=o[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){let f=o[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){let f=new G(o);f.pos=8*c;let h=B(f),g=f.readBits(1);if(h===0&&g===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let i of Wi(t,e)){let s=Yt(t[i.offset]);if(s<fe.BLA_W_LP)return"delta";if(s<=fe.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{let i=new G(t);if(i.readBits(2)!==2)return null;let s=i.readBits(1);return(i.readBits(1)<<1)+s===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(let{type:s,data:n}of xc(t))if(s===1){let a=new G(n);a.skipBits(4),i=!!a.readBits(1)}else if(s===3||s===6||s===7){if(i)return"key";let a=new G(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:le(r),p(!1)}},Zt;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Zt||(Zt={}));var qi=(r,e)=>{let t=L(r),i=0,s=t.getUint32(i,!0);i+=4;let n=he.decode(r.subarray(i,i+s));i+=s,s>0&&(e.raw??={},e.raw.vendor??=n);let a=t.getUint32(i,!0);i+=4;for(let o=0;o<a;o++){let c=t.getUint32(i,!0);i+=4;let l=he.decode(r.subarray(i,i+c));i+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),f=l.slice(u+1);switch(e.raw??={},e.raw[d]??=f,d){case"TITLE":e.title??=f;break;case"DESCRIPTION":e.description??=f;break;case"ARTIST":e.artist??=f;break;case"ALBUM":e.album??=f;break;case"ALBUMARTIST":e.albumArtist??=f;break;case"COMMENT":e.comment??=f;break;case"LYRICS":e.lyrics??=f;break;case"TRACKNUMBER":{let h=f.split("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(e.trackNumber??=g),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{let h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.tracksTotal??=h)}break;case"DISCNUMBER":{let h=f.split("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(e.discNumber??=g),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{let h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.discsTotal??=h)}break;case"DATE":{let h=new Date(f);Number.isNaN(h.getTime())||(e.date??=h)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{let h=Fi(f),g=L(h),m=g.getUint32(0,!1),w=g.getUint32(4,!1),y=String.fromCharCode(...h.subarray(8,8+w)),b=g.getUint32(8+w,!1),S=he.decode(h.subarray(12+w,12+w+b)),T=g.getUint32(w+b+28),A=h.subarray(w+b+32,w+b+32+T);e.images??=[],e.images.push({data:A,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:S||void 0})}break}}};var Gi=[2,1,2,3,3,4,4,5],Ds=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;let e=new G(r);e.skipBits(16),e.skipBits(16);let t=e.readBits(2);if(t===3)return null;let i=e.readBits(6),s=e.readBits(5);if(s>8)return null;let n=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);let o=e.readBits(1),c=Math.floor(i/2);return{fscod:t,bsid:s,bsmod:n,acmod:a,lfeon:o,bitRateCode:c}},Ec=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],_c=1536,Zf=new Uint8Array([5,4,65,67,45,51]),Jf=new Uint8Array([5,4,69,65,67,51]),ya=[1,2,3,6],Os=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;let e=new G(r);e.skipBits(16);let t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;let i=e.readBits(11),s=e.readBits(2),n=0,a;s===3?(n=e.readBits(2),a=3):a=e.readBits(2);let o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;let u=ya[a],d;return s<3?d=gr[s]/1e3:d=ma[n]/1e3,{dataRate:Math.round((i+1)*d/(u*16)),substreams:[{fscod:s,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Ic=r=>{if(r.length<2)return null;let e=new G(r),t=e.readBits(13),i=e.readBits(3),s=[];for(let n=0;n<=i&&!(Math.ceil(e.pos/8)+3>r.length);n++){let a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);let c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);let d=e.readBits(4),f=0;d>0?f=e.readBits(9):e.skipBits(1),s.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:f})}return s.length===0?null:{dataRate:t,substreams:s}},Us=r=>{let e=r.substreams[0];return p(e),e.fscod<3?gr[e.fscod]:e.fscod2!==null&&e.fscod2<3?ma[e.fscod2]:null},zs=r=>{let e=r.substreams[0];p(e);let t=Gi[e.acmod]+e.lfeon;if(e.numDepSub>0){let i=[2,2,1,1,2,2,2,1,1];for(let s=0;s<9;s++)e.chanLoc&1<<8-s&&(t+=i[s])}return t};var me=class{constructor(e){this.input=e}dispose(){}};var Ns=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){let i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},Vs=r=>{let e=L(r),t=0,i=e.getUint8(t);t+=1,t+=3;let s=Gt(r.subarray(t,t+16));t+=16;let n=null;if(i>0){let o=e.getUint32(t);if(t+=4,o>0){n=[];for(let c=0;c<o;c++)n.push(Gt(r.subarray(t,t+16))),t+=16}}let a=e.getUint32(t);return t+=4,{systemId:s,keyIds:n,data:r.slice(t,t+a)}},Ls=(r,e)=>r.systemId===e.systemId&&ps(r.data,e.data);var Je=8,vt=16,Rt=r=>{let e=R(r),t=Y(r,4),i=8;e===1&&(e=Re(r),i=16);let n=e-i;return n<0?null:{name:t,totalSize:e,headerSize:i,contentSize:n}},er=r=>Ft(r)/65536,Ws=r=>Ft(r)/1073741824,Hs=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;let i=D(r);if(e|=i&127,(i&128)===0)break}return e},et=r=>{let e=re(r);return r.skip(2),e=Math.min(e,r.remainingLength),he.decode(M(r,e))},vc=r=>{let e=Rt(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;let t=R(r);r.skip(4);let i=M(r,e.contentSize-8);switch(t){case 1:return he.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Ze(i,"image/jpeg");case 14:return new Ze(i,"image/png");case 27:return new Ze(i,"image/bmp");default:return i}};var tt=16,Bt=new Uint32Array(256),Xr=new Uint32Array(256),Qr=new Uint32Array(256),$r=new Uint32Array(256),Yr=new Uint32Array(256),Te=new Uint32Array(256),Rc=new Uint32Array(10),Fc=!1,Nu=()=>{let r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let n=0,a=1;n<256;n++)t[n]=a,e[a]=n,a=a^a<<1^(a&128?283:0);let i=(n,a)=>n&&a?t[(e[n]+e[a])%255]:0;r[0]=99;for(let n=1;n<256;n++){let a=t[255-e[n]],o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[n]=o}for(let n=0;n<256;n++){let a=r[n],o=r.indexOf(n);Bt[n]=a<<24|a<<16|a<<8|a,Te[n]=o<<24|o<<16|o<<8|o;let c=i(o,14),l=i(o,9),u=i(o,13),d=i(o,11),f=c<<24|l<<16|u<<8|d;Xr[n]=f,Qr[n]=f>>>8|f<<24,$r[n]=f>>>16|f<<16,Yr[n]=f>>>24|f<<8}let s=1;for(let n=0;n<10;n++)Rc[n]=s<<24,s=s<<1^(s&128?283:0);Fc=!0},ji=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(tt/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(tt),this.out=new Uint8Array(tt),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){p(e.byteLength===16),p(t.byteLength===16),Fc||Nu();let i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=s.getUint32(0,!1),this.iv[1]=s.getUint32(4,!1),this.iv[2]=s.getUint32(8,!1),this.iv[3]=s.getUint32(12,!1);for(let n=4;n<44;n+=4){let a=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^Bt[a>>>16&255]&4278190080^Bt[a>>>8&255]&16711680^Bt[a>>>0&255]&65280^Bt[a>>>24&255]&255^Rc[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,a=40;n<a;n+=4,a-=4)for(let o=0;o<4;o++){let c=this.roundkey[n+o];this.roundkey[n+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let n=4;n<40;n+=4)for(let a=0;a<4;a++){let o=this.roundkey[n+a];this.roundkey[n+a]=Xr[Bt[o>>>24&255]&255]^Qr[Bt[o>>>16&255]&255]^$r[Bt[o>>>8&255]&255]^Yr[Bt[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],s=this.inView.getUint32(12,!1)^this.roundkey[3],n=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,f;for(let y=1;y<10;y++){let b=y*4;l=Xr[e>>>24]^Qr[s>>>16&255]^$r[i>>>8&255]^Yr[t&255]^this.roundkey[b],u=Xr[t>>>24]^Qr[e>>>16&255]^$r[s>>>8&255]^Yr[i&255]^this.roundkey[b+1],d=Xr[i>>>24]^Qr[t>>>16&255]^$r[e>>>8&255]^Yr[s&255]^this.roundkey[b+2],f=Xr[s>>>24]^Qr[i>>>16&255]^$r[t>>>8&255]^Yr[e&255]^this.roundkey[b+3],e=l,t=u,i=d,s=f}let h=Te[e>>>24&255]&4278190080^Te[s>>>16&255]&16711680^Te[i>>>8&255]&65280^Te[t>>>0&255]&255^this.roundkey[40],g=Te[t>>>24&255]&4278190080^Te[e>>>16&255]&16711680^Te[s>>>8&255]&65280^Te[i>>>0&255]&255^this.roundkey[41],m=Te[i>>>24&255]&4278190080^Te[t>>>16&255]&16711680^Te[e>>>8&255]&65280^Te[s>>>0&255]&255^this.roundkey[42],w=Te[s>>>24&255]&4278190080^Te[i>>>16&255]&16711680^Te[t>>>8&255]&65280^Te[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,g^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,w^this.iv[3],!1),this.iv[0]=n,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}},Bc=(r,e,t)=>{let i=!1,s=0,n=2**16,a=16,o=new ji;return new ReadableStream({pull:async c=>{i||(o.init(await e()),i=!0);let l=n+a,u=r.requestSliceRange(s,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");let d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let f=d===l?d-a:d,h=M(u,f),g=new Uint8Array(f);for(let m=0;m<f;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),g.set(o.out,m);if(f<d)c.enqueue(g),s+=f;else{let m=g[f-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let w=g.subarray(0,f-m);c.enqueue(w),c.close(),t()}},cancel:()=>{t()}})};var qs=class r extends me{constructor(e){super(e),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.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(s=>s?.codec??null)));return Ns({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(i=>i.info?.type==="video"),hasAudio:this.tracks.some(i=>i.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,Je,vt);if(i instanceof Promise&&(i=await i),!i)break;let s=e,n=Rt(i);if(!n)break;if(n.name==="ftyp"||n.name==="styp"){let a=Y(i,4);this.isQuickTime=a==="qt "}else if(n.name==="moov"){let a=this.reader.requestSlice(i.filePos,n.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(let o of this.tracks){let c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+n.totalSize;break}else if(n.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let a=await this.input._initInput._getDemuxer();if(a.constructor!==r)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(let o of a.tracks){let c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(p(c.info),c.info.type==="video"&&c.info.width!==-1){let l=c;c.trackBacking=new js(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){let l=c;c.trackBacking=new Ks(l),this.tracks.push(c)}}}t=!1;break}e=s+n.totalSize}if(t){p(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);i instanceof Promise&&(i=await i),p(i);let s=R(i),n=this.reader.fileSize-s;if(n>=0&&n<=this.reader.fileSize-vt){let a=this.reader.requestSliceRange(n,Je,vt);if(a instanceof Promise&&(a=await a),a){let o=Rt(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;p(this.moovSlice);let i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ae.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){p(e.info?.type==="audio");let n=xe(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){let l=t.sampleToChunk[c],u=t.sampleToChunk[c+1],d=(u?u.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let f=0;f<d;f++){let h=l.startSampleIndex+f*l.samplesPerChunk,g=h+l.samplesPerChunk,m=H(t.sampleTimingEntries,h,C=>C.startIndex),w=t.sampleTimingEntries[m],y=H(t.sampleTimingEntries,g,C=>C.startIndex),b=t.sampleTimingEntries[y],S=w.startDecodeTimestamp+(h-w.startIndex)*w.delta,A=b.startDecodeTimestamp+(g-b.startIndex)*b.delta-S,P=Q(a);P&&P.delta===A?P.count++:a.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:S,count:1,delta:A});let E=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;o.push(E)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let n of t.sampleTimingEntries)for(let a=0;a<n.count;a++)t.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+a*n.delta,sampleIndex:n.startIndex+a});for(let n of t.sampleCompositionTimeOffsets)for(let a=0;a<n.count;a++){let o=n.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}t.presentationTimestamps.sort((n,a)=>n.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let n=0;n<t.presentationTimestamps.length;n++)t.presentationTimestampIndexMap[t.presentationTimestamps[n].sampleIndex]=n}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,Je,vt);t instanceof Promise&&(t=await t),p(t);let i=Rt(t);p(i?.name==="moof");let s=this.reader.requestSlice(e,i.totalSize);s instanceof Promise&&(s=await s),p(s),this.traverseBox(s);let n=this.lastReadFragment;p(n&&n.moofOffset===e);for(let[,a]of n.trackData){let o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){let u=o.fragmentLookupTable.find(d=>d.moofOffset===n.moofOffset);if(u)ba(a,u.timestamp);else{let d=H(c,n.moofOffset-1,f=>f.moofOffset);if(d!==-1){let f=c[d];ba(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}let l=H(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==n.moofOffset)&&c.splice(l+1,0,{moofOffset:n.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){let u=await Uc(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let d=0;d<Math.min(a.samples.length,u.length);d++){let f=u[d];a.samples[d].encryption=f}}}return n}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Je&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-Je;){let i=e.filePos,s=Rt(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=i+s.totalSize}}traverseBox(e){let t=e.filePos,i=Rt(e);if(!i)return!1;let s=e.filePos,n=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mvhd":{let a=D(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=R(e),this.movieDurationInTimescale=Re(e)):(e.skip(8),this.movieTimescale=R(e),this.movieDurationInTimescale=R(e))}break;case"trak":{let a={id:-1,demuxer:this,trackBacking:null,disposition:{...we,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Z,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(s,i.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){let o=a;a.trackBacking=new js(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let o=a;a.trackBacking=new Ks(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{let a=this.currentTrack;if(!a)break;let o=D(e),l=!!(rt(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=R(e),e.skip(4),a.durationInMovieTimescale=R(e);else if(o===1)e.skip(16),a.id=R(e),e.skip(4),a.durationInMovieTimescale=Re(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);let u=[er(e),er(e),Ws(e),er(e),er(e),Ws(e),er(e),er(e),Ws(e)],d=qt(Ii(Hu(u),90));p(d===0||d===90||d===180||d===270),a.rotation=d}break;case"elst":{let a=this.currentTrack;if(!a)break;let o=D(e);e.skip(3);let c=!1,l=0,u=R(e);for(let d=0;d<u;d++){let f=o===1?Re(e):R(e),h=o===1?Nc(e):Ft(e),g=er(e);if(f!==0){if(c){O._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){l+=f;continue}if(g!==1){O._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=h,c=!0}}}break;case"mdhd":{let a=this.currentTrack;if(!a)break;let o=D(e);e.skip(3),o===0?(e.skip(8),a.timescale=R(e),a.durationInMediaTimescale=R(e)):o===1&&(e.skip(16),a.timescale=R(e),a.durationInMediaTimescale=Re(e));let c=re(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;Fr(a.languageCode)||(a.languageCode=Z)}}break;case"hdlr":{let a=this.currentTrack;if(!a)break;e.skip(8);let o=Y(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,i.contentSize))}break;case"stsd":{let a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;let o=D(e);e.skip(3);let c=R(e);for(let l=0;l<c;l++){let u=e.filePos,d=Rt(e);if(!d)break;a.internalCodecId=d.name;let f=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=re(e),a.info.height=re(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let h=f==="encv"?a.frmaCodecString:f;a.frmaCodecString=null,h==="avc1"||h==="avc3"?(a.info.codec="avc",a.info.avcType=h==="avc1"?1:3):h==="hvc1"||h==="hev1"?a.info.codec="hevc":h==="vp08"?a.info.codec="vp8":h==="vp09"?a.info.codec="vp9":h==="av01"?a.info.codec="av1":h===null?O._warn("Unknown encrypted video codec due to missing frma box."):O._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);let h=re(e);e.skip(6);let g=re(e),m=re(e);e.skip(4);let w=R(e)/65536,y=null;o===0&&h>0&&(h===1?(e.skip(4),m=8*R(e),e.skip(8)):h===2&&(e.skip(4),w=Xs(e),g=R(e),e.skip(4),m=R(e),y=R(e),e.skip(8))),a.info.numberOfChannels=g,a.info.sampleRate=w,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));let b=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,b!=="mp4a")if(b==="opus")a.info.codec="opus",a.info.sampleRate=Pt;else if(b==="flac")a.info.codec="flac";else if(b==="ulaw")a.info.codec="ulaw";else if(b==="alaw")a.info.codec="alaw";else if(b==="ac-3")a.info.codec="ac3";else if(b==="ec-3")a.info.codec="eac3";else if(b==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(O._warn(`Unsupported sample size ${m} for codec 'twos'.`),a.info.codec=null);else if(b==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(O._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(b==="raw ")a.info.codec="pcm-u8";else if(b==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(b==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(b==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(b==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(b==="ipcm"){let S=a.info.pcmSampleSize;a.info.pcmLittleEndian?S===16?a.info.codec="pcm-s16":S===24?a.info.codec="pcm-s24":S===32?a.info.codec="pcm-s32":(O._warn(`Invalid ipcm sample size ${S}.`),a.info.codec=null):S===16?a.info.codec="pcm-s16be":S===24?a.info.codec="pcm-s24be":S===32?a.info.codec="pcm-s32be":(O._warn(`Invalid ipcm sample size ${S}.`),a.info.codec=null)}else if(b==="fpcm"){let S=a.info.pcmSampleSize;a.info.pcmLittleEndian?S===32?a.info.codec="pcm-f32":S===64?a.info.codec="pcm-f64":(O._warn(`Invalid fpcm sample size ${S}.`),a.info.codec=null):S===32?a.info.codec="pcm-f32be":S===64?a.info.codec="pcm-f64be":(O._warn(`Invalid fpcm sample size ${S}.`),a.info.codec=null)}else if(b==="lpcm"&&y!==null){let S=m+7>>3,T=!!(y&1),A=!!(y&2),P=y&4?-1:0;m>0&&m<=64&&(T?m===32&&(a.info.codec=A?"pcm-f32be":"pcm-f32"):P&1<<S-1?S===1?a.info.codec="pcm-s8":S===2?a.info.codec=A?"pcm-s16be":"pcm-s16":S===3?a.info.codec=A?"pcm-s24be":"pcm-s24":S===4&&(a.info.codec=A?"pcm-s32be":"pcm-s32"):S===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&O._warn("Unsupported PCM format.")}else b===null?O._warn("Unknown encrypted audio codec due to missing frma box."):O._warn(`Unsupported audio codec (sample entry type '${d.name}').`)}e.filePos=u+d.totalSize}}break;case"frma":{let a=this.currentTrack;if(!a)break;let c=Y(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{let a=this.currentTrack;if(!a)break;e.skip(4);let o=Y(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:O._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=D(e);e.skip(3),e.skip(1);let c=D(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=D(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=D(e),a.encryptionInfo.defaultKid=Gt(M(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){let l=D(e),u=new Uint8Array(16);u.set(M(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{let a=this.currentTrack;if(!a)break;p(a.info),a.info.codecDescription=M(e,i.contentSize)}break;case"hvcC":{let a=this.currentTrack;if(!a)break;p(a.info),a.info.codecDescription=M(e,i.contentSize)}break;case"vpcC":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(4);let o=D(e),c=D(e),l=D(e),u=l>>4,d=l>>1&7,f=l&1,h=D(e),g=D(e),m=D(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:g,matrixCoefficients:m}}break;case"av1C":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(1);let o=D(e),c=o>>5,l=o&31,u=D(e),d=u>>7,f=u>>6&1,h=u>>5&1,g=u>>4&1,m=u>>3&1,w=u>>2&1,y=u&3,b=c===2&&f?h?12:10:f?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:g,chromaSubsamplingX:m,chromaSubsamplingY:w,chromaSamplePosition:y}}break;case"colr":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="video");let o=Y(e,4);if(o!=="nclx"&&o!=="nclc")break;let c=re(e),l=re(e),u=re(e),d;o==="nclx"&&(d=!!(D(e)&128)),a.info.colorSpace={primaries:or[c],transfer:cr[l],matrix:lr[u],fullRange:d}}break;case"pasp":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="video");let o=R(e),c=R(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"esds":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);let o=D(e);p(o===3),Hs(e),e.skip(2);let c=D(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){let w=D(e);e.skip(w)}d&&e.skip(2);let f=D(e);p(f===4);let h=Hs(e),g=e.filePos,m=D(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":O._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),h>e.filePos-g){let w=D(e);p(w===5);let y=Hs(e);if(a.info.codecDescription=M(e,y),a.info.codec==="aac"){let b=Dr(a.info.codecDescription);b.numberOfChannels!==null&&(a.info.numberOfChannels=b.numberOfChannels),b.sampleRate!==null&&(a.info.sampleRate=b.sampleRate)}}}break;case"enda":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(re(e)&255)}break;case"pcmC":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);let o=D(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=D(e)}break;case"dOps":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(1);let o=D(e),c=re(e),l=R(e),u=Ki(e),d=D(e),f;d!==0?f=M(e,2+o):f=new Uint8Array(0);let h=new Uint8Array(19+f.byteLength),g=new DataView(h.buffer);g.setUint32(0,1332770163,!1),g.setUint32(4,1214603620,!1),g.setUint8(8,1),g.setUint8(9,o),g.setUint16(10,c,!0),g.setUint32(12,l,!0),g.setInt16(16,u,!0),g.setUint8(18,d),h.set(f,19),a.info.codecDescription=h,a.info.numberOfChannels=o}break;case"dfLa":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);let o=127,c=128,l=e.filePos;for(;e.filePos<n;){let g=D(e),m=rt(e);if((g&o)===Zt.STREAMINFO){e.skip(10);let y=R(e),b=y>>>12,S=(y>>9&7)+1;a.info.sampleRate=b,a.info.numberOfChannels=S,e.skip(20)}else e.skip(m);if(g&c)break}let u=e.filePos;e.filePos=l;let d=M(e,u-l),f=new Uint8Array(4+d.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(d,4),a.info.codecDescription=f}break;case"dac3":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");let o=M(e,3),c=new G(o),l=c.readBits(2);c.skipBits(8);let u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=gr[l]),a.info.numberOfChannels=Gi[u]+d}break;case"dec3":{let a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");let o=M(e,i.contentSize),c=Ic(o);if(!c){O._warn("Invalid dec3 box contents, ignoring.");break}let l=Us(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=zs(c)}break;case"stts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e),c=0,l=0;for(let u=0;u<o;u++){let d=R(e),f=R(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:d,delta:f}),c+=d,l+=d*f}}break;case"ctts":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e),c=0;for(let l=0;l<o;l++){let u=R(e),d=Ft(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e),c=R(e);if(o===0)for(let l=0;l<c;l++){let u=R(e);a.sampleTable.sampleSizes.push(u)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);let o=D(e),c=R(e),l=M(e,Math.ceil(c*o/8)),u=new G(l);for(let d=0;d<c;d++){let f=u.readBits(o);a.sampleTable.sampleSizes.push(f)}}break;case"stss":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];let o=R(e);for(let c=0;c<o;c++){let l=R(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e);for(let l=0;l<o;l++){let u=R(e)-1,d=R(e),f=R(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:u,samplesPerChunk:d,sampleDescriptionIndex:f})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){let d=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=d*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e);for(let c=0;c<o;c++){let l=R(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);let o=R(e);for(let c=0;c<o;c++){let l=Re(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mehd":{let a=D(e);e.skip(3);let o=a===1?Re(e):R(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);let a=R(e),o=R(e),c=R(e),l=R(e),u=R(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:u})}break;case"tfra":{let a=D(e);e.skip(3);let o=R(e),c=this.tracks.find(b=>b.id===o);if(!c)break;let l=R(e),u=(l&48)>>4,d=(l&12)>>2,f=l&3,h=[D,re,rt,R],g=h[u],m=h[d],w=h[f],y=R(e);for(let b=0;b<y;b++){let S=a===1?Re(e):R(e),T=a===1?Re(e):R(e);g(e),m(e),w(e),c.fragmentLookupTable.push({timestamp:S,moofOffset:T})}c.fragmentLookupTable.sort((b,S)=>b.timestamp-S.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){let S=c.fragmentLookupTable[b],T=c.fragmentLookupTable[b+1];S.timestamp===T.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(s,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(p(this.currentFragment),this.readContiguousBoxes(e.slice(s,i.contentSize)),this.currentTrack){let a=this.currentFragment.trackData.get(this.currentTrack.id);e:if(a){if(a.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}a.presentationTimestamps=a.samples.map((u,d)=>({presentationTimestamp:u.presentationTimestamp,sampleIndex:d})).sort((u,d)=>u.presentationTimestamp-d.presentationTimestamp);for(let u=0;u<a.presentationTimestamps.length;u++){let d=a.presentationTimestamps[u],f=a.samples[d.sampleIndex];if(a.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(a.firstKeyFrameTimestamp=f.presentationTimestamp),u<a.presentationTimestamps.length-1){let g=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;f.duration=g}}let o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[Q(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;let{currentFragmentState:l}=this.currentTrack;p(l),l.startTimestamp!==null&&(ba(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let a=Vs(M(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{p(this.currentFragment),e.skip(1);let a=rt(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),g=R(e),m=this.tracks.find(y=>y.id===g);if(!m)break;let w=this.fragmentTrackDefaults.find(y=>y.trackId===g);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:w?.defaultSampleDescriptionIndex??null,defaultSampleDuration:w?.defaultSampleDuration??null,defaultSampleSize:w?.defaultSampleSize??null,defaultSampleFlags:w?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Re(e):h&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=R(e)),l&&(m.currentFragmentState.defaultSampleDuration=R(e)),u&&(m.currentFragmentState.defaultSampleSize=R(e)),d&&(m.currentFragmentState.defaultSampleFlags=R(e)),f&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let a=this.currentTrack;if(!a)break;p(a.currentFragmentState);let o=D(e);e.skip(3);let c=o===0?R(e):Re(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{let a=this.currentTrack;if(!a)break;p(this.currentFragment),p(a.currentFragmentState);let o=D(e),c=rt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),g=!!(c&2048),m=R(e),w=null;l&&(w=Ft(e));let y=null;u&&(y=R(e));let b;this.currentFragment.trackData.has(a.id)?(b=this.currentFragment.trackData.get(a.id),w!==null&&(b.currentOffset=a.currentFragmentState.baseDataOffset+w)):(b={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(w??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,b));for(let S=0;S<m;S++){let T;d?T=R(e):(p(a.currentFragmentState.defaultSampleDuration!==null),T=a.currentFragmentState.defaultSampleDuration);let A;f?A=R(e):(p(a.currentFragmentState.defaultSampleSize!==null),A=a.currentFragmentState.defaultSampleSize);let P;h?P=R(e):(p(a.currentFragmentState.defaultSampleFlags!==null),P=a.currentFragmentState.defaultSampleFlags),S===0&&y!==null&&(P=y);let E=0;g&&(o===0?E=R(e):E=Ft(e));let C=!(P&65536);b.samples.push({presentationTimestamp:b.currentTimestamp+E,duration:T,byteOffset:b.currentOffset,byteSize:A,isKeyFrame:C,encryption:null}),b.currentOffset+=A,b.currentTimestamp+=T}this.currentFragment.implicitBaseDataOffset=b.currentOffset}break;case"saiz":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),rt(e)&1){let f=Y(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}let c=D(e),l=R(e),u=null;c===0&&l>0&&(u=M(e,l));let d=Dc(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;let o=D(e);if(rt(e)&1){let f=Y(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}let l=R(e);if(l===0)break;l>1&&O._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?R(e):Number(Re(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);let d=Dc(a);d.offset=u}break;case"senc":{let a=this.currentTrack;if(!a||!a.encryptionInfo)break;p(this.currentFragment);let o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);let l=!!(rt(e)&2),u=R(e),d=a.encryptionInfo.defaultPerSampleIvSize;p(d!==null);for(let f=0;f<Math.min(u,o.samples.length);f++){let h=new Uint8Array(16);d>0?h.set(M(e,d),0):h.set(a.encryptionInfo.defaultConstantIv,0);let g=null;if(l){let w=re(e);g=[];for(let y=0;y<w;y++){let b=re(e),S=R(e);g.push({clearLen:b,protectedLen:S})}}let m=o.samples[f];m.encryption={iv:h,subsamples:g}}}break;case"udta":{let a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(let{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){let l=c.filePos;this.metadataTags.raw??={},o.name[0]==="\xA9"?this.metadataTags.raw[o.name]??=et(c):this.metadataTags.raw[o.name]??=M(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=he.decode(M(c,o.contentSize)):this.metadataTags.title??=et(c);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=et(c));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=et(c));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=et(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=et(c));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=et(c));break;case"\xA9day":if(!this.currentTrack){let l=new Date(et(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=et(c));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=et(c));break}}}break;case"meta":{if(this.currentTrack)break;let o=R(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(s,i.contentSize)):this.readContiguousBoxes(e.slice(s+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let a=R(e);for(let o=0;o<a;o++){let c=R(e);e.skip(4);let l=he.decode(M(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(let{boxInfo:o,slice:c}of a){let l=o.name,u=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(u)&&(l=this.currentMetadataKeys.get(u));let d=vc(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=d,l){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof d=="string"&&(this.metadataTags.title??=d);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof d=="string"&&(this.metadataTags.description??=d);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof d=="string"&&(this.metadataTags.artist??=d);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof d=="string"&&(this.metadataTags.album??=d);break;case"aART":case"album_artist":typeof d=="string"&&(this.metadataTags.albumArtist??=d);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof d=="string"&&(this.metadataTags.comment??=d);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof d=="string"&&(this.metadataTags.genre??=d);break;case"\xA9lyr":case"lyrics":typeof d=="string"&&(this.metadataTags.lyrics??=d);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof d=="string"){let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Ze?(this.metadataTags.images??=[],this.metadataTags.images.push({data:d.data,kind:"coverFront",mimeType:d.mimeType})):d instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:d,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof d=="string"){let f=d.split("/"),h=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){let f=L(d),h=f.getUint16(2,!1),g=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),g>0&&(this.metadataTags.tracksTotal??=g)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){let f=L(d),h=f.getUint16(2,!1),g=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),g>0&&(this.metadataTags.discsTotal??=g)}break}}}break}return e.filePos=n,!0}},Gs=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),i=0;for(let s of e.tracks)if(s.trackBacking.getType()===t&&i++,s===this.internalTrack)break;return i}getCodec(){throw new 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}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(p(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return St(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=ka(s,i),a=await this.fetchPacketForSampleIndex(n,t);return!Mc(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=H(c.presentationTimestamps,i,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextPacket(e,t){let i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){let a=n.trackData.get(this.internalTrack.id);if(s.sampleIndex+1<a.samples.length)return{sampleIndex:s.sampleIndex+1,correctSampleFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Vu(s,i),a=await this.fetchPacketForSampleIndex(n,t);return!Mc(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let l=Rr(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=i),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextKeyPacket(e,t){let i=this.packetToSampleIndex.get(e);if(i!==void 0){let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Wu(n,i);return this.fetchPacketForSampleIndex(a,t)}let s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){let o=n.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let o=a.samples.findIndex(c=>c.isKeyFrame);return p(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Lu(i,e);if(!s)return null;let n;if(t.metadataOnly)n=de;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(n=M(l,s.sampleSize),this.internalTrack.encryptionAuxInfo){p(this.internalTrack.encryptionInfo);let u=await Uc(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(n=await Oc(this.internalTrack,u[e],n,null))}}let a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,c=new X(n,s.isKeyFrame?"key":"delta",a,o,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).samples[t];p(n);let a;if(i.metadataOnly)a=de;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;a=M(u,n.byteSize),n.encryption&&(a=await Oc(this.internalTrack,n.encryption,a,e))}let o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=new X(a,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,i,s,n){let a=this.internalTrack.demuxer,o=null,c=null,l=-1;if(e){let{sampleIndex:w,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,w,n);w!==-1&&(c=e,l=w)}let u=H(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=H(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,g=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null,m;for(e?g===null||e.moofOffset>=g?(m=e.moofOffset+e.moofSize,o=e):m=g:m=g??0;;){if(o){let S=o.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>s)break}let w=a.reader.requestSliceRange(m,Je,vt);if(w instanceof Promise&&(w=await w),!w)break;let y=m,b=Rt(w);if(!b)break;if(b.name==="moof"){o=await a.readFragment(y);let{sampleIndex:S,correctSampleFound:T}=t(o);if(T)return this.fetchPacketInFragment(o,S,n);S!==-1&&(c=o,l=S)}m=y+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let w=this.internalTrack.fragmentLookupTable[u-1];p(!w||w.timestamp<d.timestamp);let y=w?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,s,n)}return c?this.fetchPacketInFragment(c,l,n):null}},js=class extends Gs{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Bs(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Ms(t.data)}let e={codec:Ur(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Ks=class extends Gs{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:zr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},ka=(r,e)=>{if(r.presentationTimestamps){let t=H(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{let t=H(r.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;let i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Vu=(r,e)=>{if(!r.keySampleIndices)return ka(r,e);if(r.presentationTimestamps){let t=H(r.presentationTimestamps,e,i=>i.presentationTimestamp);if(t===-1)return-1;for(let i=t;i>=0;i--){let s=r.presentationTimestamps[i].sampleIndex;if(At(r.keySampleIndices,s,a=>a)!==-1)return s}return-1}else{let t=ka(r,e),i=H(r.keySampleIndices,t,s=>s);return r.keySampleIndices[i]??-1}},Lu=(r,e)=>{let t=H(r.sampleTimingEntries,e,y=>y.startIndex),i=r.sampleTimingEntries[t];if(!i||i.startIndex+i.count<=e)return null;let n=i.startDecodeTimestamp+(e-i.startIndex)*i.delta,a=H(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(n+=o.offset);let c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=H(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];p(u);let d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=r.chunkOffsets[d],h=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,g=0,m=f;if(r.sampleSizes.length===1)m+=c*(e-h),g+=c*u.samplesPerChunk;else for(let y=h;y<h+u.samplesPerChunk;y++){let b=r.sampleSizes[y];y<e&&(m+=b),g+=b}let w=i.delta;if(r.presentationTimestamps){let y=r.presentationTimestampIndexMap[e];p(y!==void 0),y<r.presentationTimestamps.length-1&&(w=r.presentationTimestamps[y+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:w,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:g,isKeyFrame:r.keySampleIndices?At(r.keySampleIndices,e,y=>y)!==-1:!0}},Wu=(r,e)=>{if(!r.keySampleIndices)return e+1;let t=H(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},ba=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(let t of r.samples)t.presentationTimestamp+=e;for(let t of r.presentationTimestamps)t.presentationTimestamp+=e},Hu=r=>{let[e,t]=r,i=Math.atan2(t,e);return Number.isFinite(i)?i*(180/Math.PI):0},Mc=r=>r.sampleSizes.length===0,Dc=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Uc=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let i=0;if(t.defaultSampleInfoSize>0)i=t.defaultSampleInfoSize*t.sampleCount;else{p(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let s=r.requestSlice(t.offset,i);if(s instanceof Promise&&(s=await s),!s)throw new Error("Failed to read auxiliary encryption info.");let n=e.defaultPerSampleIvSize;p(n!==null);let a=[];for(let o=0;o<t.sampleCount;o++){let c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);n>0?l.set(M(s,n),0):l.set(e.defaultConstantIv,0);let u=null;if(c>n){let d=re(s);u=[];for(let f=0;f<d;f++){let h=re(s),g=R(s);u.push({clearLen:h,protectedLen:g})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},Oc=async(r,e,t,i)=>{p(r.encryptionInfo);let s=r.encryptionInfo;p(s.defaultKid!==null);let n=s.defaultKid,a,o=r.demuxer.decryptionKeyCache.get(n);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=r.demuxer.psshBoxes;if(i){l=[...l,...i.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(n));for(let d=0;d<l.length-1;d++)for(let f=d+1;f<l.length;f++)Ls(l[d],l[f])&&(l.splice(f,1),f--)}let u=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:n,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&Ro.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:Fo(u)})();r.demuxer.decryptionKeyCache.set(n,c),a=await c}return s.scheme==="cenc"||s.scheme==="cens"?qu(a,s,e,t):Gu(a,s,e,t)},qu=async(r,e,t,i)=>{let s=new Uint8Array(16);s.set(t.iv,0);let n=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async g=>{let m=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,g);return new Uint8Array(m)};if(!t.subsamples)return a(i);p(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);let o=zc(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock),c=0;for(let g of o)for(let m of g.perSubsample)c+=m.length;let l=new Uint8Array(c),u=0;for(let g of o)for(let m of g.perSubsample)l.set(i.subarray(m.offset,m.offset+m.length),u),u+=m.length;let d=await a(l),f=new Uint8Array(i),h=0;for(let g of o)for(let m of g.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},Gu=(r,e,t,i)=>{let s=new ji;s.init({key:r,iv:t.iv});let n=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(p(n!==null&&a!==null),!t.subsamples){let u=new Uint8Array(i),d=Math.floor(i.length/16);for(let f=0;f<d;f++){let h=f*16;s.in.set(i.subarray(h,h+16)),s.decrypt(),u.set(s.out,h)}return u}if(n===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(i),c=zc(t.subsamples,n,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(let u of c){s.iv[0]=l.getUint32(0,!1),s.iv[1]=l.getUint32(4,!1),s.iv[2]=l.getUint32(8,!1),s.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let f=d.length/16;for(let h=0;h<f;h++){let g=d.offset+h*16;s.in.set(i.subarray(g,g+16)),s.decrypt(),o.set(s.out,g)}}}return o},zc=(r,e,t)=>{let i=[],s=e!==0||t!==0,n=0;for(let a of r){n+=a.clearLen;let o=[];if(!s)a.protectedLen>0&&o.push({offset:n,length:a.protectedLen}),n+=a.protectedLen;else{let c=a.protectedLen,l=n;for(;c>0&&!(c<16*e);){let u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;let d=Math.min(16*t,c);l+=d,c-=d}n+=a.protectedLen}i.push({perSubsample:o})}return i};var Zr=class{constructor(e){this.value=e}},Jr=class{constructor(e){this.value=e}},Xi=class{constructor(e){this.value=e}},it=class{constructor(e){this.value=e}},k;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(k||(k={}));var ju=[k.EBML,k.Segment],ei=[k.SeekHead,k.Info,k.Cluster,k.Tracks,k.Cues,k.Attachments,k.Chapters,k.Tags],Qi=[...ju,...ei],Vc=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,Lc=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,Wc=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-(1<<20)&&r<1<<20?3:r>=-(1<<27)&&r<1<<27?4:r>=-(2**34)&&r<2**34?5:6,Ku=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)},Qs=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=Vc(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=Lc(e)){let i=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(i++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=Wc(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=Ku(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);let s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){let n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,i),this.writer.seek(a)}}else if(typeof e.data=="number"){let t=e.size??Vc(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){let t=e.size??Lc(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof Zr)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Jr)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Xi){let t=e.size??Wc(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof it){let t=te.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else le(e.data)}},Ta=8,Fe=2,st=2*Ta,Aa=r=>{if(r.remainingLength<1)return null;let e=D(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},ti=r=>{if(r.remainingLength<1)return null;let e=D(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let s=e&i-1;for(let n=1;n<t;n++)s*=256,s+=D(r);return s},j=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=D(r);return t},Hc=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(D(r));return t};var $s=r=>{let e=Aa(r);return e===null||r.remainingLength<e?null:j(r,e)},Sa=r=>{if(r.remainingLength<1)return null;if(D(r)===255)return;r.skip(-1);let t=ti(r);if(t===null)return null;if(t!==72057594037927940)return t},nt=r=>{p(r.remainingLength>=Fe);let e=$s(r);if(e===null)return null;let t=Sa(r);return t===null?null:{id:e,size:t}},tr=(r,e)=>{let t=M(r,e),i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},ri=(r,e)=>{let t=M(r,e),i=0;for(;i<e&&t[i]!==0;)i+=1;return he.decode(t.subarray(0,i))},Ys=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?qc(r):Xs(r)},Zs=async(r,e,t,i)=>{let s=new Set(t),n=e;for(;i===null||n<i;){let a=r.requestSliceRange(n,Fe,st);if(a instanceof Promise&&(a=await a),!a)break;let o=nt(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};Mt(o.size),n=a.filePos+o.size}return{pos:i!==null&&i>n?i:n,found:!1}},xa=async(r,e,t,i)=>{let n=new Set(t),a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(o instanceof Promise&&(o=await o),!o||o.length<Ta)break;for(let c=0;c<o.length-Ta;c++){o.filePos=a;let l=$s(o);if(l!==null&&n.has(l))return a;a++}}return null},Pe={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",ac3:"A_AC3",eac3:"A_EAC3","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 Mt(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var Js=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){let i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};var Dt;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Dt||(Dt={}));var en;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(en||(en={}));var $i;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})($i||($i={}));var Ca=[{id:k.SeekHead,flag:"seekHeadSeen"},{id:k.Info,flag:"infoSeen"},{id:k.Tracks,flag:"tracksSeen"},{id:k.Cues,flag:"cuesSeen"}],Gc=10*2**20,tn=class extends me{constructor(e){super(e),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=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(s=>s?.codec??null)));return Js({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Fe,st);if(t instanceof Promise&&(t=await t),!t)break;let i=nt(t);if(!i)break;let s=i.id,n=i.size,a=t.filePos;if(s===k.EBML){Mt(n);let o=this.reader.requestSlice(a,n);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===k.Segment){if(await this.readSegment(a,n),n===void 0||this.reader.fileSize===null)break}else if(s===k.Cluster){if(this.reader.fileSize===null)break;n===void 0&&(n=(await Zs(this.reader,a,Qi,this.reader.fileSize)).pos-a);let o=Q(this.segments);o&&(o.elementEndPos=a+n)}Mt(n),e=a+n}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,Fe,st);if(o instanceof Promise&&(o=await o),!o)break;let c=i,l=nt(o);if(!l||!ei.includes(l.id)&&l.id!==k.Void){let g=await xa(this.reader,c,ei,Math.min(this.currentSegment.elementEndPos??1/0,c+Gc));if(g){i=g;continue}else break}let{id:u,size:d}=l,f=o.filePos,h=Ca.findIndex(g=>g.id===u);if(h!==-1){let g=Ca[h].flag;this.currentSegment[g]=!0,Mt(d);let m=this.reader.requestSlice(f,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===k.Tags||u===k.Attachments){u===k.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Mt(d);let g=this.reader.requestSlice(f,d);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(u===k.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(let o of this.currentSegment.seekEntries){let c=Ca.find(g=>g.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Fe,st);if(l instanceof Promise&&(l=await l),!l)continue;let u=nt(l);if(!u)continue;let{id:d,size:f}=u;if(d!==c.id)continue;Mt(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(l.filePos,f);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);let s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(let o of this.currentSegment.cuePoints){let c=s.get(o.trackId);c&&c.cuePoints.push(o)}for(let o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){let l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let n=null,a=-1/0;for(let o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(let o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,Fe,st);i instanceof Promise&&(i=await i),p(i);let s=e,n=nt(i);p(n);let a=n.id;p(a===k.Cluster);let o=n.size,c=i.filePos;o===void 0&&(o=(await Zs(this.reader,c,Qi,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);let u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){let d=this.readContiguousElements(l,Qi);u.elementEndPos=d}for(let[,d]of u.trackData){let f=d.track;p(d.blocks.length>0);let h=!1;for(let y=0;y<d.blocks.length;y++){let b=d.blocks[y];b.timestamp+=u.timestamp,h||=b.lacing!==Dt.None}d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){let b=d.presentationTimestamps[y],S=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&S.isKeyFrame&&(d.firstKeyFrameTimestamp=S.timestamp),y<d.presentationTimestamps.length-1){let T=d.presentationTimestamps[y+1];S.duration=T.timestamp-S.timestamp}else S.duration===0&&f.defaultDuration!=null&&S.lacing===Dt.None&&(S.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));let g=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[Q(d.presentationTimestamps).blockIndex];d.startTimestamp=g.timestamp,d.endTimestamp=m.timestamp+m.duration;let w=H(f.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(w===-1||f.clusterPositionCache[w].elementStartPos!==s)&&f.clusterPositionCache.splice(w+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){let s=e.segment.tracks.find(n=>n.id===t);if(!s)return null;i={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.lacing===Dt.None)continue;s.decoded||(s.data=this.decodeBlockData(t,s.data),s.decoded=!0);let n=ye.tempFromBytes(s.data),a=[],o=D(n)+1;switch(s.lacing){case Dt.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;n.bufferPos<n.length;){let f=D(n);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(n.length-(n.bufferPos+l))}break;case Dt.FixedSize:{let l=n.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case Dt.Ebml:{let l=ti(n);p(l!==null);let u=l;a.push(u);let d=u;for(let f=1;f<o-1;f++){let h=n.bufferPos,g=ti(n);p(g!==null);let m=g,y=(1<<(n.bufferPos-h)*7-1)-1,b=m-y;u+=b,a.push(u),d+=u}a.push(n.length-(n.bufferPos+d))}break;default:p(!1)}p(a.length===o),e.splice(i,1);let c=s.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){let u=a[l],d=M(n,u),f=s.timestamp+c*l/o,h=c/o;e.splice(i+l,0,{timestamp:f,duration:h,isKeyFrame:s.isKeyFrame,data:d,lacing:Dt.None,decoded:!0,mainAdditional:s.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===k.Tags&&!e.tagsSeen)){if(!(t.id===k.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Fe,st);if(i instanceof Promise&&(i=await i),!i)continue;let s=nt(i);if(!s||s.id!==t.id)continue;let{size:n}=s;Mt(n),p(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,n);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===k.Tags?e.tagsSeen=!0:t.id===k.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Fe;){let i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){let i=nt(e);if(!i||t&&t.includes(i.id))return!1;let{id:s,size:n}=i,a=e.filePos;switch(Mt(n),s){case k.DocType:this.isWebM=tr(e,n)==="webm";break;case k.Seek:{if(!this.currentSegment)break;let o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,n)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case k.SeekID:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=j(e,n)}break;case k.SeekPosition:{let o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=j(e,n)}break;case k.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=j(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case k.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Ys(e,n)}break;case k.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...we,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==en.Block||o.data.algorithm!==$i.HeaderStripping)&&(O._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}this.currentTrack.codecId===Pe.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Pe.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Pe.vp8?this.currentTrack.info.codec="vp8":c===Pe.vp9?this.currentTrack.info.codec="vp9":c===Pe.av1&&(this.currentTrack.info.codec="av1");let l=this.currentTrack;this.currentTrack.trackBacking=new Pa(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===Pe.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Pe.mp3?this.currentTrack.info.codec="mp3":c===Pe.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Pt):c===Pe.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Pe.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Pe.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===Pe.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack;this.currentTrack.trackBacking=new Ea(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case k.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=j(e,n)}break;case k.TrackType:{if(!this.currentTrack)break;let o=j(e,n);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case k.FlagEnabled:{if(!this.currentTrack)break;j(e,n)||(this.currentTrack=null)}break;case k.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!j(e,n)}break;case k.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!j(e,n)}break;case k.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!j(e,n)}break;case k.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!j(e,n)}break;case k.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!j(e,n)}break;case k.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!j(e,n)}break;case k.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=tr(e,n)}break;case k.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=M(e,n)}break;case k.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=j(e,n)}break;case k.Name:{if(!this.currentTrack)break;this.currentTrack.name=ri(e,n)}break;case k.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=tr(e,n),Fr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Z)}break;case k.LanguageBCP47:{if(!this.currentTrack)break;let c=tr(e,n).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Z,this.currentTrack.hasLanguageBcp47=!0}break;case k.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case k.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=j(e,n)}break;case k.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=j(e,n)}break;case k.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=j(e,n)}break;case k.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=j(e,n)}break;case k.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=j(e,n)}break;case k.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=j(e,n)===1}break;case k.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,n))}break;case k.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=j(e,n),c=lr[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case k.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=j(e,n)===2}break;case k.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=j(e,n),c=cr[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case k.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let o=j(e,n),c=or[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case k.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case k.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let c=-Ys(e,n);try{this.currentTrack.info.rotation=qt(c)}catch{}}break;case k.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case k.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Ys(e,n)}break;case k.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=j(e,n)}break;case k.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=j(e,n)}break;case k.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case k.CueTime:this.currentCueTime=j(e,n);break;case k.CueTrackPositions:{if(this.currentCueTime===null)break;p(this.currentSegment);let o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,n)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case k.CueTrack:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=j(e,n)}break;case k.CueClusterPosition:{let o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;p(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+j(e,n)}break;case k.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=j(e,n)}break;case k.SimpleBlock:{if(!this.currentCluster)break;let o=ti(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Ki(e),u=D(e),d=u>>1&3,f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);let h=M(e,n-(e.filePos-a)),g=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:h,lacing:d,decoded:!g,mainAdditional:null})}break;case k.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case k.Block:{if(!this.currentCluster)break;let o=ti(e);if(o===null)break;let c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;let l=Ki(e),d=D(e)>>1&3,f=M(e,n-(e.filePos-a)),h=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:d,decoded:!h,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case k.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case k.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case k.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=M(e,n)}break;case k.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=j(e,n)}break;case k.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=j(e,n)}break;case k.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case k.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case k.Targets:this.readContiguousElements(e.slice(a,n));break;case k.TargetTypeValue:j(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case k.TagTrackUID:case k.TagEditionUID:case k.TagChapterUID:case k.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case k.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case k.TagName:this.currentSimpleTagName=ri(e,n);break;case k.TagString:{if(!this.currentSimpleTagName)break;let o=ri(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case k.TagBinary:{if(!this.currentSimpleTagName)break;let o=M(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case k.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));let o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new mr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let c=this.currentAttachedFile.fileName,l="unknown";if(c){let u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case k.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Hc(e,n)}break;case k.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ri(e,n)}break;case k.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=tr(e,n)}break;case k.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=M(e,n)}break;case k.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ri(e,n)}break;case k.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case k.ContentEncoding:this.currentDecodingInstruction={order:0,scope:en.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case k.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=j(e,n)}break;case k.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=j(e,n)}break;case k.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:$i.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case k.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=j(e,n)}break;case k.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=M(e,n)}break;case k.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){p(e.decodingInstructions.length>0);let i=t;for(let s of e.decodingInstructions)switch(p(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case $i.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){let n=s.data.settings,a=new Uint8Array(n.length+i.length);a.set(n,0),a.set(i,n.length),i=a}break;default:}break;default:}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{let s=new Date(t);Number.isNaN(s.getTime())||(i.date??=s)}break;case"track_number":case"part_number":{let s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.trackNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{let s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.discNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}},rn=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),i=0;for(let s of e.segments)for(let n of s.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return St(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{let n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};let a=H(n.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){let n=s.trackData.get(this.internalTrack.id);if(i.blockIndex+1<n.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{let n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};let a=Rr(n.presentationTimestamps,l=>n.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextKeyPacket(e,t){let i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){let a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{let n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let a=n.blocks.findIndex(o=>o.isKeyFrame);return p(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(t===-1)return null;let n=e.trackData.get(this.internalTrack.id).blocks[t];p(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);let a=i.metadataOnly?de:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?de:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);let u=new X(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,i,s,n){let{demuxer:a,segment:o}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:y,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,n);y!==-1&&(l=e,u=y)}let d=H(this.internalTrack.cuePoints,i,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=H(this.internalTrack.clusterPositionCache,i,y=>y.startTimestamp),g=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(f?.clusterPosition??0,g?.elementStartPos??0)||null,w;for(e?m===null||e.elementStartPos>=m?(w=e.elementEndPos,c=e):w=m:w=m??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-Fe;){if(c){let C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>s)break}let y=a.reader.requestSliceRange(w,Fe,st);if(y instanceof Promise&&(y=await y),!y)break;let b=w,S=nt(y);if(!S||!ei.includes(S.id)&&S.id!==k.Void){let C=await xa(a.reader,b,ei,Math.min(o.elementEndPos??1/0,b+Gc));if(C){w=C;continue}else break}let T=S.id,A=S.size,P=y.filePos;if(T===k.Cluster){c=await a.readCluster(b,o),A=c.elementEndPos-P;let{blockIndex:C,correctBlockFound:x}=t(c);if(x)return this.fetchPacketInCluster(c,C,n);C!==-1&&(l=c,u=C)}A===void 0&&(p(T!==k.Cluster),A=(await Zs(a.reader,P,Qi,o.elementEndPos)).pos-P);let E=P+A;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(E,Fe,st);if(C instanceof Promise&&(C=await C),!C)break;if($s(C)===k.Segment){o.elementEndPos=E;break}}w=E}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let y=this.internalTrack.cuePoints[d-1];p(!y||y.time<f.time);let b=y?.time??-1/0;return this.performClusterLookup(null,t,b,s,n)}return l?this.fetchPacketInCluster(l,u,n):null}},Pa=class extends rn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(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)&&(e=await this.getFirstPacket({}));let i={codec:Ur({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Gr(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?jr(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Bs(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Ms(e.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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})():null}},Ea=class extends rn{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:zr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};var Yi=async(r,e,t,i=null)=>{let n=e;for(;t===null||n<t;){let a=t!==null?Math.min(65536,t-n):65536,o=r.requestSliceRange(n,4,a);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=R(o),u=r.fileSize!==null?r.fileSize-n:null,d=pr(l,u);if(d.header&&(!i||d.header.sampleRate===i.sampleRate&&d.header.mpegVersionId===i.mpegVersionId&&d.header.layer===i.layer&&$t(d.header.channel)===$t(i.channel)))return{header:d.header,startPos:n};o.filePos=c+d.bytesAdvanced,n=o.filePos}}return null};var sn=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new _e,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new _a(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Ae);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=Be(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=await Yi(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let i=Qt(t.mpegVersionId,t.channel),s=this.reader.requestSlice(e.startPos+i,4);if(s instanceof Promise&&(s=await s),s){let o=R(s);if(o===Xt||o===Wr){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+i+4,12);if(l instanceof Promise&&(l=await l),l){let u=M(l,12),d=L(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&It.FrameCount?d.getUint32(4,!1):null,fileSize:f&It.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,i=!1;for(;;){let s=this.reader.requestSlice(t,Ae);if(s instanceof Promise&&(s=await s),!s)break;let n=Be(s);if(!n)break;i=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(a instanceof Promise&&(a=await a),!a)break;rr(a,n,this.metadataTags),t=s.filePos+n.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=Zi){let s=this.reader.requestSlice(this.reader.fileSize-Zi,Zi);s instanceof Promise&&(s=await s),p(s),Y(s,3)==="TAG"&&jc(s,this.metadataTags)}return this.metadataTags}finally{e()}}},_a=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(p(e.firstFrameHeader!==null),p(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=fc(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),i=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(i)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Z}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.firstFrameHeader),$t(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...we}}async getDecoderConfig(){return p(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:$t(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=de;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=M(n,i.dataSize)}return new X(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let s=At(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=H(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var Ia=1399285583,Xu=79764919,Kc=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Xu:e<<1;Kc[r]=e>>>0&4294967295}var Xc=r=>{let e=L(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let s=0;s<r.length;s++){let n=r[s];i=(i<<8^Kc[i>>>24^n])>>>0}return e.setUint32(22,t,!0),i},Qc=(r,e,t)=>{let i=0,s=null;if(r.length>0)if(e.codec==="vorbis"){p(e.vorbisInfo);let n=e.vorbisInfo.modeBlockflags.length,o=(1<<Uo(n-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t,u=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,f=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[f]}i=l!==null?l+s>>2:0}else e.codec==="opus"&&(i=Cc(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:s}},$c=r=>{let e="audio/ogg";if(r.codecStrings){let t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};var ir=27,yr=282,Yc=yr+65025,ii=r=>{let e=r.filePos;if(wr(r)!==Ia)return null;r.skip(1);let i=D(r),s=Jc(r),n=wr(r),a=wr(r),o=wr(r),c=D(r),l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=D(r);let u=27+c,d=l.reduce((h,g)=>h+g,0),f=u+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+u,dataSize:d,headerType:i,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:l}},Zc=(r,e)=>{for(;r.filePos<e-3;){let t=wr(r),i=t&255,s=t>>>8&255,n=t>>>16&255,a=t>>>24&255,o=79;if(!(i!==o&&s!==o&&n!==o&&a!==o)){if(r.skip(-4),t===Ia)return!0;r.skip(1)}}return!1};var nn=class extends me{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,ir,yr);if(t instanceof Promise&&(t=await t),!t)break;let i=ii(t);if(!i||!!!(i.headerType&2))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(let t of this.bitstreams){let i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.trackBackings.push(new va(t,this)))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;let s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||(i=await this.findNextPacketStart(s),!i))return;let n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;let a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(s.data.length);let c=new Uint8Array(1+a.length+e.data.length+s.data.length+n.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(s.data,1+a.length+e.data.length),c.set(n.data,1+a.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;let l=L(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Pc(n.data).modeBlockflags},qi(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;let s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;let n=Kr(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=Pt,t.codecInfo.opusInfo={preSkip:n.preSkip},qi(s.data.subarray(8),this.metadataTags)}async readPacket(e,t){p(t<e.lacingValues.length);let i=0;for(let d=0;d<t;d++)i+=e.lacingValues[d];let s=e,n=i,a=t,o=[];e:for(;;){let d=this.reader.requestSlice(s.dataStartPos,s.dataSize);d instanceof Promise&&(d=await d),p(d);let f=M(d,s.dataSize);for(;;){if(a===s.lacingValues.length){o.push(f.subarray(i,n));break}let g=s.lacingValues[a];if(n+=g,g<255){o.push(f.subarray(i,n));break e}a++}let h=s.headerStartPos+s.totalSize;for(;;){let g=this.reader.requestSliceRange(h,ir,yr);if(g instanceof Promise&&(g=await g),!g)return null;let m=ii(g);if(!m)return null;if(s=m,s.serialNumber===e.serialNumber)break;h=s.headerStartPos+s.totalSize}i=0,n=0,a=0}let c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let d=0;d<o.length;d++){let f=o[d];l.set(f,u),u+=f.length}return{data:l,endPage:s,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(i,ir,yr);if(s instanceof Promise&&(s=await s),!s)return null;let n=ii(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};i=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(i=>i?.codec??null)));return $c({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},va=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new _e,this.internalSampleRate=e.codecInfo.codec==="opus"?Pt:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return p(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return p(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 Z}getDisposition(){return{...we,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(p(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;let{durationInSamples:s,vorbisBlockSize:n}=Qc(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new X(i.metadataOnly?de:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),a}async getFirstPacket(e){p(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(p(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);let s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");let s=await this.demuxer.findNextPacketStart(i.packet);if(!s)return null;let n=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let i=St(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;p(this.bitstream.lastMetadataPacket);let s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,a=this.demuxer.reader.fileSize,o=[n];e:for(;n.headerStartPos+n.totalSize<a;){let b=n.headerStartPos,S=Math.floor((b+a)/2),T=S;for(;;){let A=Math.min(T+Yc,a-ir),P=this.demuxer.reader.requestSlice(T,A-T);if(P instanceof Promise&&(P=await P),p(P),!Zc(P,A)){a=S+ir;continue e}let C=this.demuxer.reader.requestSliceRange(P.filePos,ir,yr);C instanceof Promise&&(C=await C),p(C);let x=ii(C);p(x);let _=!1;if(x.serialNumber===this.bitstream.serialNumber)_=!0;else{let I=this.demuxer.reader.requestSlice(x.headerStartPos,x.totalSize);I instanceof Promise&&(I=await I),p(I);let U=M(I,x.totalSize);_=Xc(U)===x.checksum}if(!_){T=x.headerStartPos+4;continue}if(_&&x.serialNumber!==this.bitstream.serialNumber){T=x.headerStartPos+x.totalSize;continue}if(x.granulePosition===-1){T=x.headerStartPos+x.totalSize;continue}this.granulePositionToTimestampInSamples(x.granulePosition)>i?a=x.headerStartPos:(n=x,o.push(x));continue e}}let c=s.startPage;for(let b of o){if(b.granulePosition===n.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){let b=l.headerStartPos+l.totalSize,S=this.demuxer.reader.requestSliceRange(b,ir,yr);S instanceof Promise&&(S=await S),p(S);let T=ii(S);p(T),l=T,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}p(l.granulePosition!==-1);let d=null,f,h,g=l,m=0;if(l.headerStartPos===s.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{f=0,h=!1;for(let T=l.lacingValues.length-1;T>=0;T--)if(l.lacingValues[T]<255){d=T+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;let b={data:de,endPage:g,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(b)){let T=tl(u,l,d);p(T);let A=el(u,T.page,T.segmentIndex);A&&(l=A.page,d=A.segmentIndex)}else for(;;){let T=tl(u,l,d);if(!T)break;let A=el(u,T.page,T.segmentIndex);if(!A)break;if(l=A.page,d=A.segmentIndex,T.page.headerStartPos!==g.headerStartPos){g=T.page,m=T.segmentIndex;break}}}let w=null,y=null;for(;l!==null;){p(d!==null);let b=await this.demuxer.readPacket(l,d);if(!b)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&d<s.startSegmentIndex)){let A=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);p(A);let P=this.encodedPacketToMetadata.get(A);if(p(P),!h&&b.endPage.headerStartPos===g.headerStartPos&&b.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,A=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f-P.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),p(A),P=this.encodedPacketToMetadata.get(A),p(P)):f+=P.durationInSamples,w=A,y=P,h&&(Math.max(f,0)>i||Math.max(P.timestampInSamples,0)===i))break}let T=await this.demuxer.findNextPacketStart(b);if(!T)break;l=T.startPage,d=T.startSegmentIndex}return w}async getPacketSequential(e,t){let i=await this.sequentialScanMutex.acquire();try{let s=St(e*this.internalSampleRate);e=s/this.internalSampleRate;let n=H(this.sequentialScanCache,s,c=>c.timestampInSamples),a;if(n!==-1){let c=this.sequentialScanCache[n];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){let c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(a);p(l),this.sequentialScanCache.length>0&&p(Q(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},el=(r,e,t)=>{let i=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(i.lacingValues[s]<255){s++;break e}if(p(s===-1),!(i.headerType&1)){s=0;break}let a=sa(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,s=i.lacingValues.length}if(p(s!==-1),s===i.lacingValues.length){let n=r[r.indexOf(i)+1];p(n),i=n,s=0}return{page:i,segmentIndex:s}},tl=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};let i=sa(r,s=>s.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};var Me;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(Me||(Me={}));var an=class extends me{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),p(e);let t=Y(e,4),i=t!=="RIFX",s=t==="RF64",n=Ut(e,i),a=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(Y(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let f=this.reader.requestSlice(u,8);if(f instanceof Promise&&(f=await f),!f)break;let h=Y(f,4),g=Ut(f,i),m=f.filePos;if(s&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,g,i);else if(h==="data"){if(l??=g,this.dataStart=f.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let w=this.reader.requestSlice(m,g);if(w instanceof Promise&&(w=await w),!w)break;let y=Fa(w,i);l=Fa(w,i),a=Math.min(y+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,g,i):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,g);u=m+g+(g&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Ra(this))})()}async parseFmtChunk(e,t,i){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=ni(s,i),a=ni(s,i),o=Ut(s,i);s.skip(4);let c=ni(s,i),l;if(t===14?l=8:l=ni(s,i),t>=18&&n!==357){let u=ni(s,i),d=t-18;if(Math.min(d,u)>=22&&n===Me.EXTENSIBLE){s.skip(6);let h=M(s,16);n=h[0]|h[1]<<8}}(n===Me.MULAW||n===Me.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}}async parseListChunk(e,t,i){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=Y(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+t-8;){s.filePos=a;let o=Y(s,4),c=Ut(s,i),l=M(s,c),u=0;for(let f=0;f<l.length&&l[f]!==0;f++)u++;let d=String.fromCharCode(...l.subarray(0,u));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=d,o){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let f=d.split("/"),h=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"ICRD":case"IDIT":{let f=new Date(d);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{let f=Number.parseInt(d,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=Be(i);if(s){let n=t-Ae;if(s.size=Math.min(s.size,n),s.size>0){let a=i.slice(e+Ae,s.size);rr(a,s,this.metadataTags)}}}getCodec(){if(p(this.audioInfo),this.audioInfo.format===Me.MULAW)return"ulaw";if(this.audioInfo.format===Me.ALAW)return"alaw";if(this.audioInfo.format===Me.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Me.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},si=2048,Ra=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(p(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return p(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...we}}async getPacketAtIndex(e,t){p(e>=0),p(this.demuxer.audioInfo);let i=e*si*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;let s=Math.min(si*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=de;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);c instanceof Promise&&(c=await c),p(c),n=M(c,s)}let a=e*si/this.demuxer.audioInfo.sampleRate,o=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new X(n,"key",a,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){p(this.demuxer.audioInfo);let i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/si,(this.demuxer.dataSize-1)/(si*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;let s=await this.getPacketAtIndex(i,t);if(s)return s;if(i===0)return null;p(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){let a=await this.getNextPacket(n,t);if(!a)break;n=a}return n}getNextPacket(e,t){p(this.demuxer.audioInfo);let i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/si);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var zt=7,Ne=9,De=r=>{let e=r.filePos,t=M(r,9),i=new G(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;let a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);let l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let u=i.readBits(13);i.skipBits(11);let d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return a===1?r.filePos-=2:f=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:f,startPos:e}};var Ji=1024,on=class extends me{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new _e,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();p(this.firstFrameHeader),this.trackBackings=[new Ba(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Ae);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}let o=Be(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,zt,Ne);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=De(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let i=We[t.samplingFrequencyIndex];p(i!==void 0);let s=Ji/i,n={timestamp:this.nextTimestampInSamples/i,duration:s,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Ji,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let i=this.reader.requestSlice(t,Ae);if(i instanceof Promise&&(i=await i),!i)break;let s=Be(i);if(!s)break;let n=this.reader.requestSlice(i.filePos,s.size);if(n instanceof Promise&&(n=await n),!n)break;rr(n,s,this.metadataTags),t=i.filePos+s.size}return this.metadataTags}finally{e()}}},Ba=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ji}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Z}getCodec(){return"aac"}getInternalCodecId(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){p(this.demuxer.firstFrameHeader);let e=mt[this.demuxer.firstFrameHeader.channelConfiguration];return p(e!==void 0),e}getSampleRate(){p(this.demuxer.firstFrameHeader);let e=We[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return p(e!==void 0),e}getDisposition(){return{...we}}async getDecoderConfig(){return p(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=de;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=M(n,i.dataSize)}return new X(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let s=At(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");let n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=H(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};var rl=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,il=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},sl=r=>{let e=0,t=new G(M(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);let i=[],s=e-1,n=new G(M(r,s)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(t.readBits(1));for(let c=0;c<s;c++)for(let l=0;l<8;l++){let u=n.readBits(1);l<2||i.unshift(u)}return i.reduce((c,l,u)=>c|l<<u,0)},nl=(r,e)=>{if(e==="uncommon-u16")return re(r)+1;if(e==="uncommon-u8")return D(r)+1;if(typeof e=="number")return e;le(e),p(!1)},al=(r,e)=>e==="uncommon-u16"?re(r):e==="uncommon-u16-10"?re(r)*10:e==="uncommon-u8"?D(r):typeof e=="number"?e:null,ol=r=>{let t=0;for(let i of r){t^=i;for(let s=0;s<8;s++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};var cn=class extends me{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new _e,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),p(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,Ae);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let i=Be(t);if(!i)break;let s=this.reader.requestSlice(t.filePos,i.size);s instanceof Promise&&(s=await s),p(s),rr(s,i,this.metadataTags),e=t.filePos+i.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);p(t);let i=D(t),s=rt(t),n=(i&128)!==0;switch(i&127){case Zt.STREAMINFO:{let o=this.reader.requestSlice(e,s);if(o instanceof Promise&&(o=await o),p(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=M(o,34),l=new G(c),u=l.readBits(16),d=l.readBits(16),f=l.readBits(24),h=l.readBits(24),g=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);let w=l.readBits(36);l.skipBits(128);let y=new Uint8Array(42);y.set(new Uint8Array([102,76,97,67]),0),y.set(new Uint8Array([128,0,0,34]),4),y.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:g,totalSamples:w,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:h,description:y},this.trackBacking=new Ma(this);break}case Zt.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),p(o),qi(M(o,s),this.metadataTags);break}case Zt.PICTURE:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),p(o);let c=R(o),l=R(o),u=he.decode(M(o,l)),d=R(o),f=he.decode(M(o,d));o.skip(16);let h=R(o),g=M(o,h);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,mimeType:u,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:f});break}default:break}if(e+=s,n){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){p(this.audioInfo);let i=6,s=16,n=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+s+2,o=this.audioInfo.minimumFrameSize||n,l=(this.audioInfo.maximumFrameSize||a)+s,u=await this.reader.requestSliceRange(e,s,l);if(!u)return null;let d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-i)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(D(u)===255){let h=u.filePos,g=D(u),m=this.blockingBit===1?249:248;if(g!==m){u.filePos=h;continue}u.skip(-2);let w=u.filePos-e,y=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!y){u.filePos=h;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=h;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=h;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:w,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let i=e.filePos,s=M(e,4),n=new G(s);if(n.readBits(15)!==32764)return null;if(this.blockingBit===null){p(t);let w=n.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(p(!t),n.readBits(1)!==1)return null}else if(this.blockingBit===0){if(p(!t),n.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let o=rl(n.readBits(4));if(!o)return null;p(this.audioInfo);let c=il(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;let u=sl(e),d=nl(e,o),f=al(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;let h=e.filePos-i,g=D(e);e.skip(-h),e.skip(-1);let m=ol(M(e,h));return g!==m?null:{num:u,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),p(this.lastLoadedPos!==null),p(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let i=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(n),t.isLastFrame){this.lastSampleLoaded=!0;return}}},Ma=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...we}}async getDecoderConfig(){return p(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(p(this.demuxer.audioInfo),e<0)return null;let i=await this.demuxer.readingMutex.acquire();try{for(;;){let s=H(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(s===-1){await this.demuxer.advanceReader();continue}let n=this.demuxer.loadedSamples[s],a=n.blockOffset/this.demuxer.audioInfo.sampleRate,o=n.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(s,t)}}finally{i()}}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=de;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;s=M(o,i.byteSize)}p(this.demuxer.audioInfo);let n=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new X(s,"key",n,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};var cl=r=>{let e="video/MP2T",t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};var ul="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",ll=new Set,ln=class extends me{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),p(t);let i=M(t,e);if(i[0]===71&&i[188]===71)this.packetOffset=0,this.packetStride=188;else if(i[0]===71&&i[204]===71)this.packetOffset=0,this.packetStride=204;else if(i[4]===71&&i[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let s=256;this.minReferencePointByteDistance=s*this.packetStride;let n=this.packetOffset,a=null,o=!1,c=!1;for(;;){let l=await this.readPacketHeader(n);if(!l)break;if(l.payloadUnitStartIndicator===0){n+=this.packetStride;continue}if(c&&!this.elementaryStreams.some(m=>m.pid===l.pid)){n+=this.packetStride;continue}let u=await this.readSection(n,!0,!c);if(!u)break;let d=3,f=32,h=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){let w=new G(u.payload),y=w.readAlignedByte();w.skipBits(8*y),h=w.readBits(8)===2}if(u.pid===0&&!o){let m=new G(u.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(14);let y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>f;){let b=m.readBits(16);m.skipBits(3);let S=m.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=S}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||h)&&!c){let m=new G(u.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(12);let y=m.readBits(12);m.skipBits(43);let b=m.readBits(13);m.skipBits(6);let S=m.readBits(10);for(m.skipBits(8*S);8*(y+d)-m.pos>f;){let T=m.readBits(8);m.skipBits(3);let A=m.readBits(13);m.skipBits(6);let P=m.readBits(10),E=m.pos+8*P,C=!1,x=!1;for(;m.pos<E;){let F=m.readBits(8),I=m.readBits(8);F===106?C=!0:(F===122||F===204)&&(x=!0),m.skipBits(8*I)}let _=null;switch(T){case 27:case 36:_={type:"video",codec:T===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let F;if(T===3||T===4)F="mp3";else if(T===15)F="aac";else if(T===129)F="ac3";else if(T===135)F="eac3";else throw new Error("Unreachable.");_={type:"audio",codec:F,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:x?_={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:C&&(_={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:ll.has(T)||(O._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),ll.add(T))}_&&this.elementaryStreams.push({demuxer:this,pid:A,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:_,referencePesPackets:[]})}c=!0}else{let m=this.elementaryStreams.find(w=>w.pid===u.pid);e:if(m&&!m.initialized){let w=ai(u,!0);if(!w)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){let S=(await this.input._initInput._getDemuxer()).elementaryStreams.find(T=>T.pid===u.pid&&T.info.codec===m.info.codec);if(S){m.info=S.info,m.initialized=!0;break e}}let y=new kr(m,w);if(m.info.type==="video"){for(;;){let b=y;if(b.suppliedPacket=null,await y.markNextPacket(),m.info.codec==="avc"){if(!y.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Gr(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;let S=m.info.avcCodecInfo.sequenceParameterSets[0];p(S);let T=Hi(S);m.info.width=T.displayWidth,m.info.height=T.displayHeight;let A=T.pixelAspectRatio.num,P=T.pixelAspectRatio.den;A>0&&P>0&&(A>P?(m.info.squarePixelWidth=Math.round(m.info.width*A/P),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*P/A))),m.info.colorSpace={primaries:or[T.colourPrimaries],transfer:cr[T.transferCharacteristics],matrix:lr[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!y.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=jr(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;let T=m.info.hevcCodecInfo.arrays.find(P=>P.nalUnitType===fe.SPS_NUT).nalUnits[0];p(T);let A=wa(T);m.info.width=A.displayWidth,m.info.height=A.displayHeight,A.pixelAspectRatio.num>A.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*A.pixelAspectRatio.num/A.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*A.pixelAspectRatio.den/A.pixelAspectRatio.num)),m.info.colorSpace={primaries:or[A.colourPrimaries],transfer:cr[A.transferCharacteristics],matrix:lr[A.matrixCoefficients],fullRange:!!A.fullRangeFlag},m.info.reorderSize=A.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:Ur({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await y.markNextPacket(),!y.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){let b=ye.tempFromBytes(y.suppliedPacket.data),S=De(b);if(!S)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:S.objectType},m.info.numberOfChannels=mt[S.channelConfiguration],m.info.sampleRate=We[S.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){let b=R(ye.tempFromBytes(y.suppliedPacket.data)),S=pr(b,y.suppliedPacket.data.byteLength);if(!S.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=$t(S.header.channel),m.info.sampleRate=S.header.sampleRate}else if(m.info.codec==="ac3"){let b=Ds(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Gi[b.acmod]+b.lfeon,m.info.sampleRate=gr[b.fscod]}else if(m.info.codec==="eac3"){let b=Os(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let S=Us(b);if(S===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=zs(b),m.info.sampleRate=S}else throw new Error("Unhandled.");m.info.decoderConfig={codec:zr({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;n+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new Da(l)):this.trackBackingEntries.push(new Oa(l))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(i=>i?.codec??null)));return cl(e)}async readSection(e,t,i=!1){let s=e,n=e,a=[],o=0,c=null,l=!0,u=0;for(;;){let f=await this.readPacket(n);if(n+=this.packetStride,!f)break;if(c){if(f.pid!==c.pid){if(i)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}let h=!!(f.adaptationFieldControl&2),g=!!(f.adaptationFieldControl&1),m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(u=f.body[1]>>6&1)),g&&(m===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(m)),o+=f.body.byteLength-m)),s=n,!t&&o>=64){l=!1;break}if(At(this.sectionEndPositions,s,y=>y)!==-1){l=!1;break}}if(l){let f=H(this.sectionEndPositions,s,h=>h);this.sectionEndPositions.splice(f+1,0,s)}if(!c)return null;let d;if(a.length===1)d=a[0];else{let f=a.reduce((g,m)=>g+m.length,0);d=new Uint8Array(f);let h=0;for(let g of a)d.set(g,h),h+=g.length}return{startPos:e,endPos:t?s:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(D(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=re(t),n=s>>15,a=s>>14&1,o=s>>13&1,c=s&8191,l=D(t),u=l>>6,d=l>>4&3,f=l&15;return{payloadUnitStartIndicator:a,pid:c,adaptationFieldControl:d}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let i=M(t,188);if(i[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let n=(i[1]<<8)+i[2],a=n>>15,o=n>>14&1,c=n>>13&1,l=n&8191,u=i[3],d=u>>6,f=u>>4&3,h=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:f,body:i.subarray(4)}}},br=(r,e)=>{if(r.payload.byteLength<3)return null;let t=new G(r.payload);if(t.readBits(24)!==1)return null;let s=t.readBits(8);if(t.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;t.skipBits(8);let n=t.readBits(2);t.skipBits(14);let a=null;if(n===2||n===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(ul);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},ai=(r,e)=>{p(r.endPos!==null);let t=br(r,e);if(!t)return null;let i=new G(r.payload);i.skipBits(32);let s=i.readBits(16),n=6;i.skipBits(16);let a=i.readBits(8),o=i.pos+8*a;i.pos=o;let c=o/8;p(Number.isInteger(c));let l=r.payload.subarray(c,s>0?n+s:r.payload.byteLength);return{...t,data:l}},un=class r{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type,i=0;for(let s of e.trackBackingEntries)if(s.getType()===t&&i++,p(s instanceof r),s.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Z}getDisposition(){return{...we,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let s;return this.allPacketsAreKeyPackets()?s="key":s=e.randomAccessIndicator===1?"key":"delta",new X(i.metadataOnly?de:e.data,s,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;p(t);let i=ai(t,!0);p(i);let s=new kr(this.elementaryStream,i),n=new es(this,s),a=await n.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,n),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){let u=await i.readNext();if(!u)return null;this.packetBuffers.delete(e);let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}let s=this.packetSectionStarts.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");let a=await this.elementaryStream.demuxer.readSection(s,!0);p(a);let o=ai(a,!0);p(o);let c=new kr(this.elementaryStream,o);i=new es(this,c);let l=e.sequenceNumber;for(;;){let u=await i.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){let d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,i),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if(i.type==="key")return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){let s=St(e*9e4),n=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=n,c=this.elementaryStream.pid,l=async(T,A,P)=>{let E=T;for(;E<A;){let C=await n.readPacketHeader(E);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){let x=await n.readSection(E,P);if(!x)return null;let _=br(x,!1);if(_&&_.pts!==null)return{pesPacketHeader:_,section:x}}E+=n.packetStride}return null},u=this.elementaryStream.firstSection;p(u);let d=br(u,!0);if(p(d),s<d.pts)return null;let f,h=this.elementaryStream.referencePesPackets,g=H(h,s,T=>T.pts),m=g!==-1?h[g]:null;if(m&&s-m.pts<9e4/2)f=m.sectionStartPos;else{let T=0;if(a.fileSize!==null){let A=Math.ceil(a.fileSize/o);if(A>1){let P=0,E=A-1;for(T=P;P<=E;){let C=Math.floor((P+E)/2),x=hs(C*o,n.packetStride)+d.sectionStartPos,_=x+o,F=await l(x,_,!1);if(!F){E=C-1;continue}F.pesPacketHeader.pts<=s?(T=C,P=C+1):E=C-1}}}f=hs(T*o,n.packetStride)+d.sectionStartPos}let y=(await l(f,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let b=this.getReorderSize(),S=async(T,A)=>{let P=await n.readSection(T,!0);p(P);let E=ai(P,!0);p(E);let C=new kr(this.elementaryStream,E),x=new es(this,C);for(;!((Q(x.presentationOrderPackets)?.pts??-1/0)>=s||!await x.readNextPacket()););let _=Rr(x.presentationOrderPackets,A);if(_===-1)return null;let F=x.presentationOrderPackets[_],I=_===0?0:F.pts-x.presentationOrderPackets[_-1].pts;for(;x.decodeOrderPackets[0]!==F;)x.decodeOrderPackets.shift();x.lastDuration=I;let U=await x.readNext();p(U);let q=this.createEncodedPacket(U.packet,U.duration,i);return this.packetBuffers.set(q,x),this.packetSectionStarts.set(q,U.packet.sectionStartPos),q};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let T=y.sectionStartPos+n.packetStride;for(;;){let A=await n.readPacketHeader(T);if(!A)break e;if(A.pid===c&&A.payloadUnitStartIndicator===1){let P=await n.readSection(T,!1);if(P){let E=br(P,!1);if(E&&E.pts!==null){if(E.pts>s)break e;y=E,Ua(this.elementaryStream,y);break}}}T+=n.packetStride}}e:for(let T=0;T<b+1;T++){let A=y.sectionStartPos-n.packetStride;for(;A>=n.packetOffset;){let P=await n.readPacketHeader(A);if(!P)break e;if(P.pid===c&&P.payloadUnitStartIndicator===1){let E=await n.readSection(A,!1);if(E){let C=br(E,!1);if(C&&C.pts!==null){y=C;break}}}A-=n.packetStride}}return S(y.sectionStartPos,T=>T.pts<=s)}else{let T=f,A=null,P=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let E=null,C=T<=d.sectionStartPos,x,_=null;if(C)x=d,_=u;else{let U=await l(T,a.fileSize??1/0,P);x=U?.pesPacketHeader??null,_=U?.section??null}let F=!1,I=0;e:for(;x&&!(A!==null&&x.sectionStartPos>=A);){if(x.pts<=s){let q;if(this.elementaryStream.canBeTrustedWithKeyPackets)q=x.randomAccessIndicator===1;else{p(_);let W=ai(_,!0);p(W);let V=new kr(this.elementaryStream,W);await V.markNextPacket(),q=V.suppliedPacket?.randomAccessIndicator===1}q&&(E=x)}if(x.pts>s&&(F=!0),F&&(I++,I>b))break;let U=x.sectionStartPos+n.packetStride;for(;;){let q=await n.readPacketHeader(U);if(!q)break e;if(q.pid===c&&q.payloadUnitStartIndicator===1){let W=await n.readSection(U,P);if(W){let V=br(W,!1);if(V&&V.pts!==null){x=V,_=W,Ua(this.elementaryStream,x);break}}}U+=n.packetStride}}if(E){let U=E;if(I===0)e:for(let W=0;W<b;W++){let V=U.sectionStartPos-n.packetStride;for(;V>=n.packetOffset;){let ce=await n.readPacketHeader(V);if(!ce)break e;if(ce.pid===c&&ce.payloadUnitStartIndicator===1){let Se=await n.readSection(V,P);if(Se){let ct=br(Se,!1);if(ct&&ct.pts!==null){U=ct;break}}}V-=n.packetStride}}let q=await S(U.sectionStartPos,W=>W.pts<=s&&W.randomAccessIndicator===1);return p(q),q}if(C)return null;A=T,T=Math.max(hs(T-d.sectionStartPos-o,n.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Da=class extends un{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Oa=class extends un{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Ua=(r,e)=>{let t=r.referencePesPackets,i=H(t,e.sectionStartPos,s=>s.sectionStartPos);if(i>=0){let s=t[i];if(e.pts<=s.pts)return!1;let n=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-s.sectionStartPos<n)return!1;if(i<t.length-1){let a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<n)return!1}}return t.splice(i+1,0,e),!0},kr=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return p(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let i;if(this.pesPackets.length===0)i=this.startingPesPacket;else{let s=Q(this.pesPackets).sectionEndPos;for(p(s!==null);;){let n=await this.demuxer.readPacketHeader(s);if(!n)return;if(n.pid===this.pid){let a=await this.demuxer.readSection(s,!0);if(!a)return;let o=ai(a,!1);if(o){i=o;break}}s+=this.demuxer.packetStride}}this.pesPackets.push(i),this.endPos+=i.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,s=i+e;if(this.currentPos+=e,s<=t.data.byteLength)return t.data.subarray(i,s);let n=new Uint8Array(e);n.set(t.data.subarray(i));let a=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){n.set(o.data.subarray(0,c),a);break}n.set(o.data,a),a+=o.data.byteLength}return n}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){let t=this.getCurrentPesPacket(),i=this.currentPesPacketPos+t.data.byteLength;if(e<i)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){p(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type==="video"){let t=e.info.codec,i=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let s=t==="avc"?1:2,n=null,a=!1,o=0;for(;;){let c=this.ensureBuffered(i);if(c instanceof Promise&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,f=0;for(;f<d;){let h=u.indexOf(0,f);if(h===-1||h>=d)break;f=h;let g=l+f;if(f+3>=d){this.seekTo(g);break}let m=u[f+1],w=u[f+2],y=u[f+3],b=0;if(m===0&&w===0&&y===1?b=4:m===0&&w===1&&(b=3),b===0){f++;continue}let S=g;n??=S;let T=f+b,A=T+s,P=6;if(A+(t==="avc"?P:1)>d){this.seekTo(g);break}let C=u[T],x,_,F;if(t==="avc")x=qr(C),_=x===pe.NON_IDR_SLICE||x===pe.SLICE_DPA||x===pe.IDR,F=x===pe.SEI||x===pe.SPS||x===pe.PPS||x===pe.AUD;else{if(x=Yt(C),((C&1)<<5|u[T+1]>>3)>0){f+=b;continue}_=x<=fe.RASL_R||x>=fe.BLA_W_LP&&x<=21,F=x>=fe.VPS_NUT&&x<=37||x===fe.PREFIX_SEI_NUT||x>=41&&x<=44||x>=48&&x<=55}let I=!1;if(_){let U;if(t==="avc"){let q=u.subarray(A,A+P),W=B(new G(q));U=!a||W<=o,o=W}else U=u[A]>>7===1;U&&(a?I=!0:a=!0)}else F&&a&&(I=!0);if(I){let U=S-n;return this.seekTo(n),this.supplyPacket(U,0)}f+=b}if(c<i)break}if(n!==null&&this.endPos>n){let c=this.endPos-n;return this.seekTo(n),this.supplyPacket(c,0)}}else{let t=e.info.codec,i=128;for(;;){let s=this.ensureBuffered(i);s instanceof Promise&&(s=await s);let n=this.currentPos;for(;this.currentPos-n<s;){let a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(Ne);if(c instanceof Promise&&(c=await c),c<Ne)return;let l=this.readBytes(Ne),u=De(ye.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(Ji*9e4/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(c instanceof Promise&&(c=await c),c<4)return;let l=this.readBytes(4),u=L(l).getUint32(0),d=pr(u,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);f instanceof Promise&&(f=await f);let h=d.header.audioSamplesInFrame*9e4/e.info.sampleRate;return this.supplyPacket(f,Math.round(h))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let f=Ec[3*d+u];p(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),c instanceof Promise&&(c=await c);let h=Math.round(_c*9e4/e.info.sampleRate);return this.supplyPacket(c,h)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,h=l[4]>>6===3?3:l[4]>>4&3,g=ya[h];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);let m=g*256,w=Math.round(m*9e4/e.info.sampleRate);return this.supplyPacket(c,w)}else throw new Error("Unhandled.")}if(s<i)break}}}supplyPacket(e,t){let i=this.getCurrentPesPacket(),s;if(this.lastSuppliedPesPacket===i)p(this.nextPts!==null),s=this.nextPts;else{if(i.pts===null)throw new Error(ul);s=i.pts,Ua(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=s+t;let n=i.sectionStartPos,a=n+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),c=i.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let l=Jt(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:s,data:o,sequenceNumber:a,sectionStartPos:n,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},es=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),p(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);p(t!==-1);let i;for(t===this.presentationOrderPackets.length-1?i=this.lastDuration:(i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let s=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(s))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(p(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let s=1;s<this.reorderBuffer.length;s++)this.reorderBuffer[s].pts<this.reorderBuffer[t].pts&&(t=s);let i=this.reorderBuffer[t];this.presentationOrderPackets.push(i),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var dn="application/vnd.apple.mpegurl",za="#EXT-X-STREAM-INF:",Na="#EXT-X-I-FRAME-STREAM-INF:",Va="#EXT-X-MEDIA:",ts="#EXTINF:",La="#EXT-X-MAP:",Wa="#EXT-X-KEY:",Ha="#EXT-X-MEDIA-SEQUENCE:",qa="#EXT-X-BYTERANGE:",Ga="#EXT-X-PROGRAM-DATE-TIME:",dl="#EXT-X-DISCONTINUITY",ja="#EXT-X-TARGETDURATION:",fl="#EXT-X-ENDLIST",Ka="#EXT-X-PLAYLIST-TYPE:",hl="#EXT-X-I-FRAMES-ONLY",fn=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT"),Vt=class{constructor(e){this._attributes={};let t="",i="",s=!1,n=!1;for(let a=0;a<e.length;a++){let o=e[a];o==='"'?n=!n:o==="="&&!s&&!n?s=!0:o===","&&!n?(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",s=!1):s?i+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}};var hn=class{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(t??=await this.getFirstSegment({}),!t||t.unixEpochTimestamp===null)return null;let i=e-t.timestamp;return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type==="video"){let i=dr(e,s=>s.getType()==="video")+1;e.push(new pn(this,t,i))}else if(t.type==="audio"){let i=dr(e,s=>s.getType()==="audio")+1;e.push(new gn(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let i=await this.getInputForSegment(this.firstSegment).getTracks();for(let s of i)if(s.type==="video"){let n=dr(e,a=>a.getType()==="video")+1;e.push(new pn(this,{id:e.length+1,type:"video"},n))}else if(s.type==="audio"){let n=dr(e,a=>a.getType()==="audio")+1;e.push(new gn(this,{id:e.length+1,type:"audio"},n))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){let i=e.firstSegment??e,s;if(this.firstSegmentFirstTimestamps.has(i))s=this.firstSegmentFirstTimestamps.get(i);else{let l=this.getInputForSegment(i);s=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(i,s)}if(i===e)return i.timestamp-s;let n=await this.getFirstTimestampForInput(t),a=e.timestamp-i.timestamp,c=n-s-a;return Math.abs(c)<=Math.min(.25,a)?i.timestamp-s:e.timestamp-n}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},mn=class{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let i=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),p(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){p(e.sequenceNumber>=0),p(this.segmentedInput.firstSegment);let s=await this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:ut(e.timestamp+s,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:i,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),p(this.segmentedInput.firstSegment),p(this.firstInputTrack);let t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){let s=this.packetInfos.get(e);if(!s)throw new Error("Packet was not created from this track.");let n=i?await s.track._backing.getNextKeyPacket(s.sourcePacket,t):await s.track._backing.getNextPacket(s.sourcePacket,t);if(n)return this.createAdjustedPacket(n,s.segment,s.track);let a=s.segment;for(;;){let o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===s.track.type&&f.number===s.track.number);if(!u){a=o;continue}let d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let s=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!s)return null;for(await this.hydrate();s;){let n=this.segmentedInput.getInputForSegment(s),o=(await n.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(s,n),l=e-c,u=i?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,s,o)}return null}},pn=class extends mn{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},gn=class extends mn{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};Br();var Ya=0,Za=1/0,Qu=null;typeof FinalizationRegistry<"u"&&(Qu=new FinalizationRegistry(r=>{r()}));var Ee=class extends Le{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ge;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Ya,Za),e=this._getFileSize(),p(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ge;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new wn(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Tr(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Tr=class{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let e=this.source;p(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},He=class extends Ee{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),i=s=>{if(!(s instanceof Ee||s instanceof Tr))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let n=s instanceof Ee?s.ref():s;return n.source._usedForHls||=this._usedForHls,n};return t instanceof Promise?t.then(i):i(t)}},Ja=(r,e)=>r.path===e.path,rs=class extends He{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,s){if(!this._root){if(!this._rootRequest){let n=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{let c=o instanceof Ee?o.ref():o;return this._root=c,this._rootRequest=null,c};n instanceof Promise?this._rootRequest=n.then(a):(a(n),p(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,s))}return this._root.source._read(e,t,i,s)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},Xa=class extends Ee{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=ee(e),this._view=L(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Qa=class extends Ee{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Bi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new $a({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Yu.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,s){return this._orchestrator.read(e,t,i,s)}async _runWorker(e){p(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!jt()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:i,value:s}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else{let i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},$u=.5*2**20;var is=class extends Ee{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Bi(t.maxCacheSize)||t.maxCacheSize<0))throw new 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=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let i=H(this._cache,e,u=>u.start),s=i!==-1?this._cache[i]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e,a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u<this._cache.length;u++){let d=this._cache[u];if(d.start>=t)break;let f=Math.max(e,d.start);f>n&&this._throwDueToCacheMiss();let h=Math.min(t,d.end);f<h&&(a.set(d.bytes.subarray(f-d.start,h-d.start),f-e),n=h)}if(n===t)return{bytes:a,view:L(a),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();let{promise:o,resolve:c,reject:l}=ne();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new 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(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let n of this._pendingSlices)n.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let i=this._currentIndex,s=this._currentIndex+t.byteLength;this._dispatchRead(i,s);for(let n=0;n<this._pendingSlices.length;n++){let a=this._pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.end);o<c&&(a.bytes.set(t.subarray(o-i,c-i),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:L(a.bytes),offset:a.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:i,end:s,bytes:t,view:L(t),age:0});this._cache.length>0;){let n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Yu={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(let s of t){let a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(ms(r,e,a,s.targetPos)){let o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,s.startPos+u)}}return e=Math.max(e,r+$u),{start:r,end:e}}},$a=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,s){p(!this.disposed);let n=this.options.prefetchProfile(e,t,this.workers),a=Math.max(n.start,i),o=Math.min(n.end,this.fileSize??1/0,s);p(a<=e&&t<=o);let c=null,l=H(this.cache,e,A=>A.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=H(this.cache,a,A=>A.start),f=c?null:new Uint8Array(t-e),h=0,g=a,m=[];if(d!==-1){for(let A=d;A<this.cache.length;A++){let P=this.cache[A];if(P.start>=o)break;if(P.end<=a)continue;let E=Math.max(a,P.start),C=Math.min(o,P.end);if(p(E<=C),g<E&&m.push({start:g,end:E}),g=C,f){let x=Math.max(e,P.start),_=Math.min(t,P.end);if(x<_){let F=x-e;f.set(P.bytes.subarray(x-P.start,_-P.start),F),F===h&&(h=_-e)}}P.age=this.nextAge++}g<o&&m.push({start:g,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:L(f),offset:e}),m.length===0)return p(c),c;let{promise:w,resolve:y,reject:b}=ne(),S=[];for(let A of m){let P=Math.max(e,A.start),E=Math.min(t,A.end);P===A.start&&E===A.end?S.push(A):P<E&&S.push({start:P,end:E})}let T=f&&{start:e,bytes:f,holes:S,resolve:y,reject:b};e:for(let A of m){for(let C of this.workers)if(this.checkHoleAgainstWorker(C,A,T?[T]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}let P=A.end<o||this.fileSize!==null,E=this.createWorker(A.start,A.end,P);if(E)T&&(E.pendingSlices=[T]),this.runWorker(E);else{let C=H(this.queuedReads,A.start,_=>_.hole.start),x=C!==-1?this.queuedReads[C]:null;for(x&&A.start<=x.hole.end?(x.hole.end=Math.max(x.hole.end,A.end),x.strictTarget&&=P,T&&x.pendingSlices.push(T)):(C++,x={hole:{start:A.start,end:A.end},strictTarget:P,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(C,0,x));C+1<this.queuedReads.length;){let _=this.queuedReads[C+1];if(_.hole.start>x.hole.end)break;x.hole.end=Math.max(x.hole.end,_.hole.end),x.pendingSlices.push(..._.pendingSlices),x.strictTarget&&=_.strictTarget,x.age=Math.min(x.age,_.age),this.queuedReads.splice(C+1,1)}}}return c?w.catch(A=>{if(!this.disposed)throw A}):(p(f),c=w.then(A=>A&&{bytes:A,view:L(A),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ms(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let n=0;n<i.length;n++){let a=i[n];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){let s=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,s.hole,s.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let n=null,a=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!n||c.age<n.age)&&(a=o,n=c)}if(n)p(a!==null),p(n.pendingSlices.length===0),this.workers.splice(a,1);else return null}let s={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(s),s}runWorker(e){p(!e.running),p(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!(e.running||this.workers.length>=this.options.maxWorkerCount)&&this.queuedReads.length>0){let t=0;for(let n=1;n<this.queuedReads.length;n++)this.queuedReads[n].age<this.queuedReads[t].age&&(t=n);let i=this.queuedReads[t];this.queuedReads.splice(t,1);let s=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);p(s),s.pendingSlices=i.pendingSlices,this.runWorker(s)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let i=0;i<this.workers.length;i++){let s=this.workers[i];if(s!==e){for(let n of s.pendingSlices)t.add(n);s.aborted=!0,s.pendingSlices.length=0,this.workers.splice(i,1),i--}}for(let i=0;i<this.queuedReads.length;i++){let s=this.queuedReads[i];for(let n of s.pendingSlices)t.add(n)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){p(!e.aborted);let i=e.currentPos,s=i+t.length;this.insertIntoCache({start:i,end:s,bytes:t,view:L(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){let a=e.pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){let u=a.holes[l];i<=u.start&&s>u.start&&(u.start=s),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){let a=this.workers[n];e===a||a.running||ms(i,s,a.currentPos,a.targetPos)&&(this.workers.splice(n,1),n--)}}supplyFileSize(e){p(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){let s=t.pendingSlices[i];for(let n of s.holes)if(n.end>e){s.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){let i=this.queuedReads[t];if(i.hole.start>=e){for(let s of i.pendingSlices)s.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let s=0;s<i.pendingSlices.length;s++){let n=i.pendingSlices[s];n.start>=e&&(n.resolve(null),i.pendingSlices.splice(s,1),s--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let t=this.workers.indexOf(e);p(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=H(this.cache,e.start,i=>i.start)+1;if(t>0){let i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){let s=new Uint8Array(e.end-i.start);s.set(i.bytes,0),s.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=s,i.view=L(s),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){let s=this.cache[i];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length,i--;continue}let n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=L(n),e.end=s.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){let a=this.cache[n];a.age<s.age&&(i=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};var wn=class extends Ee{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:ue(e-this._offset,0,this._length??1/0)}_read(e,t,i,s){if(this._length!==null&&t>this._length)return null;let n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+s),a=o=>o?(o.offset-=this._offset,o):null;return n instanceof Promise?n.then(a):a(n)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var ml=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(s=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");s&&(i=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},pl=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,s=0;function n(){for(;i=e.stack.pop();)try{if(!i.async&&s===1)return s=0,e.stack.push(i),Promise.resolve().then(n);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i}),Zu=/^0[xX][0-9a-fA-F]+$/,Ju=/^data:.*;base64,/i,ss=class extends hn{constructor(e,t,i,s){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=s}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await oa(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let S={stack:[],error:void 0,hasError:!1};try{let T=ml(S,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),P=await new sr(T.source).requestEntireFile();p(P),e=yn(P,P.length,{ignore:fn}),T.source instanceof He&&(this.rootPath=T.source.rootPath)}catch(T){S.error=T,S.hasError=!0}finally{pl(S)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,i=!1,s=0,n=null,a=null,o=null,c=0,l=null,u=null,d=null,f=null,h=null,g=null,m=!1,w=Q(this.segments)??null,y=S=>{let T=S.indexOf("@"),A=Number(T===-1?S:S.slice(0,T));if(!Number.isInteger(A)||A<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${S}'.`);let P=null;if(T!==-1&&(P=Number(S.slice(T+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${S}'.`);return{length:A,offset:P}},b=S=>{c=S,w&&(p(w.sequenceNumber!==null),w.sequenceNumber<S&&(s=w.timestamp+w.duration,l=w.firstSegment,u=w.initSegment,h=w.lastProgramDateTimeSeconds,n=w.unixEpochTimestamp!==null?w.unixEpochTimestamp+w.duration:null,w=null))};for(let S=0;S<e.length;S++){let T=e[S];if(!i){if(T!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0;continue}if(!T.startsWith("#")){if(!w){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let A=o;if(A&&A.method==="AES-128"&&!A.iv){let x=new Uint8Array(tt),_=L(x);_.setUint32(8,Math.floor(c/2**32)),_.setUint32(12,c),A={...A,iv:x}}let E={path:ht(this.rootPath,T),offset:f?.offset??0,length:f?.length??null},C={timestamp:s,unixEpochTimestamp:n,firstSegment:l,sequenceNumber:c,location:E,duration:a,encryption:A,initSegment:u,lastProgramDateTimeSeconds:h};l??=C,s+=a,n!==null&&(n+=a),this.segments.push(C)}a=null,f===null?d=null:f=null,b(c+1)}if(T.startsWith(ts)){if(w){m=!0;continue}m||(h===null&&c>0&&g!==null&&(s=c*g),m=!0);let A=T.slice(ts.length),P=A.indexOf(","),E=P===-1?A:A.slice(0,P),C=Number(E);if(!Number.isFinite(C)||C<0)throw new Error(`Invalid #EXTINF tag duration '${E}'.`);a=C}else if(T.startsWith(La)){let A=new Vt(T.slice(La.length)),P=A.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let E=A.get("byterange"),C=null;if(E!==null&&(C=y(E)),C&&C.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!w){let _={path:ht(this.rootPath,P),offset:C?.offset??0,length:C?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:s,unixEpochTimestamp:n,firstSegment:null,sequenceNumber:null,location:_,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,f===null?d=null:f=null}else if(T.startsWith(Wa)){let A=new Vt(T.slice(Wa.length)),P=A.get("method");if(P==="NONE")o=null;else if(P==="AES-128"){let E=A.get("uri");if(!E)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let C=null,x=A.get("iv");if(x){if(!Zu.test(x))throw new Error(`Unsupported IV format '${x}'.`);let F=x.slice(2);F=F.padStart(tt*2,"0"),C=new Uint8Array(tt);for(let I=0;I<tt;I++){let U=-tt*2+I;C[I]=parseInt(F.slice(U,U+2),16)}}let _=A.get("keyformat")??"identity";if(_!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");o={method:"AES-128",keyUri:ht(this.rootPath,E),iv:C,keyFormat:_}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){let E=A.get("uri");if(!E)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((A.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let x=null;if(Ju.test(E)){let _=E.indexOf(","),F=Fi(E.slice(_+1));if(F.length>=8&&F[4]===112&&F[5]===115&&F[6]===115&&F[7]===104){let I=L(F).getUint32(0);x=Vs(F.subarray(8,Math.min(I,F.length)))}}o={method:P,psshBox:x}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith(Ha)){let A=T.slice(Ha.length),P=Number(A);if(!Number.isInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${A}'.`);b(P)}else if(T.startsWith(qa)){let A=y(T.slice(qa.length));if(A.offset===null){if(d===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");A.offset=d}f=A,d=A.offset+A.length}else if(T.startsWith(Ga)){if(w)continue;let A=T.slice(Ga.length),P=Date.parse(A);if(!Number.isFinite(P))continue;let E=P/1e3;if(h===E)continue;if(h===null&&this.segments.length>0){let C=Q(this.segments),x=C.timestamp+C.duration,_=E-x;for(let F of this.segments)F.unixEpochTimestamp=F.timestamp+_,t&&(F.timestamp=F.unixEpochTimestamp)}h=E,n=E,t&&(s=E)}else if(T===dl)l=null;else if(T.startsWith(ja)){let A=T.slice(ja.length),P=Number(A);if(!Number.isFinite(P)||P<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${A}'.`);this.refreshInterval=P,g=P}else if(T===fl){this.streamHasEnded=!0;break}else T.startsWith(Ka)&&T.slice(Ka.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let s=H(this.segments,e,a=>a.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||i)return this.segments[s];let n=this.segments[s];if(e<n.timestamp+n.duration)return n;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){let i=this.segments.indexOf(e);p(i!==-1);let s=i+1,n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(s<this.segments.length)return this.segments[s];if(this.streamHasEnded||n)return null;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return p(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,i=this.inputCache.find(c=>c.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let s=null;(t.initSegment||t.firstSegment)&&(s=this.getInputForSegment(t.initSegment??t.firstSegment));let n={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes,{psshBox:u}=t.encryption;return(u.keyIds===null||u.keyIds.includes(c.keyId))&&!l.some(d=>Ls(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new ns({source:new rs(t.location.path,async c=>{p(c.isRoot);let l={...c,isRoot:!1},u,d=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(u=await this.input._getSourceCached(l),d){let h=u.source.slice(t.location.offset,t.location.length??void 0).ref();u.free(),u=h}}else if(t.encryption.method==="AES-128"){let f=t.encryption;p(f.iv);let h=await this.input._getSourceCached(l);if(d){let y=h.source.slice(t.location.offset,t.location.length??void 0).ref();h.free(),h=y}let g=new sr(h.source),m=Bc(g,async()=>{let w={stack:[],error:void 0,hasError:!1};try{let y=ml(w,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},gl),!1),S=await new sr(y.source).requestSlice(0,tt);if(!S)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:M(S,tt),iv:f.iv}}catch(y){w.error=y,w.hasError=!0}finally{pl(w)}},()=>{h.free()});u=new is(m).ref()}else p(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof oi)),initInput:s??void 0,formatOptions:n});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){let c=Mr(this.inputCache,l=>l.age);p(c!==-1),this.inputCache.splice(c,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var kn=class extends me{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{p(this.input._rootSource instanceof He);let e=await this.input._reader.requestEntireFile();p(e);let t=yn(e,e.length,{ignore:fn}),{rootPath:i}=this.input._rootSource,s=[],n=[];for(let d=1;d<t.length;d++){let f=t[d];if(f.startsWith(za)){let h=d,g=t[++d];if(g===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let m=ht(i,g),w=new Vt(f.slice(za.length));if(w.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:m,attributes:w,lineNumber:h,hasOnlyKeyPackets:!1})}else if(f.startsWith(Na)){let h=new Vt(f.slice(Na.length)),g=h.get("uri");if(g===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let w=ht(i,g);s.push({fullPath:w,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(Va)){let h=new Vt(f.slice(Va.length));if(h.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(h.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let w=null,y=h.get("uri");y!==null&&(w=ht(i,y)),n.push({fullPath:w,attributes:h,lineNumber:d})}else if(f!==hl){if(f.startsWith(ts)){let h=new ss(this,i,null,t);this.segmentedInputs=[h],this.hasMasterPlaylist=!1,this.trackBackings=await h.getTrackBackings();return}}}let a=[...new Set(n.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(n.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(s.map(async(d,f)=>{let h=[],g=d.attributes.get("codecs"),m;if(g)m=g.split(",").map(x=>x.trim());else{let _=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),F=await Promise.all(_.map(async I=>({track:I,codec:await I.getCodec()})));m=await Promise.all(F.filter(I=>I.codec!==null).map(I=>I.track.getDecoderConfig().then(U=>U.codec)))}let w=d.attributes.get("video"),y=d.attributes.get("audio"),b=m.some(x=>ke.includes(Et(x))),S=m.some(x=>Ie.includes(Et(x)));if(w!==null&&!b){if(!a.includes(w))throw new Error(`Invalid M3U8 file; variant stream references video group "${w}" which is not defined in any #EXT-X-MEDIA tags.`);let x=n.find(_=>{let F=_.attributes.get("group-id"),I=_.attributes.get("type");return F===w&&I.toLowerCase()==="video"});e:if(x){let _=x.attributes.get("uri");if(_===null)break e;let F=ht(i,_),q=(await this.getSegmentedInputForPath(F).getTrackBackings()).find(V=>V.getType()==="video");if(!q||await q.getCodec()===null)break e;let W=await q.getDecoderConfig().then(V=>V?.codec??null);p(W!==null),m.push(W)}}if(y!==null&&!S){if(!o.includes(y))throw new Error(`Invalid M3U8 file; variant stream references audio group "${y}" which is not defined in any #EXT-X-MEDIA tags.`);let x=n.find(_=>{let F=_.attributes.get("group-id"),I=_.attributes.get("type");return F===y&&I.toLowerCase()==="audio"});e:if(x){let _=x.attributes.get("uri");if(_===null)break e;let F=ht(i,_),q=(await this.getSegmentedInputForPath(F).getTrackBackings()).find(V=>V.getType()==="audio");if(!q||await q.getCodec()===null)break e;let W=await q.getDecoderConfig().then(V=>V?.codec??null);p(W!==null),m.push(W)}}m=[...new Set(m)];let T=null,A=null,P=d.attributes.getAsNumber("bandwidth");p(P!==null);let E=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(let x of m){let _=Et(x);if(_!==null){if(ke.includes(_)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");T=x;let F=d.attributes.get("video");if(F===null){let I=d.attributes.get("resolution"),U=null,q=null;if(I){let W=I.match(/^(\d+)x(\d+)$/);W&&(U=Number(W[1]),q=Number(W[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Z,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:E,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:U,height:q}})}else{if(!a.includes(F))throw new Error(`Invalid M3U8 file; variant stream references video group "${F}" which is not defined in any #EXT-X-MEDIA tags.`);for(let I of n){let U=I.attributes.get("group-id"),q=I.attributes.get("type");if(U!==F||q.toLowerCase()!=="video")continue;let W=I.attributes.get("resolution")??d.attributes.get("resolution"),V=null,ce=null;if(W){let Se=W.match(/^(\d+)x(\d+)$/);Se&&(V=Number(Se[1]),ce=Number(Se[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:bn(I.attributes),autoselect:bn(I.attributes)||wl(I.attributes),languageCode:yl(I.attributes.get("language")),lineNumber:I.lineNumber,fullPath:I.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:I.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:V,height:ce}})}}}else if(Ie.includes(_)){if(A!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");A=x;let F=d.attributes.get("audio");if(F===null){let I=d.attributes.get("channels"),U=I!==null?Number(I.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Z,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(f),peakBitrate:P,averageBitrate:E,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:U!==null&&Number.isInteger(U)&&U>0?U:null}})}else{if(!o.includes(F))throw new Error(`Invalid M3U8 file; variant stream references audio group "${F}" which is not defined in any #EXT-X-MEDIA tags.`);for(let I of n){let U=I.attributes.get("group-id"),q=I.attributes.get("type");if(U!==F||q.toLowerCase()!=="audio")continue;let W=I.attributes.get("channels")??d.attributes.get("channels"),V=W!==null?Number(W.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:bn(I.attributes),autoselect:bn(I.attributes)||wl(I.attributes),languageCode:yl(I.attributes.get("language")),lineNumber:I.lineNumber,fullPath:I.fullPath??d.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:I.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:V!==null&&Number.isInteger(V)&&V>0?V:null}})}}}}}return h})),l=[],u=d=>{let f=l.find(h=>h.fullPath===d.fullPath&&h.info.type===d.info.type);f?(f.pairingMask|=d.pairingMask,f.default||=d.default,f.autoselect||=d.autoselect,f.lineNumber=Math.min(f.lineNumber,d.lineNumber),d.peakBitrate!==null&&(f.peakBitrate=Math.max(f.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(f.averageBitrate=Math.max(f.averageBitrate??-1/0,d.averageBitrate)),f.languageCode===Z&&(f.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(let d of c)for(let f of d)u(f);l.sort((d,f)=>d.lineNumber-f.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new An(d)):this.trackBackings.push(new Sn(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),p(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(s=>s.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(n=>n.fullPath===e).map(n=>({id:n.id,type:n.info.type}))),t=new ss(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return dn}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Tn=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,s=(await e.getTrackBackings()).filter(n=>n.getType()===this.getType());if(s.length===1)t=s[0];else if(this instanceof An){for(let n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}else{p(this instanceof Sn);for(let n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...we,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){p(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},An=class extends Tn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Et(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},Sn=class extends Tn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Et(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},bn=r=>{let e=r.get("default");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},wl=r=>{let e=r.get("autoselect");if(e===null)return!1;let t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},yl=r=>{if(r===null)return Z;let e=r.split("-")[0];return e||Z};var Oe=class{constructor(){this._isIsobmff=!1}},as=class extends Oe{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let i=Y(t,4);return i!=="ftyp"&&i!=="styp"?null:Y(t,4)}_createDemuxer(e){return new qs(e)}},xn=class extends as{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let i=e._reader.requestSlice(4,4);if(i instanceof Promise&&(i=await i),!i)return!1;let s=Y(i,4);return s==="moof"||s==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Cn=class extends as{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},os=class extends Oe{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,st);if(i instanceof Promise&&(i=await i),!i)return!1;let s=Aa(i);if(s===null||s<1||s>8||j(i,s)!==k.EBML)return!1;let a=Sa(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;let c=i.filePos;for(;o.filePos<=c+a-Fe;){let l=nt(o);if(!l)break;let{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case k.EBMLVersion:if(j(o,d)!==1)return!1;break;case k.EBMLReadVersion:if(j(o,d)!==1)return!1;break;case k.DocType:if(tr(o,d)!==t)return!1;break;case k.DocTypeVersion:if(j(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new tn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},Pn=class extends os{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},En=class extends Oe{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,Ae);if(d instanceof Promise&&(d=await d),!d)break;let f=Be(d);if(!f)break;t=d.filePos+f.size}let i=await Yi(e._reader,t,t+4096);if(!i)return!1;let s=i.header,n=Qt(s.mpegVersionId,s.channel),a=e._reader.requestSlice(i.startPos+n,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=R(a);if(o===Xt||o===Wr)return!0;t=i.startPos+i.header.totalSize;let l=await Yi(e._reader,t,t+4);if(!l)return!1;let u=l.header;return!(s.channel!==u.channel||s.sampleRate!==u.sampleRate)}_createDemuxer(e){return new sn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},_n=class extends Oe{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let i=Y(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),Y(t,4)==="WAVE")}_createDemuxer(e){return new an(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},In=class extends Oe{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?Y(t,4)==="OggS":!1}_createDemuxer(e){return new nn(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},vn=class extends Oe{async _canReadInput(e){let t=0;for(;;){let s=e._reader.requestSlice(t,Ae);if(s instanceof Promise&&(s=await s),!s)break;let n=Be(s);if(!n)break;t=s.filePos+n.size}let i=e._reader.requestSlice(t,4);return i instanceof Promise&&(i=await i),i?Y(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new cn(e)}},Rn=class extends Oe{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,Ae);if(a instanceof Promise&&(a=await a),!a)break;let o=Be(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,zt,Ne);if(i instanceof Promise&&(i=await i),!i)return!1;let s=De(i);if(!s||(t+=s.frameLength,i=e._reader.requestSliceRange(t,zt,Ne),i instanceof Promise&&(i=await i),!i))return!1;let n=De(i);return n?s.objectType===n.objectType&&s.samplingFrequencyIndex===n.samplingFrequencyIndex&&s.channelConfiguration===n.channelConfiguration:!1}_createDemuxer(e){return new on(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},Fn=class extends Oe{async _canReadInput(e){let t=205,i=e._reader.requestSlice(0,t);if(i instanceof Promise&&(i=await i),!i)return!1;let s=M(i,t);return s[0]===71&&s[188]===71||s[0]===71&&s[204]===71?!0:s[4]===71&&s[196]===71}_createDemuxer(e){return new ln(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},oi=class extends Oe{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(Y(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof He))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new kn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return dn}},bl=new xn,kl=new Cn,Tl=new os,Al=new Pn,Sl=new En,xl=new _n,Cl=new In,Pl=new Rn,El=new vn,_l=new Fn,Il=new oi,ed=[Il,bl,kl,Tl,Al,xl,Cl,El,Sl,Pl,_l];var vl=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var Rl=r=>{let i=r,s=4096,n=0,a=12,o=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&s)!==s&&a>=5;)s>>=1,a--;return o=i>>a-4&15,~(n|a-5<<4|o)&255};var Fl=r=>{let t=2048,i=0,s=11,n=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(i|s-4<<4|n)^85};var Ar=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ci=r=>{if(!Bi(r))throw new TypeError("timestamp must be a number.")},eo=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;let s=await r.determinePacketType(i);return s&&(i.type=s),i}):e,li=class{constructor(e){if(!(e instanceof ui))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Ar(e),this._track.input._disposed)throw new ge;return eo(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Ar(e);let t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(ci(e),Ar(t),this._track.input._disposed)throw new ge;return eo(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Ar(t),this._track.input._disposed)throw new ge;return eo(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(ci(e),Ar(t),this._track.input._disposed)throw new ge;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let i=await this._track._backing.getKeyPacket(e,t);return i&&(p(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i)}async getNextKeyPacket(e,t={}){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Ar(t),this._track.input._disposed)throw new ge;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let i=await this._track._backing.getNextKeyPacket(e,t);return i&&(p(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof X))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof X))throw new TypeError("endPacket must be an EncodedPacket.");if(Ar(i),this._track.input._disposed)throw new ge;let s=[],{promise:n,resolve:a}=ne(),{promise:o,resolve:c}=ne(),l=!1,u=!1,d=null,f=[],h=()=>Math.max(2,f.length);(async()=>{let m=e??await this.getFirstPacket(i);for(;m&&!u&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(s.length>h()){({promise:o,resolve:c}=ne()),await o;continue}s.push(m),a(),{promise:n,resolve:a}=ne(),m=await this.getNextPacket(m,i)}l=!0,a()})().catch(m=>{d||(d=m,a())});let g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new ge;if(u)return{value:void 0,done:!0};if(d)throw d;if(s.length>0){let m=s.shift(),w=performance.now();for(f.push(w);f.length>0&&w-f[0]>=1e3;)f.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}},to=class{constructor(e,t){this.onSample=e,this.onError=t}},Bn=class{mediaSamplesInRange(e=-1/0,t=1/0,i){ci(e),ci(t);let s=[],n=!1,a=null,{promise:o,resolve:c}=ne(),{promise:l,resolve:u}=ne(),d=!1,f=!1,h=!1,g=null,m={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let b=await this._createDecoder(C=>{if(u(),C.timestamp>=t&&(f=!0),f){C.close();return}a&&(C.timestamp>e?(s.push(a),n=!0):a.close()),C.timestamp>=e&&(s.push(C),n=!0),a=n?null:C,s.length>0&&(c(),{promise:o,resolve:c}=ne())},C=>{g||(g=C,c())}),S=this._createPacketSink(),T=await S.getKeyPacket(e,m)??await S.getFirstKeyPacket(m),A=T,E=S.packets(T??void 0,void 0,m);for(await E.next();A&&!f&&!this._track.input._disposed;){let C=Bl(s.length);if(s.length+b.getDecodeQueueSize()>C){({promise:l,resolve:u}=ne()),await l;continue}b.decode(A);let x=await E.next();if(x.done)break;A=x.value}await E.return(),!h&&!this._track.input._disposed&&await b.flush(),b.close(),!n&&a&&s.push(a),d=!0,c()})().catch(b=>{g||(g=b,c())});let w=this._track,y=()=>{a?.close();for(let b of s)b.close()};return{async next(){for(;;){if(w.input._disposed)throw y(),new ge;if(h)return{value:void 0,done:!0};if(g)throw y(),g;if(s.length>0){let b=s.shift();return u(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,u(),c(),y(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Do(e);let i=Mo(e),s=[],n=[],{promise:a,resolve:o}=ne(),{promise:c,resolve:l}=ne(),u=!1,d=!1,f=null,h=y=>{n.push(y),o(),{promise:a,resolve:o}=ne()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let y=await this._createDecoder(C=>{if(l(),d){C.close();return}let x=0;for(;s.length>0&&C.timestamp-s[0]>-1e-10;)x++,s.shift();if(x>0)for(let _=0;_<x;_++)h(_<x-1?C.clone():C);else C.close()},C=>{f||(f=C,o())}),b=this._createPacketSink(),S=null,T=null,A=-1,P=async()=>{p(T);let C=T;for(y.decode(C);C.sequenceNumber<A;){let x=Bl(n.length);for(;n.length+y.getDecodeQueueSize()>x&&!d;)({promise:c,resolve:l}=ne()),await c;if(d)break;let _=await b.getNextPacket(C,g);p(_),y.decode(_),C=_}A=-1},E=async()=>{await y.flush();for(let C=0;C<s.length;C++)h(null);s.length=0};for await(let C of i){if(ci(C),d||this._track.input._disposed)break;let x=await b.getPacket(C,g),_=x&&await b.getKeyPacket(C,g);if(!_){A!==-1&&(await P(),await E()),h(null),S=null;continue}S&&(_.sequenceNumber!==T.sequenceNumber||x.timestamp<S.timestamp)&&(await P(),await E()),s.push(x.timestamp),A=Math.max(x.sequenceNumber,A),S=x,T=_}!d&&!this._track.input._disposed&&(A!==-1&&await P(),await E()),y.close(),u=!0,o()})().catch(y=>{f||(f=y,o())});let m=this._track,w=()=>{for(let y of n)y?.close()};return{async next(){for(;;){if(m.input._disposed)throw w(),new ge;if(d)return{value:void 0,done:!0};if(f)throw w(),f;if(n.length>0){let y=n.shift();return p(y!==void 0),l(),{value:y,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),w(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}},Bl=r=>r===0?40:8,ro=class extends to{constructor(e,t,i,s,n,a){super(e,t),this.codec=i,this.decoderConfig=s,this.rotation=n,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ht,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new Ht;let o=xs.find(c=>c.supports(i,s));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof Ye))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let c=u=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let d=this.alphaQueue.shift();p(d!==void 0),await this.mergeAlpha(u,d)}else this.colorQueue.push(u)}).catch(d=>this.onError(d))};if(i==="avc"&&this.decoderConfig.description&&Ri()){let u=kc(ee(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){let d=Hi(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(p(this.decoder),jt()||ia(this.inputTimestamps,e.timestamp,t=>t),Ri()&&this.currentPacketIndex===0){if(this.codec==="avc"){let t=[];for(let s of ga(e.data,this.decoderConfig)){let n=qr(e.data[s.offset]);n===pe.AUD&&(t.length=0),n>=20&&n<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}let i=yc(t,this.decoderConfig);e=new X(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let t=Sc(e.data,this.decoderConfig);t&&(e=new X(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Mn),!this.alphaDecoder){let i=n=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let a=this.colorQueue.shift();p(a!==void 0),await this.mergeAlpha(a,n)}else this.alphaQueue.push(n);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let a=this.colorQueue.shift();p(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},s=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:n=>{try{i(n)}catch(a){this.onError(a)}},error:n=>{n.stack=s,this.onError(n)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=Jt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Wi(e,this.decoderConfig)){let i=Yt(e[t.offset]);if(i===fe.RASL_N||i===fe.RASL_R)return!0}return!1}sampleHandler(e){if(jt()){if(this.sampleQueue.length>0&&e.timestamp>=Q(this.sampleQueue).timestamp){for(let t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ia(this.sampleQueue,e,t=>t.timestamp)}else{let t=this.inputTimestamps.shift();p(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){let n=new Ye(e);this.sampleHandler(n);return}p(this.merger);let i=await this.merger.update(e,t),s=new Ye(i);this.sampleHandler(s)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),jt()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Ml=!1,Mn=class r{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&e&&!Ml)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");let t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,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)}catch(t){this.gl=null,this.canvas=null,Ml=!0,O._warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){p(this.gl);let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2
|
+
in vec2 a_position;
|
|
3
|
+
in vec2 a_texCoord;
|
|
4
|
+
out vec2 v_texCoord;
|
|
5
|
+
|
|
6
|
+
void main() {
|
|
7
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
8
|
+
v_texCoord = a_texCoord;
|
|
9
|
+
}
|
|
10
|
+
`),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
11
|
+
precision highp float;
|
|
12
|
+
|
|
13
|
+
uniform sampler2D u_colorTexture;
|
|
14
|
+
uniform sampler2D u_alphaTexture;
|
|
15
|
+
in vec2 v_texCoord;
|
|
16
|
+
out vec4 fragColor;
|
|
17
|
+
|
|
18
|
+
void main() {
|
|
19
|
+
vec3 color = texture(u_colorTexture, v_texCoord).rgb;
|
|
20
|
+
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
21
|
+
fragColor = vec4(color, alpha);
|
|
22
|
+
}
|
|
23
|
+
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){p(this.gl);let i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){p(this.gl),p(this.program);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let s=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){p(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),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),e}updateGpu(e,t){p(this.gl),p(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.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,e),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,t),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);let i=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),i}updateCpu(e,t){if(!this.worker){let n=new Blob([`(${td.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(n);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{let c=o.data,l=this.pendingRequests.get(c.id);l&&(this.pendingRequests.delete(c.id),"error"in c?l.reject(new Error(c.error)):l.resolve(c.frame))}),this.worker.addEventListener("error",o=>{let c=new Error(o.message||"Color/alpha merge worker error.");for(let l of this.pendingRequests.values())l.reject(c);this.pendingRequests.clear()})}let i=this.nextRequestId++,s=ne();return this.pendingRequests.set(i,s),this.worker.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),s.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha merger closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};Mn.forceCpu=!0;var td=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{let f=await i(u,d);self.postMessage({id:l,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:l,error:f.message})}finally{u.close(),d.close()}})});let i=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let f=u.includes("P10"),h=u.includes("P12"),g=d.includes("P10"),m=d.includes("P12");if(g!==f||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);let w=c.codedWidth,y=c.codedHeight;if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await s(c,l,w,y,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await n(c,l,w,y,u);if(u==="NV12")return await a(c,l,w,y);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},s=async(c,l,u,d,f)=>{let h=u*d,g=new Uint8Array(h*4);await c.copyTo(g);let m=await o(l,u,d,1);for(let b=0,S=3;b<h;b++,S+=4)g[S]=m[b];let y={format:f==="RGBX"||f==="RGBA"?"RGBA":"BGRA",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,y)},n=async(c,l,u,d,f)=>{let h=f.includes("P10"),g=f.includes("P12"),m=h||g?2:1,w,y;f.startsWith("I420")?(w=Math.ceil(u/2),y=Math.ceil(d/2)):f.startsWith("I422")?(w=Math.ceil(u/2),y=d):(w=u,y=d);let b=u*d,S=w*y,T=b*m,A=S*m,P=b*m,E=T+2*A+P,C=new Uint8Array(E);await c.copyTo(C);let x=await o(l,u,d,m),_=T+2*A;C.set(x,_);let I={format:f.slice(0,4)+"A"+f.slice(4),codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,I)},a=async(c,l,u,d)=>{let f=u*d,h=Math.ceil(u/2),g=Math.ceil(d/2),m=h*g,w=c.allocationSize();(!e||e.byteLength!==w)&&(e=new Uint8Array(w)),await c.copyTo(e);let y=new Uint8Array(f+2*m+f);y.set(e.subarray(0,f),0);let b=f,S=f+m,T=f;for(let E=0;E<m;E++)y[b+E]=e[T+E*2],y[S+E]=e[T+E*2+1];let A=await o(l,u,d,1);y.set(A,f+2*m);let P={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,P)},o=async(c,l,u,d)=>{let f=c.allocationSize();(!r||r.byteLength!==f)&&(r=new Uint8Array(f)),await c.copyTo(r);let h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){let g=h==="RGBA"||h==="RGBX"?0:2,m=l*u;for(let w=0;w<m;w++)r[w]=r[w*4+g];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},rd=r=>{if(!r||typeof r!="object")throw new TypeError("decoderOptions must be an object.");if(r.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r.optimizeForLatency!==void 0&&typeof r.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},io=class extends Bn{constructor(e,t={}){if(!(e instanceof Sr))throw new TypeError("videoTrack must be an InputVideoTrack.");rd(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=await this._track.getCodec(),s=await this._track.getRotation(),n=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return p(i&&n),n={...n,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new ro(e,t,i,n,s,a)}_createPacketSink(){return new li(this._track)}async getSample(e,t={}){ci(e);for await(let i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}};var ui=class r{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Sr}isAudioTrack(){return this instanceof di}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return se(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return se(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return se(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return se(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return se(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),i=(t?.timestamp??0)+(t?.duration??0);return ut(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let i=new li(this),s=1/0,n=-1/0,a=0,o=0;for await(let c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=n)break;s=Math.min(s,c.timestamp),n=Math.max(n,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(n-s)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(n-s)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(nr({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(nr({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(nr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(nr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(nr({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=so(e);let t=await this.input.getTracks();for(let i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&=so(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=so(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},se=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},so=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{let t=s=>{if(typeof s!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return s},i=r(e);return i instanceof Promise?i.then(t):t(i)}:void 0},Sr=class extends ui{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return se(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return se(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return se(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return se(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return se(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return se(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:se(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*se(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:se(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*se(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let s=se(e,"displayWidth","getDisplayWidth");if(s!==null)return s}let i=se(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return se(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let s=se(e,"displayHeight","getDisplayHeight");if(s!==null)return s}let i=se(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return se(i,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return p(t!==null),xs.some(s=>s.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let t=await this.getCodec();if(t===null)return null;let i=await this.getDecoderConfig();return p(i),Jt(t,i,e.data)}},di=class extends ui{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return se(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return se(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return se(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return p(t!==null),la.some(i=>i.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}};var no=r=>-(r??-1/0),fi=r=>-r,hi=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{let t=s=>{if(typeof s!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return s},i=r.filter(e);return i instanceof Promise?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{let t=s=>{if(typeof s!="number"&&(!Array.isArray(s)||!s.every(n=>typeof n=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return s},i=r.sortBy(e);return i instanceof Promise?i.then(t):t(i)}:void 0}},nr=(r,e)=>({filter:r?.filter||e?.filter?t=>{let i=r?.filter?.(t)??!0,s=n=>n===!1?!1:e?.filter?.(t)??!0;return i instanceof Promise?i.then(s):s(i)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{let i=r?.sortBy?.(t)??[],s=e?.sortBy?.(t)??[],n=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([a,o])=>n(a,o)):n(i,s)}:void 0}),Dn=async(r,e)=>{let t=r;if(e?.filter){let a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){let c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;let i=t.map(a=>e.sortBy(a)),n=i.some(a=>a instanceof Promise)?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:n[o]})).sort((a,o)=>{let c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let f=c[d]??0,h=l[d]??0;if(f!==h)return f-h}return 0}).map(a=>a.track)};Br();var id=1,gl=2,ns=class r extends Le{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Oe)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ee||e.source instanceof Tr))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ee&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof r))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&vl(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Ee?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){p(this._rootSource instanceof He);let t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=id){let i=this._sourceCache.find(a=>a.cacheGroup===t&&Ja(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());let s=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Ja(a.request,e));if(s)return s.promise.then(a=>a.sourceRef.source.ref());let n=(async()=>{let a=await this._getSourceUncached(e);if(dr(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){let d=Mr(this._sourceCache,h=>h.cacheGroup===t&&h.sourceRef.source._refCount===1?h.age:1/0);p(d!==-1);let f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),Bo(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);let l=this._sourceCachePromises.findIndex(d=>d.request===e);return p(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(a=>{let o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new sr(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new cs})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),p(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof cs)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(s=>s!==null);if(t.length===0)return 0;let i=await Promise.all(t.map(s=>s.getFirstTimestamp()));return Math.min(...i)}async computeDuration(e,t){e??=await this.getTracks();let i=e.filter(n=>n!==null);if(i.length===0)return 0;let s=await Promise.all(i.map(n=>n.computeDuration(t)));return Math.max(...s)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let i=e.filter(a=>a!==null),n=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return n.length===0?null:Math.max(...n)}async getTracks(e){e&&=hi(e);let i=(await this._getTrackBackings()).map(s=>this._wrapBackingAsTrack(s));return Dn(i,e)}async getVideoTracks(e){e&&=hi(e);let i=(await this.getTracks()).filter(s=>s.isVideoTrack());return Dn(i,e)}async getAudioTracks(e){e&&=hi(e);let i=(await this.getTracks()).filter(s=>s.isAudioTrack());return Dn(i,e)}async getPrimaryVideoTrack(e){e&&=hi(e);let t=nr(e,{sortBy:async s=>[fi((await s.getDisposition()).default),fi(await s.hasPairableAudioTrack()),fi(!await s.hasOnlyKeyPackets()),no(await s.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=hi(e);let t=await this.getPrimaryVideoTrack(),i=nr(e,{sortBy:async n=>[fi(!t||n.canBePairedWith(t)),fi((await n.getDisposition()).default),no(await n.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let s=e.getType()==="video"?new Sr(this,e):new di(this,e);return this._backingToTrack.set(e,s),s}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},cs=class extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}},ge=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}};var sr=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new ge;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let n=new Uint8Array(0);return new ye(n,L(n),0,e,e)}let i=e+t,s=this.source._read(e,i,Ya,Za);return s instanceof Promise?s.then(n=>n?new ye(n.bytes,n.view,n.offset,e,i):null):s?new ye(s.bytes,s.view,s.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new ge;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,ue(this.fileSizeNonStrict-e,t,i));{let s=this.requestSlice(e,i),n=a=>a||(p(this.fileSizeNonStrict!==null),this.requestSlice(e,ue(this.fileSizeNonStrict-e,t,i)));return s instanceof Promise?s.then(n):n(s)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let e=1024;return(async()=>{let t=[],i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;let o=M(a,a.length);t.push(o),i+=a.length}let s=new Uint8Array(i),n=0;for(let a of t)s.set(a,n),n+=a.length;return new ye(s,L(s),0,0,i)})()}},ye=class r{constructor(e,t,i,s,n){this.bytes=e,this.view=t,this.offset=i,this.start=s,this.end=n,this.bufferPos=s-i}static tempFromBytes(e){return new r(e,L(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new r(this.bytes,this.view,this.offset,e,e+t)}},Ue=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},M=(r,e)=>{Ue(r,e);let t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},D=r=>(Ue(r,1),r.view.getUint8(r.bufferPos++)),ni=(r,e)=>{Ue(r,2);let t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},re=r=>{Ue(r,2);let e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},rt=r=>{Ue(r,3);let e=Ei(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Ki=r=>{Ue(r,2);let e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},Ut=(r,e)=>{Ue(r,4);let t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},R=r=>{Ue(r,4);let e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},wr=r=>{Ue(r,4);let e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Ft=r=>{Ue(r,4);let e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},sd=r=>{Ue(r,4);let e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Fa=(r,e)=>{let t,i;return e?(t=Ut(r,!0),i=Ut(r,!0)):(i=Ut(r,!1),t=Ut(r,!1)),i*4294967296+t},Re=r=>{let e=R(r),t=R(r);return e*4294967296+t},Nc=r=>{let e=Ft(r),t=R(r);return e*4294967296+t},Jc=r=>{let e=wr(r);return sd(r)*4294967296+e},qc=r=>{Ue(r,4);let e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},Xs=r=>{Ue(r,8);let e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},Y=(r,e)=>{Ue(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},yn=(r,e,t)=>he.decode(M(r,e)).split(`
|
|
24
|
+
`).map(n=>n.trim()).filter(n=>n.length>0&&!t?.ignore?.(n));var xr;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(xr||(xr={}));var be;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(be||(be={}));var Zi=128,Ae=10,pi=["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"],jc=(r,e)=>{let t=r.filePos;e.raw??={},e.raw.TAG??=M(r,Zi-3),r.filePos=t;let i=mi(r,30);i&&(e.title??=i);let s=mi(r,30);s&&(e.artist??=s);let n=mi(r,30);n&&(e.album??=n);let a=mi(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));let c=M(r,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(e.trackNumber??=d),r.skip(-30),l=mi(r,28),r.skip(2)}else r.skip(-30),l=mi(r,30);l&&(e.comment??=l);let u=D(r);u<pi.length&&(e.genre??=pi[u])},mi=(r,e)=>{let t=M(r,e),i=ur(t.indexOf(0),t.length),s=t.subarray(0,i),n="";for(let a=0;a<s.length;a++)n+=String.fromCharCode(s[a]);return n.trimEnd()},Be=r=>{let e=r.filePos,t=Y(r,3),i=D(r),s=D(r),n=D(r),a=R(r);if(t!=="ID3"||i===255||s===255||(a&2155905152)!==0)return r.filePos=e,null;let o=vs(a);return n&xr.Footer&&(o+=Ae),{majorVersion:i,revision:s,flags:n,size:o}},rr=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){O._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}let i=e.flags&xr.Footer?e.size-Ae:e.size,s=M(r,i),n=new ao(e,s);if(e.flags&xr.Unsynchronisation&&e.majorVersion===3&&n.ununsynchronizeAll(),e.flags&xr.ExtendedHeader){let a=n.readU32();e.majorVersion===3?n.pos+=a:n.pos+=a-4}for(;n.pos<=n.bytes.length-n.frameHeaderSize();){let a=n.readId3V2Frame();if(!a)break;let o=n.pos,c=n.pos+a.size,l=!1,u=!1,d=!1;if(e.majorVersion===3?(l=!!(a.flags&64),u=!!(a.flags&128)):e.majorVersion===4&&(l=!!(a.flags&4),u=!!(a.flags&8),d=!!(a.flags&2)||!!(e.flags&xr.Unsynchronisation)),l){O._warn(`Skipping encrypted ID3v2 frame ${a.id}`),n.pos=c;continue}if(u){O._warn(`Skipping compressed ID3v2 frame ${a.id}`),n.pos=c;continue}if(d&&n.ununsynchronizeRegion(n.pos,c),t.raw??={},a.id==="TXXX"){let f=t.raw.TXXX??={},h=n.readId3V2TextEncoding(),g=n.readId3V2Text(h,c),m=n.readId3V2Text(h,c);f[g]??=m}else a.id[0]==="T"?t.raw[a.id]??=n.readId3V2EncodingAndText(c):t.raw[a.id]??=n.readBytes(a.size);switch(n.pos=o,a.id){case"TIT2":case"TT2":t.title??=n.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":t.description??=n.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":t.artist??=n.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":t.album??=n.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":t.albumArtist??=n.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let h=n.readId3V2EncodingAndText(c).split("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(t.trackNumber??=g),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{let h=n.readId3V2EncodingAndText(c).split("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(t.discNumber??=g),m&&Number.isInteger(m)&&m>0&&(t.discsTotal??=m)}break;case"TCON":case"TCO":{let f=n.readId3V2EncodingAndText(c),h=/^\((\d+)\)/.exec(f);if(h){let g=Number.parseInt(h[1]);if(pi[g]!==void 0){t.genre??=pi[g];break}}if(h=/^\d+$/.exec(f),h){let g=Number.parseInt(h[0]);if(pi[g]!==void 0){t.genre??=pi[g];break}}t.genre??=f}break;case"TDRC":case"TDAT":{let f=n.readId3V2EncodingAndText(c),h=new Date(f);Number.isNaN(h.getTime())||(t.date??=h)}break;case"TYER":case"TYE":{let f=n.readId3V2EncodingAndText(c),h=Number.parseInt(f,10);Number.isInteger(h)&&(t.date??=new Date(String(h)))}break;case"USLT":case"ULT":{let f=n.readU8();n.pos+=3,n.readId3V2Text(f,c),t.lyrics??=n.readId3V2Text(f,c)}break;case"COMM":case"COM":{let f=n.readU8();n.pos+=3,n.readId3V2Text(f,c),t.comment??=n.readId3V2Text(f,c)}break;case"APIC":case"PIC":{let f=n.readId3V2TextEncoding(),h;if(e.majorVersion===2){let y=n.readAscii(3);h=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else h=n.readId3V2Text(f,c);let g=n.readU8(),m=n.readId3V2Text(f,c).trimEnd(),w=c-n.pos;if(w>=0){let y=n.readBytes(w);t.images||(t.images=[]),t.images.push({data:y,mimeType:h,kind:g===3?"coverFront":g===4?"coverBack":"unknown",description:m})}}break;default:n.pos+=a.size;break}n.pos=c}},ao=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let i=this.bytes[t];e.push(i),i===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let i=[];for(let a=e;a<t;a++){let o=this.bytes[a];i.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}let s=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(s.length+i.length+n.length),this.bytes.set(s,0),this.bytes.set(i,s.length),this.bytes.set(n,s.length+i.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);if(e==="\0\0\0")return null;let t=this.readU24();return{id:e,size:t,flags:0}}else{let e=this.readAscii(4);if(e==="\0\0\0\0")return null;let t=this.readU32(),i=this.header.majorVersion===4?vs(t):t,s=this.readU16(),n=this.pos,a=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(i)){let o=this.header.majorVersion===4?t:vs(t);a(o)&&(i=o)}return this.pos=n,{id:e,size:i,flags:s}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let i=this.pos,s=this.readBytes(t-this.pos);switch(e){case be.ISO_8859_1:{let n="";for(let a=0;a<s.length;a++){let o=s[a];if(o===0){this.pos=i+a+1;break}n+=String.fromCharCode(o)}return n}case be.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){let n=new TextDecoder("utf-16le"),a=ur(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){let n=new TextDecoder("utf-16be"),a=ur(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{let n=ur(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),he.decode(s.subarray(0,n))}case be.UTF_16_BE_NO_BOM:{let n=new TextDecoder("utf-16be"),a=ur(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case be.UTF_8:{let n=ur(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),he.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},gi=class{constructor(e){this.helper=new Uint8Array(8),this.helperView=L(this.helper),this.writer=e}writeId3V2Tag(e){let t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let i=this.writer.getPos(),s=new Set;for(let{key:o,value:c}of ft(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),s.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),s.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),s.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),s.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),s.add("TPE2");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),s.add("TRCK")}break;case"discNumber":{let l=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),s.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),s.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),s.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(c),s.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),s.add("COMM");break;case"images":{let l={coverFront:3,coverBack:4,unknown:0};for(let u of c){let d=l[u.kind]??0,f=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,f,u.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:le(o)}if(e.raw)for(let o in e.raw){let c=e.raw[o];if(c==null||o.length!==4||s.has(o))continue;let l;if(typeof c=="string")if(je(c)){l=new Uint8Array(c.length+2),l[0]=be.ISO_8859_1;for(let d=0;d<c.length;d++)l[d+1]=c.charCodeAt(d)}else{let d=te.encode(c);l=new Uint8Array(d.byteLength+2),l[0]=be.UTF_8,l.set(d,1)}else if(c instanceof Uint8Array)l=c;else if(o==="TXXX"&&gs(c)){for(let u in c){let d=c[u],f=je(u)&&je(d),h=f?null:te.encode(u),g=f?null:te.encode(d),m=f?u.length:h.byteLength,w=f?d.length:g.byteLength,y=1+m+1+w+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(y),this.writeU16(0),this.writeU8(f?be.ISO_8859_1:be.UTF_8),f?(this.writeIsoString(u),this.writeIsoString(d)):(this.writer.write(h),this.writeU8(0),this.writer.write(g),this.writeU8(0))}continue}else continue;this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}let n=this.writer.getPos(),a=n-i;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(n),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(hc(e))}writeIsoString(e){let t=new Uint8Array(e.length+1);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);this.writer.write(t)}writeUtf8String(e){let t=te.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){let i=je(t),n=1+(i?t.length:te.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(i?be.ISO_8859_1:be.UTF_8),i?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){let t=je(e),i="",s=4+i.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?be.ISO_8859_1:be.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let t=je(e),i=t?e.length:te.encode(e).byteLength,s="",n=4+s.length+1+i+1;this.writeAscii("COMM"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?be.ISO_8859_1:be.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(s),this.writeIsoString(e)):(this.writeUtf8String(s),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,i,s){let n=je(e)&&je(i),a=n?i.length:te.encode(i).byteLength,o=1+e.length+1+1+a+1+s.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(n?be.ISO_8859_1:be.UTF_8),n?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),n?this.writeIsoString(i):this.writeUtf8String(i),this.writer.write(s)}};var wt=class{constructor(e){this.mutex=new _e,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let s=this.trackTimestampInfo.get(e);if(s){if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),s.maxTimestampBeforeLastKeyPacket!==null&&t<s.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${s.maxTimestampBeforeLastKeyPacket}s.`);s.maxTimestamp=Math.max(s.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,s)}}};var wi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var nd=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Dl=r=>{let e=nd.exec(r);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},On=r=>{let e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),s=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};var Cr=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let n of e.children)n&&this.writeBox(n);let i=this.writer.getPos(),s=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,s),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);p(t!==void 0);let i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let i of e.children)i&&(t+=this.measureBox(i));return t}}},K=new Uint8Array(8),Ge=new DataView(K.buffer),oe=r=>[(r%256+256)%256],N=r=>(Ge.setUint16(0,r,!1),[K[0],K[1]]),uo=r=>(Ge.setInt16(0,r,!1),[K[0],K[1]]),zl=r=>(Ge.setUint32(0,r,!1),[K[1],K[2],K[3]]),v=r=>(Ge.setUint32(0,r,!1),[K[0],K[1],K[2],K[3]]),Lt=r=>(Ge.setInt32(0,r,!1),[K[0],K[1],K[2],K[3]]),kt=r=>(Ge.setUint32(0,Math.floor(r/2**32),!1),Ge.setUint32(4,r,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),ad=r=>(Ge.setInt32(0,Math.floor(r/2**32),!1),Ge.setUint32(4,r,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Nl=r=>(Ge.setInt16(0,2**8*r,!1),[K[0],K[1]]),ot=r=>(Ge.setInt32(0,2**16*r,!1),[K[0],K[1],K[2],K[3]]),oo=r=>(Ge.setInt32(0,2**30*r,!1),[K[0],K[1],K[2],K[3]]),co=(r,e)=>{let t=[],i=r;do{let s=i&127;i>>=7,t.length>0&&(s|=128),t.push(s),e!==void 0&&e--}while(i>0||e);return t.reverse()},J=(r,e=!1)=>{let t=Array(r.length).fill(null).map((i,s)=>r.charCodeAt(s));return e&&t.push(0),t},Vl=r=>{let e=r*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Ll=Vl(0),Wl=r=>[ot(r[0]),ot(r[1]),oo(r[2]),ot(r[3]),ot(r[4]),oo(r[5]),ot(r[6]),ot(r[7]),oo(r[8])],z=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),$=(r,e,t,i,s)=>z(r,[oe(e),zl(t),i??[]],s),Hl=r=>r.isQuickTime?z("ftyp",[J("qt "),v(512),J("qt ")]):r.fragmented?r.cmaf?z("ftyp",[J("iso5"),v(512),J("iso5"),J("iso6"),J("mp41"),J("cmfc"),J("dash")]):z("ftyp",[J("iso5"),v(512),J("iso5"),J("iso6"),J("mp41")]):z("ftyp",[J("isom"),v(512),J("isom"),r.holdsAvc?J("avc1"):[],J("mp41")]),fo=()=>z("styp",[J("iso5"),v(0),J("iso5"),J("iso6"),J("mp41"),J("cmfc"),J("dash")]),ho=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),$("sidx",1,0,[v(1),v(qe),kt(ie(r.minWrittenTimestamp,qe)),kt(0),N(0),N(1),v(e&2147483647),v(ie(t,qe)),v(0)])},ls=r=>({type:"mdat",largeSize:r}),ql=r=>({type:"free",size:r}),yi=r=>z("moov",void 0,[od(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>cd(e,r.creationTime)),r.isFragmented?Kd(r.trackDatas):null,rf(r)]),od=(r,e)=>{let t=Math.max(0,...e.map(a=>ie(Un(a),qe)+ie(a.startTimestampOffset??0,qe))),i=Math.max(0,...e.map(a=>a.track.id))+1,s=!Tt(r)||!Tt(t),n=s?kt:v;return $("mvhd",+s,0,[n(r),n(r),v(qe),n(t),ot(1),Nl(1),Array(10).fill(0),Wl(Ll),Array(24).fill(0),v(i)])},Un=r=>{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<r.samples.length;i++){let s=r.samples[i];s.timestamp<e&&(e=s.timestamp),s.timestamp+s.duration>t&&(t=s.timestamp+s.duration)}return e===1/0?0:t-e},cd=(r,e)=>{let t=Jl(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return z("trak",void 0,[ld(r,e),i?ud(r,r.startTimestampOffset):null,dd(r,e),t.name!==void 0?z("udta",void 0,[z("name",[...te.encode(t.name)])]):null])},ld=(r,e)=>{let t=ie(Un(r),qe)+ie(r.startTimestampOffset??0,qe),i=!Tt(e)||!Tt(t),s=i?kt:v,n;if(r.type==="video"){let o=r.track.metadata.rotation;n=Vl(o??0)}else n=Ll;let a=2;return r.track.metadata.disposition?.default!==!1&&(a|=1),$("tkhd",+i,a,[s(e),s(e),v(r.track.id),v(0),s(t),Array(8).fill(0),N(0),N(r.track.id),Nl(r.type==="audio"?1:0),N(0),Wl(n),ot(r.type==="video"?r.info.width:0),ot(r.type==="video"?r.info.height:0)])},ud=(r,e)=>{let t=ie(e,qe),i=ie(Un(r),qe),s=!Tt(t)||!Tt(i),n=s?kt:v,a=s?ad:Lt;return z("edts",void 0,[$("elst",s?1:0,0,[v(2),n(t),a(-1),ot(1),n(i),a(0),ot(1)])])},dd=(r,e)=>z("mdia",void 0,[fd(r,e),mo(!0,hd[r.type],md[r.type]),pd(r)]),fd=(r,e)=>{let t=ie(Un(r),r.timescale),i=!Tt(e)||!Tt(t),s=i?kt:v;return $("mdhd",+i,0,[s(e),s(e),v(r.timescale),s(t),N(Zl(r.track.metadata.languageCode??Z)),N(0)])},hd={video:"vide",audio:"soun",subtitle:"text"},md={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},mo=(r,e,t,i="\0\0\0\0")=>$("hdlr",0,0,[r?J("mhlr"):v(0),J(e),J(i),v(0),v(0),J(t,!0)]),pd=r=>z("minf",void 0,[bd[r.type](),kd(),Sd(r)]),gd=()=>$("vmhd",0,1,[N(0),N(0),N(0),N(0)]),wd=()=>$("smhd",0,0,[N(0),N(0)]),yd=()=>$("nmhd",0,0),bd={video:gd,audio:wd,subtitle:yd},kd=()=>z("dinf",void 0,[Td()]),Td=()=>$("dref",0,0,[v(1)],[Ad()]),Ad=()=>$("url ",0,1),Sd=r=>{let e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return z("stbl",void 0,[xd(r),Vd(r),e?Gd(r):null,e?jd(r):null,Wd(r),Hd(r),qd(r),Ld(r)])},xd=r=>{let e;if(r.type==="video")e=Cd(of(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){let t=Yl(r.track.source._codec,r.muxer.isQuickTime);p(t),e=Rd(t,r)}else r.type==="subtitle"&&(e=zd(uf[r.track.source._codec],r));return p(e),$("stsd",0,0,[v(1)],[e])},Cd=(r,e)=>z(r,[Array(6).fill(0),N(1),N(0),N(0),Array(12).fill(0),N(e.info.width),N(e.info.height),v(4718592),v(4718592),v(0),N(1),Array(32).fill(0),N(24),uo(65535)],[cf[e.track.source._codec](e),Pd(e),fs(e.info.decoderConfig.colorSpace)?Ed(e):null]),Pd=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:z("pasp",[v(r.info.pixelAspectRatio.num),v(r.info.pixelAspectRatio.den)]),Ed=r=>z("colr",[J(r.muxer.isQuickTime?"nclc":"nclx"),N(Ke[r.info.decoderConfig.colorSpace.primaries]),N(Xe[r.info.decoderConfig.colorSpace.transfer]),N(Qe[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:oe((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),_d=r=>r.info.decoderConfig&&z("avcC",[...ee(r.info.decoderConfig.description)]),Id=r=>r.info.decoderConfig&&z("hvcC",[...ee(r.info.decoderConfig.description)]),Ol=r=>{if(!r.info.decoderConfig)return null;let e=r.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),s=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?Ke[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):e.colorSpace?.transfer?Xe[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Qe[e.colorSpace.matrix]:2;return $("vpcC",1,0,[oe(i),oe(s),oe(c),oe(l),oe(u),oe(d),N(0)])},vd=r=>z("av1C",ws(r.info.decoderConfig.codec)),Rd=(r,e)=>{let t=0,i,s=16,n=ae.includes(e.track.source._codec);if(n){let a=e.track.source._codec,{sampleSize:o}=xe(a);s=8*o,s>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),N(1),N(t),N(0),v(0),N(e.info.numberOfChannels),N(s),N(0),N(0),N(e.info.sampleRate<2**16?e.info.sampleRate:0),N(0)];else{let a=n?0:-2;i=[Array(6).fill(0),N(1),N(t),N(0),v(0),N(e.info.numberOfChannels),N(Math.min(s,16)),uo(a),N(0),N(e.info.sampleRate<2**16?e.info.sampleRate:0),N(0),n?[v(1),v(s/8),v(e.info.numberOfChannels*s/8)]:[v(0),v(0),v(0)],v(2)]}return z(r,i,[lf(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},lo=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...oe(e),...oe(21),...zl(0),...v(0),...v(0)];if(r.info.decoderConfig.description){let i=ee(r.info.decoderConfig.description);t=[...t,...oe(5),...co(i.byteLength),...i]}return t=[...N(1),...oe(0),...oe(4),...co(t.length),...t,...oe(6),...oe(1),...oe(2)],t=[...oe(3),...co(t.length),...t],$("esds",0,0,t)},ar=r=>z("wave",void 0,[Fd(r),Bd(r),z("\0\0\0\0")]),Fd=r=>z("frma",[J(Yl(r.track.source._codec,r.muxer.isQuickTime))]),Bd=r=>{let{littleEndian:e}=xe(r.track.source._codec);return z("enda",[N(+e)])},Md=r=>{let e=r.info.numberOfChannels,t=3840,i=r.info.sampleRate,s=0,n=0,a=new Uint8Array(0),o=r.info.decoderConfig?.description;if(o){p(o.byteLength>=18);let c=ee(o),l=Kr(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return z("dOps",[oe(0),oe(e),N(t),v(i),uo(s),oe(n),...a])},Dd=r=>{let e=r.info.decoderConfig?.description;p(e);let t=ee(e);return $("dfLa",0,0,[...t.subarray(4)])},yt=r=>{let{littleEndian:e,sampleSize:t}=xe(r.track.source._codec),i=+e;return $("pcmC",0,0,[oe(i),oe(8*t)])},Od=r=>{let e=Ds(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let t=new Uint8Array(3),i=new G(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),z("dac3",[...t])},Ud=r=>{let e=Os(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(let a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;let i=Math.ceil(t/8),s=new Uint8Array(i),n=new G(s);n.writeBits(13,e.dataRate),n.writeBits(3,e.substreams.length-1);for(let a of e.substreams)n.writeBits(2,a.fscod),n.writeBits(5,a.bsid),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(3,a.bsmod),n.writeBits(3,a.acmod),n.writeBits(1,a.lfeon),n.writeBits(3,0),n.writeBits(4,a.numDepSub),a.numDepSub>0?n.writeBits(9,a.chanLoc):n.writeBits(1,0);return z("dec3",[...s])},zd=(r,e)=>z(r,[Array(6).fill(0),N(1)],[df[e.track.source._codec](e)]),Nd=r=>z("vttC",[...te.encode(r.info.config.description)]);var Vd=r=>$("stts",0,0,[v(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[v(e.sampleCount),v(e.sampleDelta)])]),Ld=r=>{if(r.samples.every(t=>t.type==="key"))return null;let e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return $("stss",0,0,[v(e.length),e.map(([t])=>v(t+1))])},Wd=r=>$("stsc",0,0,[v(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[v(e.firstChunk),v(e.samplesPerChunk),v(1)])]),Hd=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){let{sampleSize:e}=xe(r.track.source._codec);return $("stsz",0,0,[v(e*r.info.numberOfChannels),v(r.samples.reduce((t,i)=>t+ie(i.duration,r.timescale),0))])}return $("stsz",0,0,[v(0),v(r.samples.length),r.samples.map(e=>v(e.size))])},qd=r=>r.finalizedChunks.length>0&&Q(r.finalizedChunks).offset>=2**32?$("co64",0,0,[v(r.finalizedChunks.length),r.finalizedChunks.map(e=>kt(e.offset))]):$("stco",0,0,[v(r.finalizedChunks.length),r.finalizedChunks.map(e=>v(e.offset))]),Gd=r=>$("ctts",1,0,[v(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[v(e.sampleCount),Lt(e.sampleCompositionTimeOffset)])]),jd=r=>{let e=1/0,t=-1/0,i=1/0,s=-1/0;p(r.compositionTimeOffsetTable.length>0),p(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){let o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){let o=r.samples[a];i=Math.min(i,ie(o.timestamp,r.timescale)),s=Math.max(s,ie(o.timestamp+o.duration,r.timescale))}let n=Math.max(-e,0);return s>=2**31?null:$("cslg",0,0,[Lt(n),Lt(e),Lt(t),Lt(i),Lt(s)])},Kd=r=>z("mvex",void 0,r.map(Xd)),Xd=r=>$("trex",0,0,[v(r.track.id),v(1),v(0),v(0),v(0)]),po=(r,e)=>z("moof",void 0,[Qd(r),...e.map($d)]),Qd=r=>$("mfhd",0,0,[v(r)]),Gl=r=>{let e=0,t=0,i=0,s=0,n=r.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|i<<8|s},$d=r=>z("traf",void 0,[Yd(r),Zd(r),Jd(r)]),Yd=r=>{p(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;let t=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Gl(t)};return $("tfhd",0,e,[v(r.track.id),v(i.duration),v(i.size),v(i.flags)])},Zd=r=>(p(r.currentChunk),$("tfdt",1,0,[kt(ie(r.currentChunk.startTimestamp,r.timescale))])),Jd=r=>{p(r.currentChunk);let e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),i=r.currentChunk.samples.map(Gl),s=r.currentChunk.samples.map(m=>ie(m.timestamp-m.decodeTimestamp,r.timescale)),n=new Set(e),a=new Set(t),o=new Set(i),c=new Set(s),l=o.size===2&&i[0]!==i[1],u=n.size>1,d=a.size>1,f=!l&&o.size>1,h=c.size>1||[...c].some(m=>m!==0),g=0;return g|=1,g|=4*+l,g|=256*+u,g|=512*+d,g|=1024*+f,g|=2048*+h,$("trun",1,g,[v(r.currentChunk.samples.length),v(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?v(i[0]):[],r.currentChunk.samples.map((m,w)=>[u?v(e[w]):[],d?v(t[w]):[],f?v(i[w]):[],h?Lt(s[w]):[]])])},jl=r=>z("mfra",void 0,[...r.map(ef),tf()]),ef=(r,e)=>$("tfra",1,0,[v(r.track.id),v(63),v(r.finalizedChunks.length),r.finalizedChunks.map(i=>[kt(ie(i.samples[0].timestamp,r.timescale)),kt(i.moofOffset),v(e+1),v(1),v(1)])]),tf=()=>$("mfro",0,0,[v(0)]),Kl=()=>z("vtte"),Xl=(r,e,t,i,s)=>z("vttc",void 0,[s!==null?z("vsid",[Lt(s)]):null,t!==null?z("iden",[...te.encode(t)]):null,e!==null?z("ctim",[...te.encode(On(e))]):null,i!==null?z("sttg",[...te.encode(i)]):null,z("payl",[...te.encode(r)])]),Ql=r=>z("vtta",[...te.encode(r)]),rf=r=>{let e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){let s=nf(i);s&&e.push(s)}else if(t==="mdta"){let s=af(i);s&&e.push(s)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&sf(e,r.output._metadataTags);return e.length===0?null:z("udta",void 0,e)},sf=(r,e)=>{for(let{key:t,value:i}of ft(e))switch(t){case"title":r.push(bt("\xA9nam",i));break;case"description":r.push(bt("\xA9des",i));break;case"artist":r.push(bt("\xA9ART",i));break;case"album":r.push(bt("\xA9alb",i));break;case"albumArtist":r.push(bt("albr",i));break;case"genre":r.push(bt("\xA9gen",i));break;case"date":r.push(bt("\xA9day",i.toISOString().slice(0,10)));break;case"comment":r.push(bt("\xA9cmt",i));break;case"lyrics":r.push(bt("\xA9lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:le(t)}if(e.raw)for(let t in e.raw){let i=e.raw[t];i==null||t.length!==4||r.some(s=>s.type===t)||(typeof i=="string"?r.push(bt(t,i)):i instanceof Uint8Array&&r.push(z(t,Array.from(i))))}},bt=(r,e)=>{let t=te.encode(e);return z(r,[N(t.length),N(Zl("und")),Array.from(t)])},Ul={"image/jpeg":13,"image/png":14,"image/bmp":27},$l=(r,e)=>{let t=[];for(let{key:i,value:s}of ft(r))switch(i){case"title":t.push({key:e?"title":"\xA9nam",value:at(s)});break;case"description":t.push({key:e?"description":"\xA9des",value:at(s)});break;case"artist":t.push({key:e?"artist":"\xA9ART",value:at(s)});break;case"album":t.push({key:e?"album":"\xA9alb",value:at(s)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:at(s)});break;case"comment":t.push({key:e?"comment":"\xA9cmt",value:at(s)});break;case"genre":t.push({key:e?"genre":"\xA9gen",value:at(s)});break;case"lyrics":t.push({key:e?"lyrics":"\xA9lyr",value:at(s)});break;case"date":t.push({key:e?"date":"\xA9day",value:at(s.toISOString().slice(0,10))});break;case"images":for(let n of s)n.kind==="coverFront"&&t.push({key:"covr",value:z("data",[v(Ul[n.mimeType]??0),v(0),Array.from(n.data)])});break;case"trackNumber":if(e){let n=r.tracksTotal!==void 0?`${s}/${r.tracksTotal}`:s.toString();t.push({key:"track",value:at(n)})}else t.push({key:"trkn",value:z("data",[v(0),v(0),N(0),N(s),N(r.tracksTotal??0),N(0)])});break;case"discNumber":e||t.push({key:"disc",value:z("data",[v(0),v(0),N(0),N(s),N(r.discsTotal??0),N(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:le(i)}if(r.raw)for(let i in r.raw){let s=r.raw[i];s==null||!e&&i.length!==4||t.some(n=>n.key===i)||(typeof s=="string"?t.push({key:i,value:at(s)}):s instanceof Uint8Array?t.push({key:i,value:z("data",[v(0),v(0),Array.from(s)])}):s instanceof Ze&&t.push({key:i,value:z("data",[v(Ul[s.mimeType]??0),v(0),Array.from(s.data)])}))}return t},nf=r=>{let e=$l(r,!1);return e.length===0?null:$("meta",0,0,void 0,[mo(!1,"mdir","","appl"),z("ilst",void 0,e.map(t=>z(t.key,void 0,[t.value])))])},af=r=>{let e=$l(r,!0);return e.length===0?null:z("meta",void 0,[mo(!1,"mdta",""),$("keys",0,0,[v(e.length)],e.map(t=>z("mdta",[...te.encode(t.key)]))),z("ilst",void 0,e.map((t,i)=>{let s=String.fromCharCode(...v(i+1));return z(s,void 0,[t.value])}))])},at=r=>z("data",[v(1),v(0),...te.encode(r)]),of=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},cf={avc:_d,hevc:Id,vp8:Ol,vp9:Ol,av1:vd},Yl=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},lf=(r,e)=>{switch(r){case"aac":return lo;case"mp3":return lo;case"opus":return Md;case"vorbis":return lo;case"flac":return Dd;case"ac3":return Od;case"eac3":return Ud}if(e)switch(r){case"pcm-s24":return ar;case"pcm-s24be":return ar;case"pcm-s32":return ar;case"pcm-s32be":return ar;case"pcm-f32":return ar;case"pcm-f32be":return ar;case"pcm-f64":return ar;case"pcm-f64be":return ar}else switch(r){case"pcm-s16":return yt;case"pcm-s16be":return yt;case"pcm-s24":return yt;case"pcm-s24be":return yt;case"pcm-s32":return yt;case"pcm-s32be":return yt;case"pcm-f32":return yt;case"pcm-f32be":return yt;case"pcm-f64":return yt;case"pcm-f64be":return yt}return null},uf={webvtt:"wvtt"},df={webvtt:Nd},Zl=r=>{p(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};var Pr=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){p(!this.started),this.target._start(),this.started=!0}write(e){p(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let i=t+e.byteLength-this.trackedStart,s=this.trackedWrites.byteLength;for(;s<i;)s*=2;if(s!==this.trackedWrites.byteLength){let n=new Uint8Array(s);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}};var ze=class extends Le{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new zn(this,e)}},go=2**16,wo=2**32,Er=class extends ze{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(go,{maxByteLength:wo})}catch{this._buffer=new ArrayBuffer(go),this._supportsResize=!1}else this._buffer=new ArrayBuffer(go);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>wo)throw new Error(`ArrayBuffer exceeded maximum size of ${wo} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let i=new ArrayBuffer(t),s=new Uint8Array(i);s.set(this._bytes,0),this._buffer=i,this._bytes=s}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},ff=2**24,hf=2,yo=class extends ze{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??ff}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let i=t-this._lastWriteEnd;this._write(new Uint8Array(i),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(p(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((i,s)=>i.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){let s=e[e.length-1],n=t[i];n.start<=s.start+s.size?s.size=Math.max(s.size,n.start+n.data.byteLength-s.start):e.push({start:n.start,size:n.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let s of this._sections)i.start<=s.start&&s.start<i.start+i.size&&i.data.set(s.data,s.start-i.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(i.data,i.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&i.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data,position:i.start}).catch(s=>{this._writeError??=s}),this._lastFlushEnd=i.start+i.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let i=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);i===-1&&(i=this._createChunk(t));let s=this._chunks[i],n=t-s.start,a=e.subarray(0,Math.min(this._chunkSize-n,e.byteLength));s.data.set(a,n);let o={start:n,end:n+a.byteLength};if(this._insertSectionIntoChunk(s,o),s.written[0].start===0&&s.written[0].end===this._chunkSize&&(s.shouldFlush=!0),this._chunks.length>hf){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let i=0,s=e.written.length-1,n=-1;for(;i<=s;){let a=Math.floor(i+(s-i+1)/2);e.written[a].start<=t.start?(i=a+1,n=a):s=a-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}_createChunk(e){let i={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(i),this._chunks.sort((s,n)=>s.start-n.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){p(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let i=this._chunks[t];if(!(!i.shouldFlush&&!e)){for(let s of i.written){let n=i.start+s.start;if(this._monotonicity===!0&&n!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data.subarray(s.start,s.end),position:n}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=i.start+s.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;p(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}};var zn=class extends ze{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},_r=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}};var qe=57600,mf=2082844800,Jl=r=>{let e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},ie=(r,e,t=!0)=>{let i=r*e;return t?Math.round(i):i},Nn=class extends wt{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Er,this.auxWriter=new Pr(this.auxTarget,!1),this.auxBoxWriter=new Cr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ne(),this.creationTime=Math.floor(Date.now()/1e3)+mf,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof ki,this.isCmaf=t instanceof bi,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof bi?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":i instanceof Er),this.boxWriter=new Cr(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Er?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let i=await this.output._getInitTarget(),s=new Pr(i,!0);s.start(),this.initWriter=s,this.initBoxWriter=new Cr(s)}let t=this.output._tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{let i=this.initBoxWriter??this.boxWriter;if(p(i),this.format._options.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Hl({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:s,start:n}=i.writer.stopTrackingWrites();this.format._options.onFtyp(s,n)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(p(this.writer),p(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ls(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Ns({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){let s=this.trackDatas.find(f=>f.track===e);if(s)return s;ys(i),p(i),p(i.decoderConfig);let n={...i.decoderConfig};p(n.codedWidth!==void 0),p(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){let f=Gr(t.data);if(!f)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=bc(f),a=!0}else if(e.source._codec==="hevc"&&!n.description){let f=jr(t.data);if(!f)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Ac(f),a=!0}let o=zo(1/(e.metadata.frameRate??qe),1e6).den,c=n.displayAspectWidth,l=n.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:xt({num:c*n.codedHeight,den:l*n.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:u,decoderConfig:n,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((f,h)=>f.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,i){let s=this.trackDatas.find(c=>c.track===e);if(s)return s;Nr(i),p(i),p(i.decoderConfig);let n={...i.decoderConfig},a=!1;if(e.source._codec==="aac"&&!n.description){let c=De(ye.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=We[c.samplingFrequencyIndex],u=mt[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");n.description=Or({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&ae.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;bs(t),p(t),p(t.config);let s={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){let s=await this.mutex.acquire();try{let n=this.getVideoTrackData(e,t,i),a=t.data;if(n.info.requiresAnnexBTransformation){let c=[...Hr(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Fs(c,4)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");let o=this.createSampleForTrack(n,a,t.timestamp,t.duration,t.type);await this.registerSample(n,o)}finally{s()}}async addEncodedAudioPacket(e,t,i){let s=await this.mutex.acquire();try{let n=this.getAudioTrackData(e,t,i),a=t.data;if(n.info.requiresAdtsStripping){let u=De(ye.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?zt:Ne;a=a.subarray(d)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(n.info.requiresPcmTransformation){let d=xe(n.info.decoderConfig.codec).sampleSize*n.info.numberOfChannels;if(c=a.byteLength/d/n.info.sampleRate,n.info.expectedNextPcmPacketTimestamp!==null){let f=o-n.info.expectedNextPcmPacketTimestamp;if(f<.01)o=n.info.expectedNextPcmPacketTimestamp;else{let h=await this.padWithSilence(n,n.info.expectedNextPcmPacketTimestamp,f);o=n.info.expectedNextPcmPacketTimestamp+h}}n.info.expectedNextPcmPacketTimestamp=o+c}let l=this.createSampleForTrack(n,a,o,c,t.type);await this.registerSample(n,l)}finally{s()}}async padWithSilence(e,t,i){let s=ie(i,e.timescale);if(i=s/e.timescale,s>0){let{sampleSize:n,silentValue:a}=xe(e.info.decoderConfig.codec),o=s*e.info.numberOfChannels,c=new Uint8Array(n*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,i,"key");await this.registerSample(e,l)}return i}async addSubtitleCue(e,t,i){let s=await this.mutex.acquire();try{let n=this.getSubtitleTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(t),await this.processWebVTTCues(n,t.timestamp))}finally{s()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let i=new Set([]);for(let l of e.cueQueue)p(l.timestamp<=t),p(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);let s=[...i].sort((l,u)=>l-u),n=s[0],a=s[1]??n;if(t<a)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);let l=Kl();this.auxBoxWriter.writeBox(l);let u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let u=e.cueQueue[l];if(u.timestamp>=a)break;wi.lastIndex=0;let d=wi.test(u.text),f=u.timestamp+u.duration,h=e.cueToSourceId.get(u);if(h===void 0&&a<f&&(h=e.nextSourceId++,e.cueToSourceId.set(u,h)),u.notes){let m=Ql(u.notes);this.auxBoxWriter.writeBox(m)}let g=Xl(u.text,d?n:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(g),f===a&&e.cueQueue.splice(l--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,n,a-n,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,s,n){return{timestamp:i,decodeTimestamp:i,duration:s,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:ie(s,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let s=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let a=e.timestampProcessingQueue[n],o=ie(a.duration,e.timescale);s+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:s,sampleDelta:1});else{let n=Q(e.timeToSampleTable);n.sampleCount+=s}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,n)=>s-n);this.isFragmented||(e.startTimestampOffset??=i[0]);for(let s=0;s<e.timestampProcessingQueue.length;s++){let n=e.timestampProcessingQueue[s];n.decodeTimestamp=i[s];let a=ie(n.timestamp-n.decodeTimestamp,e.timescale),o=ie(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);let c=ie(n.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(p(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=Q(e.timeToSampleTable);if(p(u),u.sampleCount===1){u.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let d=Q(e.compositionTimeOffsetTable);p(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=ie(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(t.type==="key");let s=ie(t.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){let s=e.track.metadata.maximumPacketCount;if(p(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let s=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let n=this.trackDatas.every(a=>{if(e===a)return t.type==="key";let o=a.sampleQueue[0];return o?o.type==="key":a.closed});s>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=s>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),p(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(p(!this.isFragmented),p(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,s)=>i+ie(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Q(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(let n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(t=n,i=n.sampleQueue[0].timestamp)}if(!t)break;let s=t.sampleQueue.shift();await this.addSampleToTrack(t,s)}}async finalizeFragment(e=!this.isCmaf){p(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let h=this.initBoxWriter??this.boxWriter;p(h),this.format._options.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let g=yi(this);if(h.writeBox(g),this.format._options.onMoov){let{data:m,start:w}=h.writer.stopTrackingWrites();this.format._options.onMoov(m,w)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Cr(this.writer);let m=this.boxWriter.measureBox(fo()),w=this.boxWriter.measureBox(ho(this,0));this.segmentHeaderSize=m+w,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(this.boxWriter);let i=this.trackDatas.filter(h=>h.currentChunk),s=po(t,i),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s),o=a+Je,c=1/0;for(let h of i){h.currentChunk.offset=o,h.currentChunk.moofOffset=n;for(let g of h.currentChunk.samples)o+=g.size;c=Math.min(c,h.currentChunk.startTimestamp)}let l=o-a,u=l>=2**32;if(u)for(let h of i)h.currentChunk.offset+=vt-Je;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=po(t,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:h,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,g,c)}p(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=ls(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?vt:Je));for(let h of i)for(let g of h.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){let{data:h,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,g)}for(let h of i)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(p(this.writer),p(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let i=yi(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ls(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(let t of this.trackDatas){let i=t.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(s=>s.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let t=this.trackDatas.filter(s=>s.type===e);if(t.length===0)continue;if(!t.some(s=>s.track.metadata.disposition?.default!==!1)){let s=t[0];s.track.metadata.disposition={...s.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let t of this.trackDatas){await this.finalizeCurrentChunk(t),p(t.startTimestampOffset!==null);for(let i=0;i<t.samples.length;i++){let s=t.samples[i];s.timestamp-=t.startTimestampOffset,s.decodeTimestamp-=t.startTimestampOffset}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=ls(!1);let t;for(let s=0;s<2;s++){let n=yi(this),a=this.boxWriter.measureBox(n);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(let c of this.finalizedChunks){c.offset=o;for(let{data:l}of c.samples)p(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let i=yi(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(let s of this.finalizedChunks)for(let n of s.samples)p(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){let{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,n)}}else if(this.isFragmented)if(this.isCmaf){let t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(fo()),this.boxWriter.writeBox(ho(this,t))}else{let t=this.writer.getPos(),i=jl(this.trackDatas);this.boxWriter.writeBox(i);let s=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{p(this.mdat);let t=this.boxWriter.offsets.get(this.mdat);p(t!==void 0);let i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,a)}let s=yi(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);let n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(ql(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){let{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,a)}}e()}};var pf=-(2**15),gf=2**15-1,eu="Mediabunny",tu=6,ru=5,wf={video:1,audio:2,subtitle:17},Vn=class extends wt{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=ne(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Qs(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:k.EBML,data:[{id:k.EBMLVersion,data:1},{id:k.EBMLReadVersion,data:1},{id:k.EBMLMaxIDLength,data:4},{id:k.EBMLMaxSizeLength,data:8},{id:k.DocType,data:this.format instanceof Ti?"webm":"matroska"},{id:k.DocTypeVersion,data:2},{id:k.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:k.SeekHead,data:[{id:k.Seek,data:[{id:k.SeekID,data:t},{id:k.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:k.Seek,data:[{id:k.SeekID,data:i},{id:k.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:k.Seek,data:[{id:k.SeekID,data:s},{id:k.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:k.Seek,data:[{id:k.SeekID,data:n},{id:k.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:k.Seek,data:[{id:k.SeekID,data:a},{id:k.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){let e={id:k.Duration,data:new Jr(0)};this.segmentDuration=e;let t={id:k.Info,data:[{id:k.TimestampScale,data:1e6},{id:k.MuxingApp,data:eu},{id:k.WritingApp,data:eu},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){let e={id:k.Tracks,data:[]};this.tracksElement=e;for(let t of this.trackDatas){let i=Pe[t.track.source._codec];p(i);let s=0;if(t.type==="audio"&&t.track.source._codec==="opus"){s=1e6*80;let n=t.info.decoderConfig.description;if(n){let a=ee(n),o=Kr(a);s=Math.round(1e9*(o.preSkip/Pt))}}e.data.push({id:k.TrackEntry,data:[{id:k.TrackNumber,data:t.track.id},{id:k.TrackUID,data:t.track.id},{id:k.TrackType,data:wf[t.type]},t.track.metadata.disposition?.default===!1?{id:k.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:k.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:k.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:k.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:k.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:k.FlagCommentary,data:1}:null,{id:k.FlagLacing,data:0},{id:k.Language,data:t.track.metadata.languageCode??Z},{id:k.CodecID,data:i},{id:k.CodecDelay,data:0},{id:k.SeekPreRoll,data:s},t.track.metadata.name!==void 0?{id:k.Name,data:new it(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,rotation:i}=e.track.metadata,s=[e.info.decoderConfig.description?{id:k.CodecPrivate,data:ee(e.info.decoderConfig.description)}:null,t?{id:k.DefaultDuration,data:1e9/t}:null],n=i?qt(-i):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace,c={id:k.Video,data:[{id:k.PixelWidth,data:e.info.width},{id:k.PixelHeight,data:e.info.height},a?{id:k.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:k.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:k.DisplayUnit,data:3}:null,e.info.alphaMode?{id:k.AlphaMode,data:1}:null,fs(o)?{id:k.Colour,data:[{id:k.MatrixCoefficients,data:Qe[o.matrix]},{id:k.TransferCharacteristics,data:Xe[o.transfer]},{id:k.Primaries,data:Ke[o.primaries]},{id:k.Range,data:o.fullRange?2:1}]}:null,n?{id:k.Projection,data:[{id:k.ProjectionType,data:0},{id:k.ProjectionPoseRoll,data:new Zr((n+180)%360-180)}]}:null]};return s.push(c),s}audioSpecificTrackInfo(e){let t=ae.includes(e.track.source._codec)?xe(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:k.CodecPrivate,data:ee(e.info.decoderConfig.description)}:null,{id:k.Audio,data:[{id:k.SamplingFrequency,data:new Zr(e.info.sampleRate)},{id:k.Channels,data:e.info.numberOfChannels},t?{id:k.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:k.CodecPrivate,data:te.encode(e.info.config.description)}]}maybeCreateTags(){let e=[],t=(n,a)=>{e.push({id:k.SimpleTag,data:[{id:k.TagName,data:new it(n)},typeof a=="string"?{id:k.TagString,data:new it(a)}:{id:k.TagBinary,data:a}]})},i=this.output._metadataTags,s=new Set;for(let{key:n,value:a}of ft(i))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{let o=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{let o=i.discsTotal!==void 0?`${a}/${i.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:le(n)}if(i.raw)for(let n in i.raw){let a=i.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:k.Tags,data:[{id:k.Tag,data:[{id:k.Targets,data:[{id:k.TargetTypeValue,data:50},{id:k.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],i=new Set,s=e.images??[];for(let n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(Vo(n.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!i.has(o))break}i.add(o),t.push({id:k.AttachedFile,data:[n.description!==void 0?{id:k.FileDescription,data:new it(n.description)}:null,{id:k.FileName,data:new it(a)},{id:k.FileMediaType,data:n.mimeType},{id:k.FileData,data:n.data},{id:k.FileUID,data:o}]})}for(let[n,a]of Object.entries(e.raw??{}))!(a instanceof mr)||!/^\d+$/.test(n)||s.find(c=>c.mimeType===a.mimeType&&ps(c.data,a.data))||t.push({id:k.AttachedFile,data:[a.description!==void 0?{id:k.FileDescription,data:new it(a.description)}:null,{id:k.FileName,data:new it(a.name??"")},{id:k.FileMediaType,data:a.mimeType??""},{id:k.FileData,data:a.data},{id:k.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:k.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:k.Segment,size:this.format._options.appendOnly?-1:tu,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:k.Cues,data:[]}}get segmentDataOffset(){return p(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Js({isWebM:this.format instanceof Ti,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){let s=this.trackDatas.find(l=>l.track===e);if(s)return s;ys(i),p(i),p(i.decoderConfig),p(i.decoderConfig.codedWidth!==void 0),p(i.decoderConfig.codedHeight!==void 0);let n=i.decoderConfig.displayAspectWidth,a=i.decoderConfig.displayAspectHeight,o=n===void 0||a===void 0?null:xt({num:n,den:a}),c={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec==="vp9"?c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(jo(c.info.decoderConfig.codec))}:e.source._codec==="av1"&&(c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(ws(c.info.decoderConfig.codec))}),this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,i){let s=this.trackDatas.find(c=>c.track===e);if(s)return s;Nr(i),p(i),p(i.decoderConfig);let n={...i.decoderConfig},a=!1;if(e.source._codec==="aac"&&!n.description){let c=De(ye.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=We[c.samplingFrequencyIndex],u=mt[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");n.description=Or({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}let o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;bs(t),p(t),p(t.config);let s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){let s=await this.mutex.acquire();try{let n=this.getVideoTrackData(e,t,i),a=t.type==="key";this.validateTimestamp(n.track,t.timestamp,a);let o=t.timestamp,c=t.duration;e.metadata.frameRate!==void 0&&(o=ut(o,e.metadata.frameRate),c=ut(c,e.metadata.frameRate));let l=n.info.alphaMode?t.sideData.alpha??null:null,u=this.createInternalChunk(t.data,o,c,t.type,l);e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,u),n.chunkQueue.push(u),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,i){let s=await this.mutex.acquire();try{let n=this.getAudioTrackData(e,t,i),a=t.data;if(n.info.requiresAdtsStripping){let l=De(ye.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let u=l.crcCheck===null?zt:Ne;a=a.subarray(u)}let o=t.type==="key";this.validateTimestamp(n.track,t.timestamp,o);let c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,i){let s=await this.mutex.acquire();try{let n=this.getSubtitleTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,!0);let a=t.text,o=Math.round(t.timestamp*1e3);wi.lastIndex=0,a=a.replace(wi,d=>{let h=Dl(d.slice(1,-1))-o;return`<${On(h)}>`});let c=te.encode(a),l=`${t.settings??""}
|
|
25
|
+
${t.identifier??""}
|
|
26
|
+
${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?te.encode(l):null);n.chunkQueue.push(u),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(let n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!n.closed)break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(t=n,i=n.chunkQueue[0].timestamp)}if(!t)break;let s=t.chunkQueue.shift();this.writeBlock(t,s)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let i=new G(t.data);i.skipBits(2);let s=i.readBits(1),a=(i.readBits(1)<<1)+s;if(a===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;a>=2&&i.skipBits(1);let u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];vo(t.data,i.pos,i.pos+3,u)}createInternalChunk(e,t,i,s,n=null){return{data:e,type:s,timestamp:t,duration:i,additions:n}}writeBlock(e,t){this.segment||this.createSegment();let i=Math.round(1e3*t.timestamp),s=this.trackDatas.every(u=>{if(e===u)return t.type==="key";let d=u.chunkQueue[0];return d?d.type==="key":u.closed}),n=!1;if(!this.currentCluster)n=!0;else{p(this.currentClusterStartMsTimestamp!==null),p(this.currentClusterMaxMsTimestamp!==null);let u=i-this.currentClusterStartMsTimestamp;n=s&&i>this.currentClusterMaxMsTimestamp&&u>=1e3*(this.format._options.minimumClusterDuration??1)||u>gf}n&&this.createNewCluster(i);let a=i-this.currentClusterStartMsTimestamp;if(a<pf)return;let o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,a,!1);let l=Math.round(1e3*t.duration);if(t.additions){let u={id:k.BlockGroup,data:[{id:k.Block,data:[o,t.data]},t.type==="delta"?{id:k.ReferenceBlock,data:new Xi(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:k.BlockAdditions,data:[{id:k.BlockMore,data:[{id:k.BlockAddID,data:1},{id:k.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:k.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(u)}else{c.setUint8(3,+(t.type==="key")<<7);let u={id:k.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(u)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:k.Cluster,size:this.format._options.appendOnly?-1:ru,data:[{id:k.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(p(this.currentCluster),!this.format._options.appendOnly){let s=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),n=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(s,ru),this.writer.seek(n)}if(this.format._options.onCluster){p(this.currentClusterStartMsTimestamp!==null);let{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(s,n,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(let[s,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(s);let i=[...t.entries()].sort((s,n)=>s[0]-n[0]);for(let[s,n]of i)p(this.cues),this.cues.data.push({id:k.CuePoint,data:[{id:k.CueTime,data:s},...n.map(a=>({id:k.CueTrackPositions,data:[{id:k.CueTrack,data:a.track.id},{id:k.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(s=>s.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),p(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,tu);let i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Jr(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),p(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var Ln=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),i=255,s=224|e.mpegVersionId<<3|e.layer<<1,n;e.mpegVersionId&2?n=e.mpegVersionId&1?0:1:n=1;let a=0,o=155,c=-1,l=n*16*4+e.layer*16;for(let w=0;w<16;w++){let y=_s[l+w];if(Is(n,e.layer,1e3*y,e.sampleRate,a)>=o){c=w;break}}if(c===-1)throw new Error("No suitable bitrate found.");let u=c<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=i,this.helper[1]=s,this.helper[2]=u,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let f=Qt(e.mpegVersionId,e.channel);this.writer.seek(t+f),this.writeU32(Xt);let h=0;e.frameCount!==null&&(h|=It.FrameCount),e.fileSize!==null&&(h|=It.FileSize),e.toc!==null&&(h|=It.Toc),this.writeU32(h),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let g=_s[l+c],m=Is(n,e.layer,1e3*g,e.sampleRate,a);this.writer.seek(t+m)}};var Wn=class extends wt{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new Ln(this.writer),Es(this.output._metadataTags)||new gi(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){let i=await this.mutex.acquire();try{let s=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&s){let n=L(t.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");let a=n.getUint32(0,!1),o=pr(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");let c=Qt(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){let l=n.getUint32(c,!1);if(l===Xt||l===Wr)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,t.type==="key"),s&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let e=await this.mutex.acquire(),i=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);let s=new Uint8Array(100);for(let n=0;n<100;n++){let a=Math.floor(this.framePositions.length*(n/100)),o=this.framePositions[a]-this.xingFramePos;s[n]=256*(o/i)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=i,this.xingFrameData.toc=s,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,a)}e()}};var Hn=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}};var qn=class extends wt{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new Hn(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){let s=await this.mutex.acquire();try{if(this.headerWritten||(Nr(i),p(i),p(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let i,s=e.source._codec,n=xe(s);n.dataType==="ulaw"?i=Me.MULAW:n.dataType==="alaw"?i=Me.ALAW:n.dataType==="float"?i=Me.IEEE_FLOAT:i=Me.PCM;let a=t.numberOfChannels,o=t.sampleRate,c=n.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(i),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*n.sampleSize),!Es(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):le(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,u)}}writeInfoChunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let i=new Set,s=(o,c)=>{if(!je(c)){O._warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}let l=c.length+1,u=new Uint8Array(l);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(l),this.writer.write(u),l&1&&this.writer.write(new Uint8Array(1)),i.add(o)};for(let{key:o,value:c}of ft(e))switch(o){case"title":s("INAM",c),i.add("INAM");break;case"artist":s("IART",c),i.add("IART");break;case"album":s("IPRD",c),i.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();s("ITRK",l),i.add("ITRK")}break;case"genre":s("IGNR",c),i.add("IGNR");break;case"date":s("ICRD",c.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":s("ICMT",c),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:le(o)}if(e.raw)for(let o in e.raw){let c=e.raw[o];c==null||o.length!==4||i.has(o)||typeof c=="string"&&s(o,c)}let n=this.writer.getPos(),a=n-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(n),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let s=new gi(this.writer).writeId3V2Tag(e),n=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(n),s&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire(),t=this.writer.getPos();this.isRf64?(p(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),p(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),p(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(p(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),p(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}};var Gn=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){p(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,s)=>i[s*e]:e===1&&t===4?this.channelMixer=(i,s,n)=>i[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(i,s,n)=>i[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(i,s)=>{let n=s*e;return .5*(i[n]+i[n+1])}:e===2&&t===4?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(i,s)=>{let n=s*e;return .25*(i[n]+i[n+1]+i[n+2]+i[n+3])}:e===4&&t===2?this.channelMixer=(i,s,n)=>{let a=s*e;return .5*(i[a+n]+i[a+n+2])}:e===4&&t===6?this.channelMixer=(i,s,n)=>{let a=s*e;return n<2?i[a+n]:n===2||n===3?0:i[a+n-2]}:e===6&&t===1?this.channelMixer=(i,s)=>{let n=s*e;return Math.SQRT1_2*(i[n]+i[n+1])+i[n+2]+.5*(i[n+4]+i[n+5])}:e===6&&t===2?this.channelMixer=(i,s,n)=>{let a=s*e;return i[a+n]+Math.SQRT1_2*(i[a+2]+i[a+n+4])}:e===6&&t===4?this.channelMixer=(i,s,n)=>{let a=s*e;return n<2?i[a+n]+Math.SQRT1_2*i[a+2]:i[a+n+2]}:this.channelMixer=(i,s,n)=>n<e?i[s*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),p(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let i=e.allocationSize({planeIndex:0,format:"f32"}),s=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(s,{planeIndex:0,format:"f32"});let n=e.timestamp-this.startTime,a=n+e.duration,o=Math.floor(n*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;p(u<this.bufferSizeInFrames);let h=(l/this.targetSampleRate-n)*this.sourceSampleRate,g=Math.floor(h),m=Math.ceil(h),w=h-g;for(let y=0;y<this.targetNumberOfChannels;y++){let b=0,S=0;g>=0&&g<e.numberOfFrames&&(b=this.channelMixer(s,g,y)),m>=0&&m<e.numberOfFrames&&(S=this.channelMixer(s,m,y));let T=b+w*(S-b),A=u*this.targetNumberOfChannels+y;this.outputBuffer[A]+=T}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;p(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let i=new gt({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var Ai=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Ir=class extends Ai{constructor(e){if(super(),this._connectedTrack=null,!ke.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ke.join(", ")}.`);this._codec=e}},bo=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},ko=class extends Ir{constructor(e){super(e)}add(e,t){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),bo(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},To=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Ht,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,i){let s=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let n=this.encodingConfig,a=n.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(n.transform?.width!==void 0||n.transform?.height!==void 0||n.transform?.rotate!==void 0||n.transform?.crop!==void 0||n.transform?.force===!0||o&&a!=="passThrough"){let d=n.transform?.width,f=n.transform?.height,h=n.transform?.fit??"fill";o&&a!=="passThrough"&&(p(this.outputWidth),p(this.outputHeight),p(a!=="deny"),d=this.outputWidth,f=this.outputHeight,h=a);let g=await e.transform({width:d,height:f,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:h,alpha:n.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=g.displayWidth,this.outputHeight=g.displayHeight),t&&e.close(),e=g,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let u=n.transform?.frameRate;if(u!==void 0){let d=e.timestamp+e.duration,f=na(e.timestamp,u);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(f,i);e===s&&(e=e.clone(),t=!0),e.setTimestamp(f),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){let i=this.encodingConfig,s;if(i.transform?.process){let n=i.transform.process(e);if(n instanceof Promise&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]),s=n.map(a=>a instanceof Ye?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new Ye(a):new Ye(a,{timestamp:e.timestamp,duration:e.duration}))}else s=[e];try{for(let n of s){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(n),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized),this.closed)break;let a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(n.timestamp/a),c={...n.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(n),this.customEncoder){this.customEncoderQueueSize++;let u=n.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).then(()=>this.customEncoderQueueSize--).catch(f=>this.error??=f).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await d}else{p(this.encoder);let u=n.toVideoFrame(),d=H(this.preciseTimings,u.timestamp,h=>h.microsecondTimestamp),f=d!==-1?this.preciseTimings[d]:null;if(f&&f.microsecondTimestamp===u.timestamp?(f.timestamp!==n.timestamp&&(f.timestampIsValid=!1),f.duration!==n.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:n.timestamp,duration:n.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,l),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,l),u.close();else{let g=u.displayWidth,m=u.displayHeight;this.splitter||(this.splitter=new jn(g,m));let{colorFrame:w,alphaFrame:y}=await this.splitter.update(u);this.alphaFrameQueue.push(y),this.encoder.encode(w,l),w.close()}this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(let n of s)n!==e&&n.close()}}async padFrameRate(e,t){let i=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);let s=Math.round((e-this.frameRateLastTimestamp)*i);for(let n=1;n<s;n++){let a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+n/i),a.setDuration(1/i),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=fa({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let i=Vr.find(s=>s.supports(this.encodingConfig.codec,t));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(s,n)=>{if(!(s instanceof X))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(n!==void 0&&(!n||typeof n!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");bo(this.source._connectedTrack,s),this.encodingConfig.onEncodedPacket?.(s,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,n).catch(a=>{this.error??=a})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let a=[],o=[],c=0,l=0,u=(f,h,g)=>{let m={};if(h){let T=new Uint8Array(h.byteLength);h.copyTo(T),m.alpha=T}let w=X.fromEncodedChunk(f,m),y=H(this.preciseTimings,f.timestamp,T=>T.microsecondTimestamp),b=y!==-1?this.preciseTimings[y]:null,S=null;this.emittedEncoderPackets===0&&w.type==="delta"&&g?.decoderConfig&&(S=Jt(this.encodingConfig.codec,g.decoderConfig,w.data)),(b&&b.microsecondTimestamp===f.timestamp||S!==null)&&(w=w.clone({timestamp:b?.timestampIsValid?b.timestamp:void 0,duration:b?.durationIsValid?b.duration:void 0,type:S??void 0})),bo(this.source._connectedTrack,w),this.encodingConfig.onEncodedPacket?.(w,g),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,g).catch(T=>{this.error??=T}),this.emittedEncoderPackets++},d=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(f,h)=>{if(!this.alphaEncoder){u(f,null,h);return}let g=this.alphaFrameQueue.shift();p(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:f.type==="key"}),l++,g.close(),a.push({chunk:f,meta:h})):l===0?u(f,null,h):(o.push(c+l),a.push({chunk:f,meta:h}))},error:f=>{f.stack=d,this.error??=f}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let f=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(h,g)=>{l--;let m=a.shift();for(p(m!==void 0),u(m.chunk,h,m.meta),c++;o.length>0&&o[0]===c;){o.shift();let w=a.shift();p(w!==void 0),u(w.chunk,null,w.meta)}},error:h=>{h.stack=f,this.error??=h}}),this.alphaEncoder.configure(t)}}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let t=this.encodingConfig.transform.frameRate,i=na(this.frameRateLastEndTimestamp,t);await this.padFrameRate(i)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},iu=!1,jn=class r{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let i=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!r.forceCpu&&i&&!iu)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);let s=this.canvas.getContext("webgl2",{alpha:!0});if(!s)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=s,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(s){this.gl=null,this.canvas=null,iu=!0,O._warn("Falling back to CPU for color/alpha splitting.",s)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){p(this.gl),p(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),i=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:i}}createVertexShader(){return p(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
27
|
+
in vec2 a_position;
|
|
28
|
+
in vec2 a_texCoord;
|
|
29
|
+
out vec2 v_texCoord;
|
|
30
|
+
|
|
31
|
+
void main() {
|
|
32
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
33
|
+
v_texCoord = a_texCoord;
|
|
34
|
+
}
|
|
35
|
+
`)}createColorProgram(){p(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
36
|
+
precision highp float;
|
|
37
|
+
|
|
38
|
+
uniform sampler2D u_sourceTexture;
|
|
39
|
+
in vec2 v_texCoord;
|
|
40
|
+
out vec4 fragColor;
|
|
41
|
+
|
|
42
|
+
void main() {
|
|
43
|
+
vec4 source = texture(u_sourceTexture, v_texCoord);
|
|
44
|
+
fragColor = vec4(source.rgb, 1.0);
|
|
45
|
+
}
|
|
46
|
+
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createAlphaProgram(){p(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
47
|
+
precision highp float;
|
|
48
|
+
|
|
49
|
+
uniform sampler2D u_sourceTexture;
|
|
50
|
+
uniform vec2 u_resolution; // The width and height of the canvas
|
|
51
|
+
in vec2 v_texCoord;
|
|
52
|
+
out vec4 fragColor;
|
|
53
|
+
|
|
54
|
+
// This function determines the value for a single byte in the YUV stream
|
|
55
|
+
float getByteValue(float byteOffset) {
|
|
56
|
+
float width = u_resolution.x;
|
|
57
|
+
float height = u_resolution.y;
|
|
58
|
+
|
|
59
|
+
float yPlaneSize = width * height;
|
|
60
|
+
|
|
61
|
+
if (byteOffset < yPlaneSize) {
|
|
62
|
+
// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
|
|
63
|
+
float y = floor(byteOffset / width);
|
|
64
|
+
float x = mod(byteOffset, width);
|
|
65
|
+
|
|
66
|
+
// Add 0.5 to sample the center of the texel
|
|
67
|
+
vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
|
|
68
|
+
|
|
69
|
+
// The luma value is the alpha from the source texture
|
|
70
|
+
return texture(u_sourceTexture, sampleCoord).a;
|
|
71
|
+
} else {
|
|
72
|
+
// Write a fixed value for chroma and beyond
|
|
73
|
+
return 128.0 / 255.0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
void main() {
|
|
78
|
+
// Each fragment writes 4 bytes (R, G, B, A)
|
|
79
|
+
float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
|
|
80
|
+
float baseByteOffset = pixelIndex * 4.0;
|
|
81
|
+
|
|
82
|
+
vec4 result;
|
|
83
|
+
for (int i = 0; i < 4; i++) {
|
|
84
|
+
float currentByteOffset = baseByteOffset + float(i);
|
|
85
|
+
result[i] = getByteValue(currentByteOffset);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fragColor = result;
|
|
89
|
+
}
|
|
90
|
+
`),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){p(this.gl);let i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||O._error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){p(this.gl),p(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let s=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){p(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),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),e}runColorProgram(e){return p(this.gl),p(this.canvas),this.gl.useProgram(this.colorProgram),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),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){p(this.gl),p(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),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);let{width:t,height:i}=this.canvas,s=Math.ceil(t/2)*Math.ceil(i/2),n=t*i+s*2,a=Math.ceil(n/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,n),p(o[t*i]===128),p(o[o.length-1]===128);let c={format:"I420",codedWidth:t,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){let s=new Blob([`(${yf.toString()})()`],{type:"application/javascript"}),n=URL.createObjectURL(s);this.worker=new Worker(n),URL.revokeObjectURL(n),this.worker.addEventListener("message",a=>{let o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{let o=new Error(a.message||"Color/alpha splitter worker error.");for(let c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}let t=this.nextRequestId++,i=ne();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=new Error("Color/alpha splitter closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};jn.forceCpu=!0;var yf=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",n=>{let{id:a,sourceFrame:o}=n.data;e=e.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});let t=async n=>{let a=n.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=n.codedWidth,c=n.codedHeight,l=n.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await n.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,o,c,a,n);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return s(r,o,c,a,n);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(n,a,o,c,l)=>{let u=a*o,d=Math.ceil(a/2),f=Math.ceil(o/2),h=u+d*f*2,g=new Uint8Array(h);for(let b=0,S=3;b<u;b++,S+=4)g[b]=n[S];g.fill(128,u);let m=new VideoFrame(n,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),w={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[g.buffer]},y=new VideoFrame(g,w);return{colorFrame:m,alphaFrame:y}},s=(n,a,o,c,l)=>{let u=c.includes("P10"),d=c.includes("P12"),f=u||d?2:1,h,g;c.startsWith("I420")?(h=Math.ceil(a/2),g=Math.ceil(o/2)):c.startsWith("I422")?(h=Math.ceil(a/2),g=o):(h=a,g=o);let m=a*o,w=h*g,y=m*f,b=w*f,S=m*f,T=y+b*2,A=c.replace("A",""),P=Math.ceil(a/2),E=Math.ceil(o/2),C=P*E,x=C*f,_=S+2*x,F=new Uint8Array(_),I=T;F.set(n.subarray(I,I+S),0);let U=S,q=u?512:d?2048:128;f===1?F.fill(q,U):new Uint16Array(F.buffer,U,2*C).fill(q);let W=u?"I420P10":d?"I420P12":"I420",V=new VideoFrame(n.subarray(0,T),{format:A,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),ce={format:W,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[F.buffer]},Se=new VideoFrame(F,ce);return{colorFrame:V,alphaFrame:Se}}};var Ao=class extends Ir{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ac(t),super(t.codec),this._encoder=new To(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");let s=new Ye(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var Si=class extends Ai{constructor(e){if(super(),this._connectedTrack=null,!Ie.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ie.join(", ")}.`);this._codec=e}};var So=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Ht,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Gn({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,onSample:async n=>{await this.processAndEncode(n,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&sc(e.format)!==i.transform.sampleFormat){let s=nc(e,i.transform.sampleFormat);t&&e.close(),e=s,t=!0}if(i.transform?.process){let s=i.transform.process(e);if(s instanceof Promise&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);for(let n of s){if(!(n instanceof gt))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(n,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized),this.closed)return;{let i=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=s;else{let n=i-this.lastEndSampleIndex;if(n>=64){let a=new gt({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let i=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??=n).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await s,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{p(this.encoder);let i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){p(this.outputSampleSize),p(this.writeOutputValue);let{numberOfChannels:i,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let f=0;f<s;f+=o){let h=Math.min(o,e.numberOfFrames-f),g=h*i*this.outputSampleSize,m=new ArrayBuffer(g),w=new DataView(m);c.push({frameCount:h,view:w})}let l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let f=0;f<i;f++){e.copyTo(u,{planeIndex:f,format:"f32-planar"});for(let h=0;h<c.length;h++){let{frameCount:g,view:m}=c[h];for(let w=0;w<g;w++)this.writeOutputValue(m,(w*i+f)*this.outputSampleSize,u[h*o+w])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:n}};for(let f=0;f<c.length;f++){let{frameCount:h,view:g}=c[f],m=g.buffer,w=f*o,y=new X(new Uint8Array(m),"key",a+w/n,h/n);this.encodingConfig.onEncodedPacket?.(y,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:i}=e,s=ha({numberOfChannels:t,sampleRate:i,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(s);let n=Lr.find(a=>a.supports(this.encodingConfig.codec,s));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof X))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o).catch(c=>{this.error??=c})},await this.customEncoder.init();else if(ae.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(s)).supported)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let d=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?d=!0:d=Dr(ee(l.decoderConfig.description)).objectType===0,d){let f=Number(Q(s.codec.split(".")));l.decoderConfig.description=Or({objectType:f,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let u=X.fromEncodedChunk(c);u=u.clone({timestamp:ut(u.timestamp,s.sampleRate),duration:c.duration!=null?ut(u.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(u,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(d=>{this.error??=d})},error:c=>{c.stack=o,this.error??=c}}),this.encoder.configure(s)}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:s}=xe(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,ue((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,ue(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{let c=ue(Math.floor(o*32767),-32768,32767);n.setUint8(a,Rl(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{let c=ue(Math.floor(o*32767),-32768,32767);n.setUint8(a,Fl(c))}:p(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,ue((o+1)*32767.5,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,ue(Math.round(o*32767),-32768,32767),s):p(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>_i(n,a,ue((o+1)*83886075e-1,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>Oo(n,a,ue(Math.round(o*8388607),-8388608,8388607),s):p(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,ue((o+1)*21474836475e-1,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,ue(Math.round(o*2147483647),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):p(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):p(!1);break;default:le(i),p(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}};var xo=class extends Si{constructor(e){cc(e),super(e.codec),this._accumulatedTime=0,this._encoder=new So(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let t=gt._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}};var us=class extends Ai{constructor(e){if(super(),this._connectedTrack=null,!pt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${pt.join(", ")}.`);this._codec=e}};var Wt=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ke.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ie.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>pt.includes(e))}_codecUnsupportedHint(e){return""}},xi=class extends Wt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Nn(e,this)}},Kn=class extends xi{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ke,...Di,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...pt]}_codecUnsupportedHint(e){return new ki().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},bi=class extends xi{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ke,...Di,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...pt]}},ki=class extends xi{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ke,...Ie]}_codecUnsupportedHint(e){return new Kn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},ds=class extends Wt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Vn(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...ke,...Di,...ae.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...pt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},Ti=class extends ds{constructor(e){super(e)}getSupportedCodecs(){return[...ke.filter(e=>["vp8","vp9","av1"].includes(e)),...Ie.filter(e=>["opus","vorbis"].includes(e)),...pt]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new ds().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}},Co=class extends Wt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Wn(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},Po=class extends Wt{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new qn(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...ae.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}};var bf=["video","audio","subtitle"],Ci=class r{constructor(e,t,i,s,n){this.id=e,this.output=t,this.type=i,this.source=s,this.metadata=n}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=ca(this.metadata.group),i=ca(e.metadata.group);for(let s of t)if(this.type!==e.type&&i.some(o=>s===o)||i.some(o=>s._pairedGroups.has(o)))return!0;return!1}},Xn=class extends Ci{constructor(e,t,i,s){super(e,t,"video",i,s)}},Qn=class extends Ci{constructor(e,t,i,s){super(e,t,"audio",i,s)}},$n=class extends Ci{constructor(e,t,i,s){super(e,t,"subtitle",i,s)}},Pi=class r{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof r))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}},Eo=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Fr(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&dc(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof Pi)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Pi))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},_o=class extends Le{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Pi,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new _e,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Wt))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ze||e.target instanceof _r))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ze&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ze)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ze&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){p(this._target instanceof _r);let t=this._target.getTarget(e),i=s=>{if(!(s instanceof ze))throw new TypeError("getTarget must return a Target.");return s};return t instanceof Promise?t.then(i):i(t)}async _getTarget(e){p(this._target instanceof _r);let t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(p(this._initTarget!==null),this._initTarget instanceof ze)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof ze)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),i=s=>(this.state==="canceled"?s._close():this._rememberTarget(s),this._emit("target",{target:s,request:e,isRoot:!0}),this._rootTarget=s,s);return t instanceof Promise?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),i=new Pr(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Ir))throw new TypeError("source must be a VideoSource.");if(Eo(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Xn(this._tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Si))throw new TypeError("source must be an AudioSource.");Eo(t);let i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Qn(this._tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof us))throw new TypeError("source must be a SubtitleSource.");Eo(t);let i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new $n(this._tracks.length+1,this,e,i))}setMetadataTags(e){if(uc(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),s=t[e.type].max;if(i===s)throw new Error(s===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${s} ${e.type} track${s===1?"":"s"}.`);let n=t.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks${n===1?"":"s"} in total.`);if(e.isVideoTrack()){let a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let i of bf){let s=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s<n)throw new Error(n===e[i].max?`${this.format._name} requires exactly ${n} ${i} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${i} track${n===1?"":"s"}.`)}let t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(O._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let i=await this._mutex.acquire();try{await this._muxer.start();let s=this._tracks.map(n=>n.source._start());await Promise.all(s)}finally{i()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return O._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&O._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(O._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){let i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}};var su=Symbol.for("mediabunny loaded");globalThis[su]&&O._error(`[WARNING]
|
|
91
|
+
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[su]=!0;export{O as a,X as b,Xa as c,Qa as d,bl as e,Al as f,ed as g,Su as h,xu as i,Cu as j,Pu as k,Eu as l,_u as m,Iu as n,Ts as o,fu as p,li as q,io as r,ns as s,Er as t,yo as u,ko as v,Ao as w,xo as x,Kn as y,Ti as z,Co as A,Po as B,_o as C};
|
|
92
|
+
/*! Bundled license information:
|
|
93
|
+
|
|
94
|
+
mediabunny/dist/modules/src/misc.js:
|
|
95
|
+
mediabunny/dist/modules/src/logging.js:
|
|
96
|
+
mediabunny/dist/modules/src/packet.js:
|
|
97
|
+
mediabunny/dist/modules/shared/bitstream.js:
|
|
98
|
+
mediabunny/dist/modules/shared/aac-misc.js:
|
|
99
|
+
mediabunny/dist/modules/src/codec.js:
|
|
100
|
+
mediabunny/dist/modules/src/custom-coder.js:
|
|
101
|
+
mediabunny/dist/modules/src/sample.js:
|
|
102
|
+
mediabunny/dist/modules/src/encode.js:
|
|
103
|
+
mediabunny/dist/modules/src/metadata.js:
|
|
104
|
+
mediabunny/dist/modules/shared/mp3-misc.js:
|
|
105
|
+
mediabunny/dist/modules/shared/ac3-misc.js:
|
|
106
|
+
mediabunny/dist/modules/src/codec-data.js:
|
|
107
|
+
mediabunny/dist/modules/src/demuxer.js:
|
|
108
|
+
mediabunny/dist/modules/src/isobmff/isobmff-misc.js:
|
|
109
|
+
mediabunny/dist/modules/src/isobmff/isobmff-reader.js:
|
|
110
|
+
mediabunny/dist/modules/src/aes.js:
|
|
111
|
+
mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js:
|
|
112
|
+
mediabunny/dist/modules/src/matroska/ebml.js:
|
|
113
|
+
mediabunny/dist/modules/src/matroska/matroska-misc.js:
|
|
114
|
+
mediabunny/dist/modules/src/matroska/matroska-demuxer.js:
|
|
115
|
+
mediabunny/dist/modules/src/mp3/mp3-reader.js:
|
|
116
|
+
mediabunny/dist/modules/src/mp3/mp3-demuxer.js:
|
|
117
|
+
mediabunny/dist/modules/src/ogg/ogg-misc.js:
|
|
118
|
+
mediabunny/dist/modules/src/ogg/ogg-reader.js:
|
|
119
|
+
mediabunny/dist/modules/src/ogg/ogg-demuxer.js:
|
|
120
|
+
mediabunny/dist/modules/src/wave/wave-demuxer.js:
|
|
121
|
+
mediabunny/dist/modules/src/adts/adts-reader.js:
|
|
122
|
+
mediabunny/dist/modules/src/adts/adts-demuxer.js:
|
|
123
|
+
mediabunny/dist/modules/src/flac/flac-misc.js:
|
|
124
|
+
mediabunny/dist/modules/src/flac/flac-demuxer.js:
|
|
125
|
+
mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-misc.js:
|
|
126
|
+
mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js:
|
|
127
|
+
mediabunny/dist/modules/src/hls/hls-misc.js:
|
|
128
|
+
mediabunny/dist/modules/src/segmented-input.js:
|
|
129
|
+
mediabunny/dist/modules/src/source.js:
|
|
130
|
+
mediabunny/dist/modules/src/hls/hls-segmented-input.js:
|
|
131
|
+
mediabunny/dist/modules/src/hls/hls-demuxer.js:
|
|
132
|
+
mediabunny/dist/modules/src/input-format.js:
|
|
133
|
+
mediabunny/dist/modules/src/pcm.js:
|
|
134
|
+
mediabunny/dist/modules/src/media-sink.js:
|
|
135
|
+
mediabunny/dist/modules/src/input-track.js:
|
|
136
|
+
mediabunny/dist/modules/src/input.js:
|
|
137
|
+
mediabunny/dist/modules/src/reader.js:
|
|
138
|
+
mediabunny/dist/modules/src/id3.js:
|
|
139
|
+
mediabunny/dist/modules/src/muxer.js:
|
|
140
|
+
mediabunny/dist/modules/src/subtitles.js:
|
|
141
|
+
mediabunny/dist/modules/src/isobmff/isobmff-boxes.js:
|
|
142
|
+
mediabunny/dist/modules/src/writer.js:
|
|
143
|
+
mediabunny/dist/modules/src/target.js:
|
|
144
|
+
mediabunny/dist/modules/src/isobmff/isobmff-muxer.js:
|
|
145
|
+
mediabunny/dist/modules/src/matroska/matroska-muxer.js:
|
|
146
|
+
mediabunny/dist/modules/src/mp3/mp3-writer.js:
|
|
147
|
+
mediabunny/dist/modules/src/mp3/mp3-muxer.js:
|
|
148
|
+
mediabunny/dist/modules/src/wave/riff-writer.js:
|
|
149
|
+
mediabunny/dist/modules/src/wave/wave-muxer.js:
|
|
150
|
+
mediabunny/dist/modules/src/resample.js:
|
|
151
|
+
mediabunny/dist/modules/src/media-source.js:
|
|
152
|
+
mediabunny/dist/modules/src/output-format.js:
|
|
153
|
+
mediabunny/dist/modules/src/output.js:
|
|
154
|
+
mediabunny/dist/modules/src/index.js:
|
|
155
|
+
(*!
|
|
156
|
+
* Copyright (c) 2026-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
|
+
*)
|
|
162
|
+
*/
|
|
163
|
+
//# sourceMappingURL=chunk-L5UFQACH.js.map
|