easecut-react 1.1.0
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/LICENSE +21 -0
- package/README.md +224 -0
- package/dist/.dist-D4zXwUWp.js +81 -0
- package/dist/assets/audio-waveform.worker-DiTI_wJb.js +353 -0
- package/dist/assets/fonts/alibaba-puhuiti-2-regular.woff2 +0 -0
- package/dist/assets/fonts/licenses/source-han-sans-OFL-1.1.txt +96 -0
- package/dist/assets/fonts/licenses/zcool-gaoduanhei-usage-statement.txt +52 -0
- package/dist/assets/fonts/source-han-sans-cn-regular.otf +0 -0
- package/dist/assets/fonts/zcool-canger-yuyang-w03.ttf +0 -0
- package/dist/assets/fonts/zcool-gaoduanhei.ttf +0 -0
- package/dist/assets/fonts/zcool-kuaile.ttf +0 -0
- package/dist/assets/fonts/zcool-kuhei.ttf +0 -0
- package/dist/assets/fonts/zcool-wenyi.ttf +0 -0
- package/dist/assets/fonts/zcool-xiaowei-logo.otf +0 -0
- package/dist/assets/frame-preview.worker-ruBHl77w.js +345 -0
- package/dist/assets/soundtouch-processor-BKTidsbT.js +2062 -0
- package/dist/index.js +10802 -0
- package/dist/styles.css +1 -0
- package/dist/types/editor/EaseCut.d.ts +4 -0
- package/dist/types/editor/EaseCut.d.ts.map +1 -0
- package/dist/types/editor/api/create-easecut-api.d.ts +12 -0
- package/dist/types/editor/api/create-easecut-api.d.ts.map +1 -0
- package/dist/types/editor/api/easecut-api-context.d.ts +12 -0
- package/dist/types/editor/api/easecut-api-context.d.ts.map +1 -0
- package/dist/types/editor/api/errors.d.ts +6 -0
- package/dist/types/editor/api/errors.d.ts.map +1 -0
- package/dist/types/editor/api/index.d.ts +3 -0
- package/dist/types/editor/api/index.d.ts.map +1 -0
- package/dist/types/editor/api/source-input.d.ts +7 -0
- package/dist/types/editor/api/source-input.d.ts.map +1 -0
- package/dist/types/editor/api/source-store.d.ts +16 -0
- package/dist/types/editor/api/source-store.d.ts.map +1 -0
- package/dist/types/editor/api/types.d.ts +78 -0
- package/dist/types/editor/api/types.d.ts.map +1 -0
- package/dist/types/editor/components/AudioFloatingInspector.d.ts +10 -0
- package/dist/types/editor/components/AudioFloatingInspector.d.ts.map +1 -0
- package/dist/types/editor/components/CanvasRatioPanel.d.ts +2 -0
- package/dist/types/editor/components/CanvasRatioPanel.d.ts.map +1 -0
- package/dist/types/editor/components/ExportMenu.d.ts +8 -0
- package/dist/types/editor/components/ExportMenu.d.ts.map +1 -0
- package/dist/types/editor/components/FloatingInspector.d.ts +11 -0
- package/dist/types/editor/components/FloatingInspector.d.ts.map +1 -0
- package/dist/types/editor/components/FloatingInspectorBasicPanel.d.ts +10 -0
- package/dist/types/editor/components/FloatingInspectorBasicPanel.d.ts.map +1 -0
- package/dist/types/editor/components/FloatingInspectorShell.d.ts +15 -0
- package/dist/types/editor/components/FloatingInspectorShell.d.ts.map +1 -0
- package/dist/types/editor/components/FloatingInspectorSpeedPanel.d.ts +7 -0
- package/dist/types/editor/components/FloatingInspectorSpeedPanel.d.ts.map +1 -0
- package/dist/types/editor/components/FormDialog.d.ts +16 -0
- package/dist/types/editor/components/FormDialog.d.ts.map +1 -0
- package/dist/types/editor/components/PreviewPanel.d.ts +9 -0
- package/dist/types/editor/components/PreviewPanel.d.ts.map +1 -0
- package/dist/types/editor/components/TextFloatingInspector.d.ts +12 -0
- package/dist/types/editor/components/TextFloatingInspector.d.ts.map +1 -0
- package/dist/types/editor/components/TimelineToolbar.d.ts +8 -0
- package/dist/types/editor/components/TimelineToolbar.d.ts.map +1 -0
- package/dist/types/editor/components/TitleContentTextarea.d.ts +8 -0
- package/dist/types/editor/components/TitleContentTextarea.d.ts.map +1 -0
- package/dist/types/editor/components/VideoFloatingInspector.d.ts +12 -0
- package/dist/types/editor/components/VideoFloatingInspector.d.ts.map +1 -0
- package/dist/types/editor/components/ui/ColorInput.d.ts +15 -0
- package/dist/types/editor/components/ui/ColorInput.d.ts.map +1 -0
- package/dist/types/editor/components/ui/IconButton.d.ts +15 -0
- package/dist/types/editor/components/ui/IconButton.d.ts.map +1 -0
- package/dist/types/editor/components/ui/InputNumber.d.ts +13 -0
- package/dist/types/editor/components/ui/InputNumber.d.ts.map +1 -0
- package/dist/types/editor/components/ui/Select.d.ts +14 -0
- package/dist/types/editor/components/ui/Select.d.ts.map +1 -0
- package/dist/types/editor/components/ui/TextInput.d.ts +10 -0
- package/dist/types/editor/components/ui/TextInput.d.ts.map +1 -0
- package/dist/types/editor/core/audio-waveform-bars.d.ts +50 -0
- package/dist/types/editor/core/audio-waveform-bars.d.ts.map +1 -0
- package/dist/types/editor/core/canvas-size.d.ts +44 -0
- package/dist/types/editor/core/canvas-size.d.ts.map +1 -0
- package/dist/types/editor/core/clip-speed.d.ts +11 -0
- package/dist/types/editor/core/clip-speed.d.ts.map +1 -0
- package/dist/types/editor/core/collision.d.ts +96 -0
- package/dist/types/editor/core/collision.d.ts.map +1 -0
- package/dist/types/editor/core/composition.d.ts +47 -0
- package/dist/types/editor/core/composition.d.ts.map +1 -0
- package/dist/types/editor/core/export-schema.d.ts +5 -0
- package/dist/types/editor/core/export-schema.d.ts.map +1 -0
- package/dist/types/editor/core/index.d.ts +11 -0
- package/dist/types/editor/core/index.d.ts.map +1 -0
- package/dist/types/editor/core/model.d.ts +187 -0
- package/dist/types/editor/core/model.d.ts.map +1 -0
- package/dist/types/editor/core/preview-snapping.d.ts +27 -0
- package/dist/types/editor/core/preview-snapping.d.ts.map +1 -0
- package/dist/types/editor/core/text-fonts.d.ts +76 -0
- package/dist/types/editor/core/text-fonts.d.ts.map +1 -0
- package/dist/types/editor/core/time.d.ts +15 -0
- package/dist/types/editor/core/time.d.ts.map +1 -0
- package/dist/types/editor/core/timeline-commands.d.ts +143 -0
- package/dist/types/editor/core/timeline-commands.d.ts.map +1 -0
- package/dist/types/editor/core/timeline-layout.d.ts +25 -0
- package/dist/types/editor/core/timeline-layout.d.ts.map +1 -0
- package/dist/types/editor/core/timeline-math.d.ts +22 -0
- package/dist/types/editor/core/timeline-math.d.ts.map +1 -0
- package/dist/types/editor/core/timeline-tracks.d.ts +47 -0
- package/dist/types/editor/core/timeline-tracks.d.ts.map +1 -0
- package/dist/types/editor/media/audio-waveform-peaks.d.ts +17 -0
- package/dist/types/editor/media/audio-waveform-peaks.d.ts.map +1 -0
- package/dist/types/editor/media/audio-waveform.d.ts +8 -0
- package/dist/types/editor/media/audio-waveform.d.ts.map +1 -0
- package/dist/types/editor/media/frame-preview.d.ts +25 -0
- package/dist/types/editor/media/frame-preview.d.ts.map +1 -0
- package/dist/types/editor/media/index.d.ts +6 -0
- package/dist/types/editor/media/index.d.ts.map +1 -0
- package/dist/types/editor/media/media-runtime.d.ts +47 -0
- package/dist/types/editor/media/media-runtime.d.ts.map +1 -0
- package/dist/types/editor/media/mediabunny-audio-waveform.d.ts +8 -0
- package/dist/types/editor/media/mediabunny-audio-waveform.d.ts.map +1 -0
- package/dist/types/editor/media/mediabunny-frame-preview.d.ts +21 -0
- package/dist/types/editor/media/mediabunny-frame-preview.d.ts.map +1 -0
- package/dist/types/editor/media/preview-audio-engine.d.ts +23 -0
- package/dist/types/editor/media/preview-audio-engine.d.ts.map +1 -0
- package/dist/types/editor/media/preview-playback-controller.d.ts +26 -0
- package/dist/types/editor/media/preview-playback-controller.d.ts.map +1 -0
- package/dist/types/editor/media/single-frame-preview.d.ts +30 -0
- package/dist/types/editor/media/single-frame-preview.d.ts.map +1 -0
- package/dist/types/editor/media/text-layout-runtime.d.ts +27 -0
- package/dist/types/editor/media/text-layout-runtime.d.ts.map +1 -0
- package/dist/types/editor/store/index.d.ts +3 -0
- package/dist/types/editor/store/index.d.ts.map +1 -0
- package/dist/types/editor/store/timeline-store-context.d.ts +14 -0
- package/dist/types/editor/store/timeline-store-context.d.ts.map +1 -0
- package/dist/types/editor/store/timeline-store.d.ts +115 -0
- package/dist/types/editor/store/timeline-store.d.ts.map +1 -0
- package/dist/types/editor/timeline/AudioWaveformCanvas.d.ts +13 -0
- package/dist/types/editor/timeline/AudioWaveformCanvas.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelineClip.d.ts +41 -0
- package/dist/types/editor/timeline/TimelineClip.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelineDragGhost.d.ts +9 -0
- package/dist/types/editor/timeline/TimelineDragGhost.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelinePanel.d.ts +11 -0
- package/dist/types/editor/timeline/TimelinePanel.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelineRuler.d.ts +14 -0
- package/dist/types/editor/timeline/TimelineRuler.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelineTrimHandle.d.ts +12 -0
- package/dist/types/editor/timeline/TimelineTrimHandle.d.ts.map +1 -0
- package/dist/types/editor/timeline/TimelineViewport.d.ts +8 -0
- package/dist/types/editor/timeline/TimelineViewport.d.ts.map +1 -0
- package/dist/types/editor/timeline/clip-reveal.d.ts +29 -0
- package/dist/types/editor/timeline/clip-reveal.d.ts.map +1 -0
- package/dist/types/editor/timeline/timeline-interaction.d.ts +79 -0
- package/dist/types/editor/timeline/timeline-interaction.d.ts.map +1 -0
- package/dist/types/editor/timeline/useTimelineController.d.ts +22 -0
- package/dist/types/editor/timeline/useTimelineController.d.ts.map +1 -0
- package/dist/types/editor/types.d.ts +52 -0
- package/dist/types/editor/types.d.ts.map +1 -0
- package/dist/types/editor/util/abort-error.d.ts +3 -0
- package/dist/types/editor/util/abort-error.d.ts.map +1 -0
- package/dist/types/editor/util/browser.d.ts +5 -0
- package/dist/types/editor/util/browser.d.ts.map +1 -0
- package/dist/types/editor/util/format-canvas-font.d.ts +7 -0
- package/dist/types/editor/util/format-canvas-font.d.ts.map +1 -0
- package/dist/types/editor/util/format-media-label.d.ts +4 -0
- package/dist/types/editor/util/format-media-label.d.ts.map +1 -0
- package/dist/types/editor/util/format-text-color.d.ts +4 -0
- package/dist/types/editor/util/format-text-color.d.ts.map +1 -0
- package/dist/types/editor/util/format-timeline-time.d.ts +6 -0
- package/dist/types/editor/util/format-timeline-time.d.ts.map +1 -0
- package/dist/types/editor/util/id.d.ts +2 -0
- package/dist/types/editor/util/id.d.ts.map +1 -0
- package/dist/types/editor/util/media-file-format.d.ts +6 -0
- package/dist/types/editor/util/media-file-format.d.ts.map +1 -0
- package/dist/types/editor/util/number.d.ts +6 -0
- package/dist/types/editor/util/number.d.ts.map +1 -0
- package/dist/types/editor/util/text.d.ts +2 -0
- package/dist/types/editor/util/text.d.ts.map +1 -0
- package/dist/types/editor/util/url.d.ts +5 -0
- package/dist/types/editor/util/url.d.ts.map +1 -0
- package/dist/types/editor/util/value.d.ts +3 -0
- package/dist/types/editor/util/value.d.ts.map +1 -0
- package/dist/types/editor/workers/audio-waveform-protocol.d.ts +24 -0
- package/dist/types/editor/workers/audio-waveform-protocol.d.ts.map +1 -0
- package/dist/types/editor/workers/audio-waveform.worker.d.ts +2 -0
- package/dist/types/editor/workers/audio-waveform.worker.d.ts.map +1 -0
- package/dist/types/editor/workers/frame-preview-protocol.d.ts +35 -0
- package/dist/types/editor/workers/frame-preview-protocol.d.ts.map +1 -0
- package/dist/types/editor/workers/frame-preview.worker.d.ts +2 -0
- package/dist/types/editor/workers/frame-preview.worker.d.ts.map +1 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/index.d.ts.map +1 -0
- package/package.json +74 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
(function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);
|
|
2
|
+
/*!
|
|
3
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
4
|
+
*
|
|
5
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
6
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
7
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
8
|
+
*/
|
|
9
|
+
function t(e){if(!e)throw Error(`Assertion failed.`)}let n=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},r=e=>e&&e[e.length-1],i=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},a=e=>{let t=i(e);return t&1?t+1>>1:-(t>>1)},o=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),s=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),c=new TextDecoder,l=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),u={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},d=l(u),f={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},p=l(f),m={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},h=l(m),g=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);var _=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}};let v=/^[0-9a-fA-F]+$/,y=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),b=e=>{t(e.length%2==0);let n=new Uint8Array(e.length/2);for(let t=0;t<e.length;t+=2)n[t/2]=parseInt(e.slice(t,t+2),16);return n},x=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),S=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},C=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},ee=(e,t,n)=>{let r=C(e,n(t),n);e.splice(r+1,0,t)},w=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},T=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},E=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},te=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},ne=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},re=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},ie=e=>{throw Error(`Unexpected value: ${e}`)},ae=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},oe=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},se=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),ce=(e,t,n)=>Math.max(t,Math.min(n,e)),le=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},ue=(e,t)=>Math.round(e/t)*t,de=(e,t)=>Math.round(e*t)/t,fe=(e,t)=>Math.floor(e/t)*t,pe=e=>{let t=0;for(;e;)t++,e>>=1;return t},me=/^[a-z]{3}$/,he=e=>me.test(e),ge=1e6*(1+2**-52);var _e=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}};let ve=null,ye=()=>ve===null?ve=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):ve,be=null,xe=()=>be===null?be=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):be,Se=null,Ce=()=>Se===null?Se=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):Se,we=null,Te=()=>{if(we!==null)return we;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?we=Number(e[1]):null},Ee=(e,t)=>e===-1?t:e,De=(e,t,n,r)=>e<=r&&n<=t,Oe=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},ke=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Ae=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},je=e=>typeof e==`number`&&!Number.isNaN(e),Me=(e,t)=>{if(t.includes(`://`))return t;if(e.includes(`://`)){let t=e.indexOf(`?`);t!==-1&&(e=e.slice(0,t))}let n;if(t.startsWith(`/`)){let r=e.indexOf(`://`);if(r===-1)n=t;else{let i=e.indexOf(`/`,r+3);n=i===-1?e+t:e.slice(0,i)+t}}else{let r=e.lastIndexOf(`/`);n=r===-1?t:e.slice(0,r+1)+t}let r=``,i=n.indexOf(`://`);if(i!==-1){let e=n.indexOf(`/`,i+3);e!==-1&&(r=n.slice(0,e),n=n.slice(e))}let a=n.split(`/`),o=[];for(let e of a)e===`..`?o.pop():e!==`.`&&o.push(e);return r+o.join(`/`)},Ne=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},Pe=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},Fe=e=>{t(Number.isInteger(e.num)),t(Number.isInteger(e.den)),t(e.den!==0);let n=Math.abs(e.num),r=Math.abs(e.den);for(;r!==0;){let e=n%r;n=r,r=e}let i=n||1;return{num:e.num/i,den:e.den/i}},Ie=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},Le=e=>new Promise(t=>setTimeout(t,e));var Re=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},ze
|
|
10
|
+
/*!
|
|
11
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
12
|
+
*
|
|
13
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
14
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
15
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
16
|
+
*/
|
|
17
|
+
;(function(e){e[e.Silent=0]=`Silent`,e[e.Errors=1]=`Errors`,e[e.Warnings=2]=`Warnings`,e[e.Info=3]=`Info`})(ze||={});var D=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==ze.Silent&&t!==ze.Errors&&t!==ze.Warnings&&t!==ze.Info)throw TypeError(`Invalid log level. Use one of the values of the LogLevel enum.`);e._level=t}static get _emitter(){return e._emitterInstance??=new Re}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=ze.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=ze.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=ze.Info&&console.info(...t)}};D._level=ze.Info,D._emitterInstance=null;
|
|
18
|
+
/*!
|
|
19
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
20
|
+
*
|
|
21
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
22
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
23
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
24
|
+
*/
|
|
25
|
+
var Be=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Ve=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}};let He={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};
|
|
26
|
+
/*!
|
|
27
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
28
|
+
*
|
|
29
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
30
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
31
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
32
|
+
*/
|
|
33
|
+
var O=class e{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,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw 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 t=new e(this.bytes);return t.pos=this.pos,t}};
|
|
34
|
+
/*!
|
|
35
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
36
|
+
*
|
|
37
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
38
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
39
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
40
|
+
*/
|
|
41
|
+
let Ue=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],We=[-1,1,2,3,4,5,6,8],Ge=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new O(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<Ue.length&&(i=Ue[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=We[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},Ke=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],qe=[`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`],Je=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,...qe],Ye=[{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}],Xe=[{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}],Ze=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Qe=e=>{
|
|
42
|
+
/*!
|
|
43
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
44
|
+
*
|
|
45
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
46
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
47
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
48
|
+
*/
|
|
49
|
+
let{codec:n,codecDescription:i,colorSpace:a,avcCodecInfo:o,hevcCodecInfo:c,vp9CodecInfo:l,av1CodecInfo:d,proresFormat:p}=e;if(n===`avc`){if(t(e.avcType!==null),o){let t=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${e.avcType}.${y(t)}`}if(!i||i.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${y(i.subarray(1,4))}`}else if(n===`hevc`){let e,t,n,r,a,o;if(c)e=c.generalProfileSpace,t=c.generalProfileIdc,n=x(c.generalProfileCompatibilityFlags),r=c.generalTierFlag,a=c.generalLevelIdc,o=[...c.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let c=s(i),l=c.getUint8(1);e=l>>6&3,t=l&31,n=x(c.getUint32(2)),r=l>>5&1,a=c.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(c.getUint8(6+e))}let l=`hev1.`;for(l+=[``,`A`,`B`,`C`][e]+t,l+=`.`,l+=n.toString(16).toUpperCase(),l+=`.`,l+=r===0?`L`:`H`,l+=a;o.length>0&&o[o.length-1]===0;)o.pop();return o.length>0&&(l+=`.`,l+=o.map(e=>e.toString(16).toUpperCase()).join(`.`)),l}else if(n===`vp8`)return`vp8`;else if(n===`vp9`){if(!l){let t=e.width*e.height,n=r(Xe).level;for(let e of Xe)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=l.profile.toString().padStart(2,`0`),n=l.level.toString().padStart(2,`0`),i=l.bitDepth.toString().padStart(2,`0`),a=l.chromaSubsampling.toString().padStart(2,`0`),o=l.colourPrimaries.toString().padStart(2,`0`),s=l.transferCharacteristics.toString().padStart(2,`0`),c=l.matrixCoefficients.toString().padStart(2,`0`),u=l.videoFullRangeFlag.toString().padStart(2,`0`),d=`vp09.${t}.${n}.${i}.${a}`;return d+=`.${o}.${s}.${c}.${u}`,d.endsWith(`.01.01.01.01.00`)&&(d=d.slice(0,-15)),d}else if(n===`av1`){if(!d){let t=e.width*e.height,n=r(Xe).level;for(let e of Xe)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=d.profile,n=d.level.toString().padStart(2,`0`),i=d.tier?`H`:`M`,o=d.bitDepth.toString().padStart(2,`0`),s=d.monochrome?`1`:`0`,c=100*d.chromaSubsamplingX+10*d.chromaSubsamplingY+1*(d.chromaSubsamplingX&&d.chromaSubsamplingY?d.chromaSamplePosition:0),l=a?.primaries?u[a.primaries]:1,p=a?.transfer?f[a.transfer]:1,h=a?.matrix?m[a.matrix]:1,g=+!!a?.fullRange,_=`av01.${t}.${n}${i}.${o}`;return _+=`.${s}.${c.toString().padStart(3,`0`)}`,_+=`.${l.toString().padStart(2,`0`)}`,_+=`.${p.toString().padStart(2,`0`)}`,_+=`.${h.toString().padStart(2,`0`)}`,_+=`.${g}`,_.endsWith(`.0.110.01.01.01.0`)&&(_=_.slice(0,-17)),_}else if(n===`prores`)return p??`apch`;else n!==null&&ie(n);throw TypeError(`Unhandled codec '${n}'.`)},$e=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?Ge(n).objectType:r.objectType,`mp4a.40.${e}`}}else if(t===`mp3`)return`mp3`;else if(t===`opus`)return`opus`;else if(t===`vorbis`)return`vorbis`;else if(t===`flac`)return`flac`;else if(t===`ac3`)return`ac-3`;else if(t===`eac3`)return`ec-3`;else if(t&&qe.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},et=48e3,tt=/^pcm-([usf])(\d+)(be)?$/,nt=e=>{if(t(qe.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let n=tt.exec(e);t(n);let r;r=n[1]===`u`?`unsigned`:n[1]===`s`?`signed`:`float`;let i=Number(n[2])/8,a=n[3]!==`be`;return{dataType:r,sampleSize:i,littleEndian:a,silentValue:e===`pcm-u8`?2**7:0}},rt=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:Ze.includes(e)?`prores`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:tt.test(e)?e:e===`webvtt`?`webvtt`:null;[...Ze];
|
|
50
|
+
/*!
|
|
51
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
52
|
+
*
|
|
53
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
54
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
55
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
56
|
+
*/
|
|
57
|
+
let it=[44100,48e3,32e3],at=[-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],ot=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,st=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,ct=(e,t)=>e===3?t===3?21:36:t===3?13:21,lt=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=at[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=it[d]>>o+s,x=ot(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:o,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},ut=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n};var dt;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(dt||={});let ft=e=>e===3?1:2,pt=[48e3,44100,32e3],mt=[24e3,22050,16e3]
|
|
58
|
+
/*!
|
|
59
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
60
|
+
*
|
|
61
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
62
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
63
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
64
|
+
*/
|
|
65
|
+
;
|
|
66
|
+
/*!
|
|
67
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
68
|
+
*
|
|
69
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
70
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
71
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
72
|
+
*/
|
|
73
|
+
var k;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(k||={});var A;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(A||={});let ht=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},gt=function*(e,n){let r=0,i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+n<=e.length;){let e;n===1?e=i.getUint8(r):n===2?e=i.getUint16(r,!1):n===3?e=ae(i,r,!1):(t(n===4),e=i.getUint32(r,!1)),r+=n,yield{offset:r,length:e},r+=e}},_t=(e,t)=>{if(t.description){let n=(o(t.description)[4]&3)+1;return gt(e,n)}else return ht(e)},vt=e=>e&31,yt=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},bt=new Uint8Array([0,0,0,1]),xt=e=>{let t=e.reduce((e,t)=>e+bt.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(bt,r),r+=bt.byteLength,n.set(t,r),r+=t.byteLength;return n},St=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:oe(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1);break}i+=t,r.set(n,i),i+=n.byteLength}return r},Ct=(e,t)=>{if(t.description){let n=(o(t.description)[4]&3)+1;return St(e,n)}else return xt(e)},wt=e=>{try{let n=[],r=[],i=[];for(let t of ht(e)){let a=e.subarray(t.offset,t.offset+t.length),o=vt(a[0]);o===k.SPS?n.push(a):o===k.PPS?r.push(a):o===k.SPS_EXT&&i.push(a)}if(n.length===0||r.length===0)return null;let a=n[0],o=Dt(a);t(o!==null);let s=o.profileIdc===100||o.profileIdc===110||o.profileIdc===122||o.profileIdc===144;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:n,pictureParameterSets:r,chromaFormat:s?o.chromaFormatIdc:null,bitDepthLumaMinus8:s?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?i:null}}catch(e){return D._error(`Error building AVC Decoder Configuration Record:`,e),null}},Tt=e=>{try{let t=s(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),c=t.getUint8(n++)&3,l=t.getUint8(n++)&31,u=[];for(let r=0;r<l;r++){let r=t.getUint16(n,!1);n+=2,u.push(e.subarray(n,n+r)),n+=r}let d=t.getUint8(n++),f=[];for(let r=0;r<d;r++){let r=t.getUint16(n,!1);n+=2,f.push(e.subarray(n,n+r)),n+=r}let p={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:c,sequenceParameterSets:u,pictureParameterSets:f,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);p.chromaFormat=r,p.bitDepthLumaMinus8=i,p.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}p.sequenceParameterSetExt=s}return p}catch(e){return D._error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Et={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}},Dt=e=>{try{let n=new O(yt(e));if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;let o=n.readAlignedByte(),s=n.readAlignedByte(),c=n.readAlignedByte();i(n);let l=1,u=0,d=0,f=0;if((o===100||o===110||o===122||o===244||o===44||o===83||o===86||o===118||o===128)&&(l=i(n),l===3&&(f=n.readBits(1)),u=i(n),d=i(n),n.skipBits(1),n.readBits(1))){for(let e=0;e<(l===3?12:8);e++)if(n.readBits(1)){let t=e<6?16:64,r=8,i=8;for(let e=0;e<t;e++){if(i!==0){let e=a(n);i=(r+e+256)%256}r=i===0?r:i}}}i(n);let p=i(n);if(p===0)i(n);else if(p===1){n.skipBits(1),a(n),a(n);let e=i(n);for(let t=0;t<e;t++)a(n)}i(n),n.skipBits(1);let m=i(n),h=i(n),g=16*(m+1),_=16*(h+1),v=g,y=_,b=n.readBits(1);if(b||n.skipBits(1),n.skipBits(1),n.readBits(1)){let e=i(n),t=i(n),r=i(n),a=i(n),o,s;if((f===0?l:0)===0)o=1,s=2-b;else{let e=l===3?1:2,t=l===1?2:1;o=e,s=t*(2-b)}v-=o*(e+t),y-=s*(r+a)}let x=2,S=2,C=2,ee=0,w={num:1,den:1},T=null,E=null;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)w={num:n.readBits(16),den:n.readBits(16)};else{let t=Et[e];t&&(w=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),ee=n.readBits(1),n.readBits(1)&&(x=n.readBits(8),S=n.readBits(8),C=n.readBits(8))),n.readBits(1)&&(i(n),i(n)),n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.skipBits(1));let e=n.readBits(1);e&&Ot(n);let t=n.readBits(1);t&&Ot(n),(e||t)&&n.skipBits(1),n.skipBits(1),n.readBits(1)&&(n.skipBits(1),i(n),i(n),i(n),i(n),T=i(n),E=i(n))}if(T===null){t(E===null);let e=s&16;if((o===44||o===86||o===100||o===110||o===122||o===244)&&e)T=0,E=0;else{let e=m+1,t=h+1,n=(2-b)*t,i=Ye.find(e=>e.level>=c)??r(Ye),a=Math.min(Math.floor(i.maxDpbMbs/(e*n)),16);T=a,E=a}}return t(E!==null),{profileIdc:o,constraintFlags:s,levelIdc:c,frameMbsOnlyFlag:b,chromaFormatIdc:l,bitDepthLumaMinus8:u,bitDepthChromaMinus8:d,codedWidth:g,codedHeight:_,displayWidth:v,displayHeight:y,pixelAspectRatio:w,colourPrimaries:x,matrixCoefficients:C,transferCharacteristics:S,fullRangeFlag:ee,numReorderFrames:T,maxDecFrameBuffering:E}}catch(e){return D._error(`Error parsing AVC SPS:`,e),null}},Ot=e=>{let t=i(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)i(e),i(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},kt=(e,t)=>{if(t.description){let n=(o(t.description)[21]&3)+1;return St(e,n)}else return xt(e)},At=(e,t)=>{if(t.description){let n=(o(t.description)[21]&3)+1;return gt(e,n)}else return ht(e)},jt=e=>e>>1&63,Mt=e=>{try{let t=new O(yt(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=Pt(t,n);i(t);let d=i(t),f=0;d===3&&(f=t.readBits(1));let p=i(t),m=i(t),h=p,g=m;if(t.readBits(1)){let e=i(t),n=i(t),r=i(t),a=i(t),o=1,s=1,c=f===0?d:0;c===1?(o=2,s=2):c===2&&(o=2,s=1),h-=(e+n)*o,g-=(r+a)*s}let _=i(t),v=i(t);i(t);let y=t.readBits(1)?0:n,b=0;for(let e=y;e<=n;e++)i(t),b=i(t),i(t);i(t),i(t),i(t),i(t),i(t),i(t),t.readBits(1)&&t.readBits(1)&&Ft(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),i(t),i(t),t.skipBits(1));let x=i(t);if(It(t,x),t.readBits(1)){let e=i(t);for(let n=0;n<e;n++)i(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let S=2,C=2,ee=2,w=0,T=0,E={num:1,den:1};if(t.readBits(1)){let e=Rt(t,n);E=e.pixelAspectRatio,S=e.colourPrimaries,C=e.transferCharacteristics,ee=e.matrixCoefficients,w=e.fullRangeFlag,T=e.minSpatialSegmentationIdc}return{displayWidth:h,displayHeight:g,pixelAspectRatio:E,colourPrimaries:S,transferCharacteristics:C,matrixCoefficients:ee,fullRangeFlag:w,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,chromaFormatIdc:d,bitDepthLumaMinus8:_,bitDepthChromaMinus8:v,minSpatialSegmentationIdc:T}}catch(e){return D._error(`Error parsing HEVC SPS:`,e),null}},Nt=e=>{try{let t=[],n=[],r=[],o=[];for(let i of ht(e)){let a=e.subarray(i.offset,i.offset+i.length),s=jt(a[0]);s===A.VPS_NUT?t.push(a):s===A.SPS_NUT?n.push(a):s===A.PPS_NUT?r.push(a):(s===A.PREFIX_SEI_NUT||s===A.SUFFIX_SEI_NUT)&&o.push(a)}if(n.length===0||r.length===0)return null;let s=Mt(n[0]);if(!s)return null;let c=0;if(r.length>0){let e=r[0],t=new O(yt(e));t.skipBits(16),i(t),i(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),i(t),i(t),a(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&i(t),a(t),a(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),o=t.readBits(1);c=!n&&!o?0:n&&!o?2:!n&&o?3:0}let l=[...t.length?[{arrayCompleteness:1,nalUnitType:A.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:A.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:A.PPS_NUT,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:jt(o[0][0]),nalUnits:o}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(e){return D._error(`Error building HEVC Decoder Configuration Record:`,e),null}},Pt=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Ft=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))i(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&a(e);for(let t=0;t<n;t++)a(e)}},It=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Lt(e,r,t,n)},Lt=(e,t,n,r)=>{let a=0,o=0,s=0;if(t!==0&&(o=e.readBits(1)),o){s=t===n?t-(i(e)+1):t-1,e.readBits(1),i(e);let o=r[s]??0;for(let t=0;t<=o;t++)e.readBits(1)||e.readBits(1);a=r[s]}else{let t=i(e),n=i(e);for(let n=0;n<t;n++)i(e),e.readBits(1);for(let t=0;t<n;t++)i(e),e.readBits(1);a=t+n}return a},Rt=(e,t)=>{let n=2,r=2,a=2,o=0,s=0,c={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)c={num:e.readBits(16),den:e.readBits(16)};else{let e=Et[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),o=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(i(e),i(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(i(e),i(e),i(e),i(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&i(e),e.readBits(1)&&zt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),s=i(e),i(e),i(e),i(e),i(e)),{pixelAspectRatio:c,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:o,minSpatialSegmentationIdc:s}},zt=(e,t,n)=>{let r=!1,a=!1,o=!1;t&&(r=e.readBits(1)===1,a=e.readBits(1)===1,(r||a)&&(o=e.readBits(1)===1,o&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),o&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let s=!1;n?i(e):s=e.readBits(1)===1;let c=1;s||(c=i(e)+1),r&&Bt(e,c,o),a&&Bt(e,c,o)}},Bt=(e,t,n)=>{for(let r=0;r<t;r++)i(e),i(e),n&&(i(e),i(e)),e.readBits(1)};var j;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(j||={});let Vt=(e,t)=>{let n=new Set,r=j.audAllowed;for(let i of At(e,t)){if(r===j.noMoreDataAllowed){n.add(i.offset);continue}let t=jt(e[i.offset]);if(r===j.eoBitstreamAllowed&&t!==37){n.add(i.offset);continue}let a=!1;t===35?r>j.audAllowed?a=!0:r=j.beforeFirstVcl:t<=31?r>j.afterFirstVcl?a=!0:r=j.afterFirstVcl:t===36?r===j.afterFirstVcl?r=j.eoBitstreamAllowed:a=!0:t===37?r<j.afterFirstVcl?a=!0:r=j.noMoreDataAllowed:t===32||t===33||t===34||t===39||t>=41&&t<=44||t>=48&&t<=55?r>j.beforeFirstVcl?a=!0:r=j.beforeFirstVcl:(t===38||t===40||t>=45&&t<=47||t>=56&&t<=63)&&r<j.afterFirstVcl&&(a=!0),a&&n.add(i.offset)}if(n.size===0)return null;let i=[];for(let r of At(e,t))n.has(r.offset)||i.push(e.subarray(r.offset,r.offset+r.length));return kt(i,t)},Ht=e=>{let t=new O(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),i=(t.readBits(1)<<1)+n;if(i===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let a=8;i>=2&&(a=t.readBits(1)?12:10);let o=t.readBits(3),s=0,c=0;if(o!==7)if(c=t.readBits(1),i===1||i===3){let e=t.readBits(1),n=t.readBits(1);s=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else s=1;else s=3,c=1;let l=t.readBits(16),u=t.readBits(16),d=(l+1)*(u+1),f=r(Xe).level;for(let e of Xe)if(d<=e.maxPictureSize){f=e.level;break}return{profile:i,level:f,bitDepth:a,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:o===2?1:o===1?6:2,transferCharacteristics:o===2?1:o===1?6:2,matrixCoefficients:o===7?0:o===2?1:o===1?6:2}},Ut=function*(e){let n=new O(e),r=()=>{let e=0;for(let t=0;t<8;t++){let r=n.readAlignedByte();if(e|=(r&127)<<t*7,!(r&128))break;if(t===7&&r&128)return null}return e>=2**32-1?null:e};for(;n.getBitsLeft()>=8;){n.skipBits(1);let i=n.readBits(4),a=n.readBits(1),o=n.readBits(1);n.skipBits(1),a&&n.skipBits(8);let s;if(o){let e=r();if(e===null)return;s=e}else s=Math.floor(n.getBitsLeft()/8);t(n.pos%8==0),yield{type:i,data:e.subarray(n.pos/8,n.pos/8+s)},n.skipBits(s*8)}},Wt=e=>{for(let{type:t,data:n}of Ut(e)){if(t!==1)continue;let e=new O(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},Gt=e=>{let t=s(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),c=null;return o&&(c=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:c}},Kt=[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],qt=e=>{let t=e[0]>>3,n=e[0]&3,r;return r=n===0?1:n===1||n===2?2:e[1]&63,{durationInSamples:Kt[t]*r}},Jt=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new O(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},Yt=(e,n,r)=>{switch(e){case`avc`:for(let e of _t(r,n)){let t=r[e.offset],n=vt(t);if(n>=k.NON_IDR_SLICE&&n<=k.SLICE_DPC)return`delta`;if(n===k.IDR)return`key`;if(n===k.SEI&&(!Ce()||Te()>=144)){let t=r.subarray(e.offset,e.offset+e.length),n=yt(t),a=1;do{let e=0;for(;;){let t=n[a++];if(t===void 0||(e+=t,t<255))break}let t=0;for(;;){let e=n[a++];if(e===void 0||(t+=e,e<255))break}if(e===6){let e=new O(n);e.pos=8*a;let t=i(e),r=e.readBits(1);if(t===0&&r===1)return`key`}a+=t}while(a<n.length-1)}}return`delta`;case`hevc`:for(let e of At(r,n)){let t=jt(r[e.offset]);if(t<A.BLA_W_LP)return`delta`;if(t<=A.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return r[0]&1?`delta`:`key`;case`vp9`:{let e=new O(r);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:n}of Ut(r))if(t===1){let t=new O(n);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new O(n);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:ie(e),t(!1)}};var Xt;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Xt||={});let Zt=(e,t)=>{let n=s(e),r=0,i=n.getUint32(r,!0);r+=4;let a=c.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=c.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let l=a.slice(0,o).toUpperCase(),u=a.slice(o+1);switch(t.raw??={},t.raw[l]??=u,l){case`TITLE`:t.title??=u;break;case`DESCRIPTION`:t.description??=u;break;case`ARTIST`:t.artist??=u;break;case`ALBUM`:t.album??=u;break;case`ALBUMARTIST`:t.albumArtist??=u;break;case`COMMENT`:t.comment??=u;break;case`LYRICS`:t.lyrics??=u;break;case`TRACKNUMBER`:{let e=u.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(u,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=u.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(u,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(u);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=u;break;case`METADATA_BLOCK_PICTURE`:{let e=Oe(u),n=s(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),l=c.decode(e.subarray(12+i,12+i+o)),d=n.getUint32(i+o+28),f=e.subarray(i+o+32,i+o+32+d);t.images??=[],t.images.push({data:f,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:l||void 0})}break}}},Qt=[2,1,2,3,3,4,4,5],$t=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new O(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},en=[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];new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);let tn=[1,2,3,6],nn=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new O(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=tn[o],d;return d=i<3?pt[i]/1e3:mt[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},rn=e=>{if(e.length<2)return null;let t=new O(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},an=e=>{let n=e.substreams[0];return t(n),n.fscod<3?pt[n.fscod]:n.fscod2!==null&&n.fscod2<3?mt[n.fscod2]:null},on=e=>{let n=e.substreams[0];t(n);let r=Qt[n.acmod]+n.lfeon;if(n.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let t=0;t<9;t++)n.chanLoc&1<<8-t&&(r+=e[t])}return r};
|
|
74
|
+
/*!
|
|
75
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
76
|
+
*
|
|
77
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
78
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
79
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
80
|
+
*/
|
|
81
|
+
var M=class{constructor(e){this.input=e}dispose(){}};
|
|
82
|
+
/*!
|
|
83
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
84
|
+
*
|
|
85
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
86
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
87
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
88
|
+
*/
|
|
89
|
+
let N=new Uint8Array;var P=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===N&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw 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===N}get microsecondTimestamp(){return Math.trunc(ge*this.timestamp)}get microsecondDuration(){return Math.trunc(ge*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`Your browser does not support EncodedAudioChunk.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}};
|
|
90
|
+
/*!
|
|
91
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
92
|
+
*
|
|
93
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
94
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
95
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
96
|
+
*/
|
|
97
|
+
let sn=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},cn=e=>{let t=s(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=y(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(y(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},ln=(e,t)=>e.systemId===t.systemId&&ke(e.data,t.data),un=e=>{
|
|
98
|
+
/*!
|
|
99
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
100
|
+
*
|
|
101
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
102
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
103
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
104
|
+
*/
|
|
105
|
+
let t=Y(e),n=Z(e,4),r=8;t===1&&(t=X(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},dn=e=>Ja(e)/65536,fn=e=>Ja(e)/1073741824,pn=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=q(e);if(t|=n&127,!(n&128))break}return t},F=e=>{let t=J(e);return e.skip(2),t=Math.min(t,e.remainingLength),c.decode(K(e,t))},mn=e=>{let t=un(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=Y(e);e.skip(4);let r=K(e,t.contentSize-8);switch(n){case 1:return c.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new Be(r,`image/jpeg`);case 14:return new Be(r,`image/png`);case 27:return new Be(r,`image/bmp`);default:return r}},hn=new Uint32Array(256),gn=new Uint32Array(256),_n=new Uint32Array(256),vn=new Uint32Array(256),yn=new Uint32Array(256),I=new Uint32Array(256),bn=new Uint32Array(10),xn=!1,Sn=()=>{
|
|
106
|
+
/*!
|
|
107
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
108
|
+
*
|
|
109
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
110
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
111
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
112
|
+
*/
|
|
113
|
+
let e=new Uint8Array(256),t=new Uint8Array(256),n=new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);hn[t]=n<<24|n<<16|n<<8|n,I[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;gn[t]=l,_n[t]=l>>>8|l<<24,vn[t]=l>>>16|l<<16,yn[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)bn[e]=i<<24,i=i<<1^(i&128?283:0);xn=!0};var Cn=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(16),this.out=new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:n}){t(e.byteLength===16),t(n.byteLength===16),xn||Sn();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(n.buffer,n.byteOffset,n.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^hn[t>>>16&255]&4278190080^hn[t>>>8&255]&16711680^hn[t>>>0&255]&65280^hn[t>>>24&255]&255^bn[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=gn[hn[n>>>24&255]&255]^_n[hn[n>>>16&255]&255]^vn[hn[n>>>8&255]&255]^yn[hn[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=gn[e>>>24]^_n[r>>>16&255]^vn[n>>>8&255]^yn[t&255]^this.roundkey[a],l=gn[t>>>24]^_n[e>>>16&255]^vn[r>>>8&255]^yn[n&255]^this.roundkey[a+1],u=gn[n>>>24]^_n[t>>>16&255]^vn[e>>>8&255]^yn[r&255]^this.roundkey[a+2],d=gn[r>>>24]^_n[n>>>16&255]^vn[t>>>8&255]^yn[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=I[e>>>24&255]&4278190080^I[r>>>16&255]&16711680^I[n>>>8&255]&65280^I[t>>>0&255]&255^this.roundkey[40],p=I[t>>>24&255]&4278190080^I[e>>>16&255]&16711680^I[r>>>8&255]&65280^I[n>>>0&255]&255^this.roundkey[41],m=I[n>>>24&255]&4278190080^I[t>>>16&255]&16711680^I[e>>>8&255]&65280^I[r>>>0&255]&255^this.roundkey[42],h=I[r>>>24&255]&4278190080^I[n>>>16&255]&16711680^I[t>>>8&255]&65280^I[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}};let wn=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new Cn;return new ReadableStream({pull:async s=>{r||=(o.init(await t()),!0);let c=a+16,l=e.requestSliceRange(i,0,c);if(l instanceof Promise&&(l=await l),!l||l.length===0)throw Error(`Invalid ciphertext.`);let u=l.length;if(u%16!=0)throw Error(`Invalid ciphertext.`);let d=u===c?u-16:u,f=K(l,d),p=new Uint8Array(d);for(let e=0;e<d;e+=16)o.in.set(f.subarray(e,e+16)),o.decrypt(),p.set(o.out,e);if(d<u)s.enqueue(p),i+=d;else{let e=p[d-1];if(e===0||e>16)throw Error(`Invalid PKCS#7 padding. Incorrect key or corrupted data.`);let t=p.subarray(0,d-e);s.enqueue(t),s.close(),n()}},cancel:()=>{n()}})};
|
|
114
|
+
/*!
|
|
115
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
116
|
+
*
|
|
117
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
118
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
119
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
120
|
+
*/
|
|
121
|
+
var Tn=class e extends M{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(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return sn({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let n=0,r=!1;for(;;){let i=this.reader.requestSliceRange(n,8,16);if(i instanceof Promise&&(i=await i),!i)break;let a=n,o=un(i);if(!o)break;if(o.name===`ftyp`||o.name===`styp`){let e=Z(i,4);this.isQuickTime=e===`qt `}else if(o.name===`moov`){let e=this.reader.requestSlice(i.filePos,o.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}r=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>a+o.totalSize;break}else if(o.name===`moof`){if(!this.input._initInput)throw 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 n=await this.input._initInput._getDemuxer();if(n.constructor!==e)throw Error(`Init input must match the input's format.`);await n.readMetadata(),this.movieTimescale=n.movieTimescale,this.movieDurationInTimescale=n.movieDurationInTimescale,this.metadataTags=n.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=n.fragmentTrackDefaults,this.psshBoxes=n.psshBoxes;for(let e of n.tracks){let n={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};e.trackBacking&&(t(n.info),n.info.type===`video`&&n.info.width!==-1?(n.trackBacking=new Dn(n),this.tracks.push(n)):n.info.type===`audio`&&n.info.numberOfChannels!==-1&&(n.trackBacking=new On(n),this.tracks.push(n)))}r=!1;break}n=a+o.totalSize}if(r){t(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),t(e);let n=Y(e),r=this.reader.fileSize-n;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){let t=un(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let n={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=n,e.sampleTableByteOffset===null)return n;t(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&&qe.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){t(e.info?.type===`audio`);let i=nt(e.info.codec),a=[],o=[];for(let t=0;t<n.sampleToChunk.length;t++){let s=n.sampleToChunk[t],c=n.sampleToChunk[t+1],l=(c?c.startChunkIndex:n.chunkOffsets.length)-s.startChunkIndex;for(let t=0;t<l;t++){let c=s.startSampleIndex+t*s.samplesPerChunk,l=c+s.samplesPerChunk,u=C(n.sampleTimingEntries,c,e=>e.startIndex),d=n.sampleTimingEntries[u],f=C(n.sampleTimingEntries,l,e=>e.startIndex),p=n.sampleTimingEntries[f],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,h=p.startDecodeTimestamp+(l-p.startIndex)*p.delta-m,g=r(a);g&&g.delta===h?g.count++:a.push({startIndex:s.startChunkIndex+t,startDecodeTimestamp:m,count:1,delta:h});let _=s.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;o.push(_)}s.startSampleIndex=s.startChunkIndex,s.samplesPerChunk=1}n.sampleTimingEntries=a,n.sampleSizes=o}if(n.sampleCompositionTimeOffsets.length>0){n.presentationTimestamps=[];for(let e of n.sampleTimingEntries)for(let t=0;t<e.count;t++)n.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+t*e.delta,sampleIndex:e.startIndex+t});for(let e of n.sampleCompositionTimeOffsets)for(let t=0;t<e.count;t++){let r=e.startIndex+t,i=n.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}n.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),n.presentationTimestampIndexMap=Array(n.presentationTimestamps.length).fill(-1);for(let e=0;e<n.presentationTimestamps.length;e++)n.presentationTimestampIndexMap[n.presentationTimestamps[e].sampleIndex]=e}return n}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let n=this.reader.requestSliceRange(e,8,16);n instanceof Promise&&(n=await n),t(n);let r=un(n);t(r?.name===`moof`);let i=this.reader.requestSlice(e,r.totalSize);i instanceof Promise&&(i=await i),t(i),this.traverseBox(i);let a=this.lastReadFragment;t(a&&a.moofOffset===e);for(let[,e]of a.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===a.moofOffset);if(r)Nn(e,r.timestamp);else{let t=C(n,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Nn(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=C(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==a.moofOffset)&&n.splice(r+1,0,{moofOffset:a.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await Ln(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return a}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=un(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let i=e.filePos,a=un(e);if(!a)return!1;let o=e.filePos,l=i+a.totalSize;switch(a.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`mvhd`:{let t=q(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=Y(e),this.movieDurationInTimescale=X(e)):(e.skip(8),this.movieTimescale=Y(e),this.movieDurationInTimescale=Y(e))}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...He,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(o,a.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Dn(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new On(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let r=this.currentTrack;if(!r)break;let i=q(e),a=!!(Wa(e)&1);if(r.disposition.default=a,i===0)e.skip(8),r.id=Y(e),e.skip(4),r.durationInMovieTimescale=Y(e);else if(i===1)e.skip(16),r.id=Y(e),e.skip(4),r.durationInMovieTimescale=X(e);else throw Error(`Incorrect track header version ${i}.`);e.skip(16);let o=[dn(e),dn(e),fn(e),dn(e),dn(e),fn(e),dn(e),dn(e),fn(e)],s=n(ue(Pn(o),90));t(s===0||s===90||s===180||s===270),r.rotation=s}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=q(e);e.skip(3);let r=!1,i=0,a=Y(e);for(let o=0;o<a;o++){let a=n===1?X(e):Y(e),o=n===1?Za(e):Ja(e),s=dn(e);if(a!==0){if(r){D._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){D._warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=q(e);e.skip(3),n===0?(e.skip(8),t.timescale=Y(e),t.durationInMediaTimescale=Y(e)):n===1&&(e.skip(16),t.timescale=Y(e),t.durationInMediaTimescale=X(e));let r=J(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;he(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=Z(e,4);n===`vide`?t.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,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=i,this.readContiguousBoxes(e.slice(o,a.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=q(e);e.skip(3);let r=Y(e);for(let i=0;i<r;i++){let r=e.filePos,i=un(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=J(e),t.info.height=J(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:Ze.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?D._warn(`Unknown encrypted video codec due to missing frma box.`):D._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=J(e);e.skip(6);let s=J(e),c=J(e);e.skip(4);let l=Y(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*Y(e),e.skip(8)):o===2&&(e.skip(4),l=eo(e),s=Y(e),e.skip(4),c=Y(e),u=Y(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`)if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=et;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(D._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(D._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(D._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(D._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(D._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(D._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&D._warn(`Unsupported PCM format.`)}else d===null?D._warn(`Unknown encrypted audio codec due to missing frma box.`):D._warn(`Unsupported audio codec (sample entry type '${i.name}').`)}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=Z(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=Z(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:D._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=q(e);e.skip(3),e.skip(1);let r=q(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=q(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=q(e),t.encryptionInfo.defaultKid=y(K(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=q(e),r=new Uint8Array(16);r.set(K(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let n=this.currentTrack;if(!n)break;t(n.info),n.info.codecDescription=K(e,a.contentSize)}break;case`hvcC`:{let n=this.currentTrack;if(!n)break;t(n.info),n.info.codecDescription=K(e,a.contentSize)}break;case`vpcC`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`video`),e.skip(4);let r=q(e),i=q(e),a=q(e),o=a>>4,s=a>>1&7,c=a&1,l=q(e),u=q(e),d=q(e);n.info.vp9CodecInfo={profile:r,level:i,bitDepth:o,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case`av1C`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`video`),e.skip(1);let r=q(e),i=r>>5,a=r&31,o=q(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;n.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p}}break;case`colr`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`video`);let r=Z(e,4);if(r!==`nclx`&&r!==`nclc`)break;let i=J(e),a=J(e),o=J(e),s;r===`nclx`&&(s=!!(q(e)&128)),n.info.colorSpace={primaries:d[i],transfer:p[a],matrix:h[o],fullRange:s}}break;case`pasp`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`video`);let r=Y(e),i=Y(e);r>0&&i>0&&(r>i?n.info.squarePixelWidth=Math.round(n.info.width*r/i):n.info.squarePixelHeight=Math.round(n.info.height*i/r))}break;case`wave`:this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`esds`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(4),t(q(e)===3),pn(e),e.skip(2);let r=q(e),i=(r&128)!=0,a=(r&64)!=0,o=(r&32)!=0;if(i&&e.skip(2),a){let t=q(e);e.skip(t)}o&&e.skip(2),t(q(e)===4);let s=pn(e),c=e.filePos,l=q(e);if(l===64||l===103?(n.info.codec=`aac`,n.info.aacCodecInfo={isMpeg2:l===103,objectType:null}):l===105||l===107?n.info.codec=`mp3`:l===221?n.info.codec=`vorbis`:D._warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),s>e.filePos-c){t(q(e)===5);let r=pn(e);if(n.info.codecDescription=K(e,r),n.info.codec===`aac`){let e=Ge(n.info.codecDescription);e.numberOfChannels!==null&&(n.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(n.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),n.info.pcmLittleEndian=!!(J(e)&255)}break;case`pcmC`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(4);let r=q(e);n.info.pcmLittleEndian=!!(r&1),n.info.pcmSampleSize=q(e)}break;case`dOps`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(1);let r=q(e),i=J(e),a=Y(e),o=Ga(e),s=q(e),c;c=s===0?new Uint8Array:K(e,2+r);let l=new Uint8Array(19+c.byteLength),u=new DataView(l.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,r),u.setUint16(10,i,!0),u.setUint32(12,a,!0),u.setInt16(16,o,!0),u.setUint8(18,s),l.set(c,19),n.info.codecDescription=l,n.info.numberOfChannels=r}break;case`dfLa`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(4);let r=e.filePos;for(;e.filePos<l;){let t=q(e),r=Wa(e);if((t&127)===Xt.STREAMINFO){e.skip(10);let t=Y(e),r=t>>>12,i=(t>>9&7)+1;n.info.sampleRate=r,n.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(t&128)break}let i=e.filePos;e.filePos=r;let a=K(e,i-r),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),n.info.codecDescription=o}break;case`dac3`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`);let r=new O(K(e,3)),i=r.readBits(2);r.skipBits(8);let a=r.readBits(3),o=r.readBits(1);i<3&&(n.info.sampleRate=pt[i]),n.info.numberOfChannels=Qt[a]+o}break;case`dec3`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`);let r=rn(K(e,a.contentSize));if(!r){D._warn(`Invalid dec3 box contents, ignoring.`);break}let i=an(r);i!==null&&(n.info.sampleRate=i),n.info.numberOfChannels=on(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0,i=0;for(let a=0;a<n;a++){let n=Y(e),a=Y(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0;for(let i=0;i<n;i++){let n=Y(e),i=Ja(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=Y(e);if(n===0)for(let n=0;n<r;n++){let n=Y(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=q(e),r=Y(e),i=new O(K(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1,r=Y(e),i=Y(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=X(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`mehd`:{let t=q(e);e.skip(3);let n=t===1?X(e):Y(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=Y(e),n=Y(e),r=Y(e),i=Y(e),a=Y(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=q(e);e.skip(3);let n=Y(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=Y(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[q,J,Wa,Y],l=c[a],u=c[o],d=c[s],f=Y(e);for(let n=0;n<f;n++){let n=t===1?X(e):Y(e),i=t===1?X(e):Y(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:i,moofSize:a.totalSize,implicitBaseDataOffset:i,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(o,a.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(t(this.currentFragment),this.readContiguousBoxes(e.slice(o,a.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);cond:if(e){if(e.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break cond}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let n=e.samples[e.presentationTimestamps[0].sampleIndex],i=e.samples[r(e.presentationTimestamps).sampleIndex];e.startTimestamp=n.presentationTimestamp,e.endTimestamp=i.presentationTimestamp+i.duration;let{currentFragmentState:a}=this.currentTrack;t(a),a.startTimestamp!==null&&(Nn(e,a.startTimestamp),e.startTimestampIsFinal=!0),a.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=a.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=cn(K(e,a.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{t(this.currentFragment),e.skip(1);let n=Wa(e),r=!!(n&1),i=!!(n&2),a=!!(n&8),o=!!(n&16),s=!!(n&32),c=!!(n&65536),l=!!(n&131072),u=Y(e),d=this.tracks.find(e=>e.id===u);if(!d)break;let f=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:f?.defaultSampleDescriptionIndex??null,defaultSampleDuration:f?.defaultSampleDuration??null,defaultSampleSize:f?.defaultSampleSize??null,defaultSampleFlags:f?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},r?d.currentFragmentState.baseDataOffset=X(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(d.currentFragmentState.sampleDescriptionIndex=Y(e)),a&&(d.currentFragmentState.defaultSampleDuration=Y(e)),o&&(d.currentFragmentState.defaultSampleSize=Y(e)),s&&(d.currentFragmentState.defaultSampleFlags=Y(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let n=this.currentTrack;if(!n)break;t(n.currentFragmentState);let r=q(e);e.skip(3);let i=r===0?Y(e):X(e);n.currentFragmentState.startTimestamp=i}break;case`trun`:{let n=this.currentTrack;if(!n)break;t(this.currentFragment),t(n.currentFragmentState);let r=q(e),i=Wa(e),a=!!(i&1),o=!!(i&4),s=!!(i&256),c=!!(i&512),l=!!(i&1024),u=!!(i&2048),d=Y(e),f=null;a&&(f=Ja(e));let p=null;o&&(p=Y(e));let m;this.currentFragment.trackData.has(n.id)?(m=this.currentFragment.trackData.get(n.id),f!==null&&(m.currentOffset=n.currentFragmentState.baseDataOffset+f)):(m={track:n,currentTimestamp:0,currentOffset:n.currentFragmentState.baseDataOffset+(f??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(n.id,m));for(let i=0;i<d;i++){let a;s?a=Y(e):(t(n.currentFragmentState.defaultSampleDuration!==null),a=n.currentFragmentState.defaultSampleDuration);let o;c?o=Y(e):(t(n.currentFragmentState.defaultSampleSize!==null),o=n.currentFragmentState.defaultSampleSize);let d;l?d=Y(e):(t(n.currentFragmentState.defaultSampleFlags!==null),d=n.currentFragmentState.defaultSampleFlags),i===0&&p!==null&&(d=p);let f=0;u&&(f=r===0?Y(e):Ja(e));let h=!(d&65536);m.samples.push({presentationTimestamp:m.currentTimestamp+f,duration:a,byteOffset:m.currentOffset,byteSize:o,isKeyFrame:h,encryption:null}),m.currentOffset+=o,m.currentTimestamp+=a}this.currentFragment.implicitBaseDataOffset=m.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),Wa(e)&1){let n=Z(e,4),r=Y(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=q(e),r=Y(e),i=null;n===0&&r>0&&(i=K(e,r));let a=In(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=q(e);if(Wa(e)&1){let n=Z(e,4),r=Y(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=Y(e);if(r===0)break;r>1&&D._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?Y(e):Number(X(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=In(t);a.offset=i}break;case`senc`:{let n=this.currentTrack;if(!n||!n.encryptionInfo)break;t(this.currentFragment);let r=this.currentFragment.trackData.get(n.id);if(!r)break;e.skip(1);let i=!!(Wa(e)&2),a=Y(e),o=n.encryptionInfo.defaultPerSampleIvSize;t(o!==null);for(let t=0;t<Math.min(a,r.samples.length);t++){let a=new Uint8Array(16);o>0?a.set(K(e,o),0):a.set(n.encryptionInfo.defaultConstantIv,0);let s=null;if(i){let t=J(e);s=[];for(let n=0;n<t;n++){let t=J(e),n=Y(e);s.push({clearLen:t,protectedLen:n})}}let c=r.samples[t];c.encryption={iv:a,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(o,a.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=F(n):this.metadataTags.raw[e.name]??=K(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=c.decode(K(n,e.contentSize)):this.metadataTags.title??=F(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=F(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=F(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=F(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=F(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=F(n));break;case`©day`:if(!this.currentTrack){let e=new Date(F(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=F(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=F(n));break}}}break;case`meta`:{if(this.currentTrack)break;let t=Y(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(o,a.contentSize)):this.readContiguousBoxes(e.slice(o+4,a.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=Y(e);for(let n=0;n<t;n++){let t=Y(e);e.skip(4);let r=c.decode(K(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(o,a.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=mn(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof Be?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=s(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=s(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}break}}}break}return e.filePos=l,!0}},En=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(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}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:(t(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,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return le(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=kn(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Fn(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=C(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.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 n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=An(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Fn(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=te(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,n){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),t=Mn(e,r);return this.fetchPacketForSampleIndex(t,n)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>i.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let n=e.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let e=n.samples.findIndex(e=>e.isKeyFrame);return t(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,n)}async fetchPacketForSampleIndex(e,n){if(e===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=jn(r,e);if(!i)return null;let a;if(n.metadataOnly)a=N;else{let n=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(n instanceof Promise&&(n=await n),!n)return null;if(a=K(n,i.sampleSize),this.internalTrack.encryptionAuxInfo){t(this.internalTrack.encryptionInfo);let n=await Ln(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(a=await Rn(this.internalTrack,n[e],a,null))}}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new P(a,i.isKeyFrame?`key`:`delta`,o,s,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,n,r){if(n===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[n];t(i);let a;if(r.metadataOnly)a=N;else{let t=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;a=K(t,i.byteSize),i.encryption&&(a=await Rn(this.internalTrack,i.encryption,a,e))}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new P(a,i.isKeyFrame?`key`:`delta`,o,s,e.moofOffset+n,i.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:n}),c}async performFragmentedLookup(e,n,r,i,a){let o=this.internalTrack.demuxer,s=null,c=null,l=-1;if(e){let{sampleIndex:t,correctSampleFound:r}=n(e);if(r)return this.fetchPacketInFragment(e,t,a);t!==-1&&(c=e,l=t)}let u=C(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),d=u===-1?null:this.internalTrack.fragmentLookupTable[u],f=C(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.fragmentPositionCache[f],m=Math.max(d?.moofOffset??0,p?.moofOffset??0)||null,h;for(e?m===null||e.moofOffset>=m?(h=e.moofOffset+e.moofSize,s=e):h=m:h=m??0;;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=o.reader.requestSliceRange(h,8,16);if(e instanceof Promise&&(e=await e),!e)break;let t=h,r=un(e);if(!r)break;if(r.name===`moof`){s=await o.readFragment(t);let{sampleIndex:e,correctSampleFound:r}=n(s);if(r)return this.fetchPacketInFragment(s,e,a);e!==-1&&(c=s,l=e)}h=t+r.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let e=this.internalTrack.fragmentLookupTable[u-1];t(!e||e.timestamp<d.timestamp);let r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,n,r,i,a)}return c?this.fetchPacketInFragment(c,l,a):null}},Dn=class extends En{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 this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Ht(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Wt(e.data)}let e={codec:Qe(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}},On=class extends En{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:$e(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};let kn=(e,t)=>{if(e.presentationTimestamps){let n=C(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}else{let n=C(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},An=(e,t)=>{if(!e.keySampleIndices)return kn(e,t);if(e.presentationTimestamps){let n=C(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(S(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}else{let n=kn(e,t),r=C(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},jn=(e,n)=>{let r=C(e.sampleTimingEntries,n,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=n)return null;let a=i.startDecodeTimestamp+(n-i.startIndex)*i.delta,o=C(e.sampleCompositionTimeOffsets,n,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[o];s&&n-s.startIndex<s.count&&(a+=s.offset);let c=e.sampleSizes[Math.min(n,e.sampleSizes.length-1)],l=C(e.sampleToChunk,n,e=>e.startSampleIndex),u=e.sampleToChunk[l];t(u);let d=u.startChunkIndex+Math.floor((n-u.startSampleIndex)/u.samplesPerChunk),f=e.chunkOffsets[d],p=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,m=0,h=f;if(e.sampleSizes.length===1)h+=c*(n-p),m+=c*u.samplesPerChunk;else for(let t=p;t<p+u.samplesPerChunk;t++){let r=e.sampleSizes[t];t<n&&(h+=r),m+=r}let g=i.delta;if(e.presentationTimestamps){let r=e.presentationTimestampIndexMap[n];t(r!==void 0),r<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[r+1].presentationTimestamp-a)}return{presentationTimestamp:a,duration:g,sampleOffset:h,sampleSize:c,chunkOffset:f,chunkSize:m,isKeyFrame:!e.keySampleIndices||S(e.keySampleIndices,n,e=>e)!==-1}},Mn=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=C(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Nn=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Pn=e=>{let[t,n]=e,r=Math.atan2(n,t);return Number.isFinite(r)?180/Math.PI*r:0},Fn=e=>e.sampleSizes.length===0,In=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Ln=async(e,n,r)=>{if(r.resolved)return r.resolved;if(r.offset===null||r.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let i=0;if(r.defaultSampleInfoSize>0)i=r.defaultSampleInfoSize*r.sampleCount;else{t(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)i+=r.sampleSizes[e]}let a=e.requestSlice(r.offset,i);if(a instanceof Promise&&(a=await a),!a)throw Error(`Failed to read auxiliary encryption info.`);let o=n.defaultPerSampleIvSize;t(o!==null);let s=[];for(let e=0;e<r.sampleCount;e++){let t=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],i=new Uint8Array(16);o>0?i.set(K(a,o),0):i.set(n.defaultConstantIv,0);let c=null;if(t>o){let e=J(a);c=[];for(let t=0;t<e;t++){let e=J(a),t=Y(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},Rn=async(e,n,r,i)=>{t(e.encryptionInfo);let a=e.encryptionInfo;t(a.defaultKid!==null);let o=a.defaultKid,s,c=e.demuxer.decryptionKeyCache.get(o);if(c)s=await c;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(i){t=[...t,...i.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(o));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)ln(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:o,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&v.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:b(n)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return a.scheme===`cenc`||a.scheme===`cens`?zn(s,a,n,r):Bn(s,a,n,r)},zn=async(e,n,r,i)=>{let a=new Uint8Array(16);a.set(r.iv,0);let o=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),s=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:a,length:64},o,e);return new Uint8Array(t)};if(!r.subsamples)return s(i);t(n.defaultCryptByteBlock!==null&&n.defaultSkipByteBlock!==null);let c=Vn(r.subsamples,n.defaultCryptByteBlock,n.defaultSkipByteBlock),l=0;for(let e of c)for(let t of e.perSubsample)l+=t.length;let u=new Uint8Array(l),d=0;for(let e of c)for(let t of e.perSubsample)u.set(i.subarray(t.offset,t.offset+t.length),d),d+=t.length;let f=await s(u),p=new Uint8Array(i),m=0;for(let e of c)for(let t of e.perSubsample)p.set(f.subarray(m,m+t.length),t.offset),m+=t.length;return p},Bn=(e,n,r,i)=>{let a=new Cn;a.init({key:e,iv:r.iv});let o=n.defaultCryptByteBlock,s=n.defaultSkipByteBlock;if(t(o!==null&&s!==null),!r.subsamples){let e=new Uint8Array(i),t=Math.floor(i.length/16);for(let n=0;n<t;n++){let t=n*16;a.in.set(i.subarray(t,t+16)),a.decrypt(),e.set(a.out,t)}return e}if(o===0&&s===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let c=new Uint8Array(i),l=Vn(r.subsamples,o,s),u=new DataView(r.iv.buffer,r.iv.byteOffset,16);for(let e of l){a.iv[0]=u.getUint32(0,!1),a.iv[1]=u.getUint32(4,!1),a.iv[2]=u.getUint32(8,!1),a.iv[3]=u.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;a.in.set(i.subarray(e,e+16)),a.decrypt(),c.set(a.out,e)}}}return c},Vn=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r};
|
|
122
|
+
/*!
|
|
123
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
124
|
+
*
|
|
125
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
126
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
127
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
128
|
+
*/
|
|
129
|
+
var L;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(L||={});let Hn=[L.EBML,L.Segment],Un=[L.SeekHead,L.Info,L.Cluster,L.Tracks,L.Cues,L.Attachments,L.Chapters,L.Tags],Wn=[...Hn,...Un],Gn=e=>{if(e.remainingLength<1)return null;let t=q(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},Kn=e=>{if(e.remainingLength<1)return null;let t=q(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=q(e);return i},R=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=q(e);return n},qn=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(q(e));return n},Jn=e=>{let t=Gn(e);return t===null||e.remainingLength<t?null:R(e,t)},Yn=e=>{if(e.remainingLength<1)return null;if(q(e)===255)return;e.skip(-1);let t=Kn(e);if(t===null)return null;if(t!==72057594037927940)return t},Xn=e=>{t(e.remainingLength>=2);let n=Jn(e);if(n===null)return null;let r=Yn(e);return r===null?null:{id:n,size:r}},Zn=(e,t)=>{let n=K(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Qn=(e,t)=>{let n=K(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return c.decode(n.subarray(0,r))},$n=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?$a(e):eo(e)},er=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=Xn(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};nr(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},tr=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=Jn(t);if(e!==null&&a.has(e))return o;o++}}return null},z={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,prores:`V_PRORES`,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 nr(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}
|
|
130
|
+
/*!
|
|
131
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
132
|
+
*
|
|
133
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
134
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
135
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
136
|
+
*/
|
|
137
|
+
let rr=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t};
|
|
138
|
+
/*!
|
|
139
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
140
|
+
*
|
|
141
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
142
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
143
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
144
|
+
*/
|
|
145
|
+
var ir;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(ir||={});var ar;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(ar||={});var or;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(or||={});let sr=[{id:L.SeekHead,flag:`seekHeadSeen`},{id:L.Info,flag:`infoSeen`},{id:L.Tracks,flag:`tracksSeen`},{id:L.Cues,flag:`cuesSeen`}],cr=10*2**20;var lr=class extends M{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(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return rr({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!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,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=Xn(t);if(!n)break;let i=n.id,a=n.size,o=t.filePos;if(i===L.EBML){nr(a);let e=this.reader.requestSlice(o,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(i===L.Segment){if(await this.readSegment(o,a),a===void 0||this.reader.fileSize===null)break}else if(i===L.Cluster){if(this.reader.fileSize===null)break;a===void 0&&(a=(await er(this.reader,o,Wn,this.reader.fileSize)).pos-o);let e=r(this.segments);e&&(e.elementEndPos=o+a)}nr(a),e=o+a}})()}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 n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=Xn(e);if(!r||!Un.includes(r.id)&&r.id!==L.Void){let e=await tr(this.reader,t,Un,Math.min(this.currentSegment.elementEndPos??1/0,t+cr));if(e){n=e;continue}else break}let{id:i,size:a}=r,o=e.filePos,s=sr.findIndex(e=>e.id===i);if(s!==-1){let e=sr[s].flag;this.currentSegment[e]=!0,nr(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===L.Tags||i===L.Attachments){i===L.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,nr(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===L.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=sr.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=Xn(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;nr(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,n){if(n.lastReadCluster?.elementStartPos===e)return n.lastReadCluster;let i=this.reader.requestSliceRange(e,2,16);i instanceof Promise&&(i=await i),t(i);let a=e,o=Xn(i);t(o);let s=o.id;t(s===L.Cluster);let c=o.size,l=i.filePos;c===void 0&&(c=(await er(this.reader,l,Wn,n.elementEndPos)).pos-l);let u=this.reader.requestSlice(l,c);u instanceof Promise&&(u=await u);let d={segment:n,elementStartPos:a,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};this.currentCluster=d,u&&(d.elementEndPos=this.readContiguousElements(u,Wn));for(let[,e]of d.trackData){let n=e.track;t(e.blocks.length>0);let i=!1;for(let t=0;t<e.blocks.length;t++){let n=e.blocks[t];n.timestamp+=d.timestamp,i||=n.lacing!==ir.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let r=e.presentationTimestamps[t],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),t<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[t+1].timestamp-i.timestamp:i.duration===0&&n.defaultDuration!=null&&i.lacing===ir.None&&(i.duration=n.defaultDuration)}i&&(this.expandLacedBlocks(e.blocks,n),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let o=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[r(e.presentationTimestamps).blockIndex];e.startTimestamp=o.timestamp,e.endTimestamp=s.timestamp+s.duration;let c=C(n.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(c===-1||n.clusterPositionCache[c].elementStartPos!==a)&&n.clusterPositionCache.splice(c+1,0,{elementStartPos:d.elementStartPos,startTimestamp:e.startTimestamp})}return n.lastReadCluster=d,d}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,n){for(let r=0;r<e.length;r++){let i=e[r];if(i.lacing===ir.None)continue;i.decoded||=(i.data=this.decodeBlockData(n,i.data),!0);let a=Ha.tempFromBytes(i.data),o=[],s=q(a)+1;switch(i.lacing){case ir.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){let n=q(a);if(t+=n,n<255){o.push(t),e+=t;break}}}o.push(a.length-(a.bufferPos+e))}break;case ir.FixedSize:{let e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)o.push(t)}break;case ir.Ebml:{let e=Kn(a);t(e!==null);let n=e;o.push(n);let r=n;for(let e=1;e<s-1;e++){let e=a.bufferPos,i=Kn(a);t(i!==null);let s=i-((1<<(a.bufferPos-e)*7-1)-1);n+=s,o.push(n),r+=n}o.push(a.length-(a.bufferPos+r))}break;default:t(!1)}t(o.length===s),e.splice(r,1);let c=i.duration||s*(n.defaultDuration??0);for(let t=0;t<s;t++){let n=o[t],l=K(a,n),u=i.timestamp+c*t/s,d=c/s;e.splice(r+t,0,{timestamp:u,duration:d,isKeyFrame:i.isKeyFrame,data:l,lacing:ir.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(let n of e.seekEntries){if(!(n.id===L.Tags&&!e.tagsSeen)&&!(n.id===L.Attachments&&!e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+n.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=Xn(r);if(!i||i.id!==n.id)continue;let{size:a}=i;nr(a),t(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,a);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,n.id===L.Tags?e.tagsSeen=!0:n.id===L.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,r){let i=Xn(e);if(!i||r&&r.includes(i.id))return!1;let{id:a,size:o}=i,s=e.filePos;switch(nr(o),a){case L.DocType:this.isWebM=Zn(e,o)===`webm`;break;case L.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,o)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case L.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=R(e,o)}break;case L.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=R(e,o)}break;case L.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=R(e,o),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case L.Duration:if(!this.currentSegment)break;this.currentSegment.duration=$n(e,o);break;case L.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...He,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(s,o)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==ar.Block||e.data.algorithm!==or.HeaderStripping)&&(D._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 e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);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 e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===z.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===z.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===z.vp8)this.currentTrack.info.codec=`vp8`;else if(t===z.vp9)this.currentTrack.info.codec=`vp9`;else if(t===z.av1)this.currentTrack.info.codec=`av1`;else if(t===z.prores){let e=this.currentTrack.codecPrivate?c.decode(this.currentTrack.codecPrivate):``;Ze.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new dr(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===z.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===z.mp3?this.currentTrack.info.codec=`mp3`:t===z.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=et):t===z.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===z.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===z.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===z.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 e=this.currentTrack;this.currentTrack.trackBacking=new fr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case L.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=R(e,o);break;case L.TrackType:{if(!this.currentTrack)break;let t=R(e,o);t===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,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case L.FlagEnabled:if(!this.currentTrack)break;R(e,o)||(this.currentTrack=null);break;case L.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!R(e,o);break;case L.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!R(e,o);break;case L.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!R(e,o);break;case L.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!R(e,o);break;case L.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!R(e,o);break;case L.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!R(e,o);break;case L.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Zn(e,o);break;case L.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=K(e,o);break;case L.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=R(e,o);break;case L.Name:if(!this.currentTrack)break;this.currentTrack.name=Qn(e,o);break;case L.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zn(e,o),he(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case L.LanguageBCP47:{if(!this.currentTrack)break;let t=Zn(e,o).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case L.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case L.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=R(e,o);break;case L.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=R(e,o);break;case L.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=R(e,o);break;case L.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=R(e,o);break;case L.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=R(e,o);break;case L.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=R(e,o)===1;break;case L.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,o));break;case L.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=h[R(e,o)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case L.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=R(e,o)===2;break;case L.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=p[R(e,o)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case L.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=d[R(e,o)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case L.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case L.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-$n(e,o);try{this.currentTrack.info.rotation=n(t)}catch{}}break;case L.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(s,o));break;case L.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=$n(e,o);break;case L.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=R(e,o);break;case L.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=R(e,o);break;case L.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,o)),this.currentCueTime=null;break;case L.CueTime:this.currentCueTime=R(e,o);break;case L.CueTrackPositions:{if(this.currentCueTime===null)break;t(this.currentSegment);let n={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(n),this.readContiguousElements(e.slice(s,o)),(n.trackId===-1||n.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case L.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=R(e,o)}break;case L.CueClusterPosition:{let n=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!n)break;t(this.currentSegment),n.clusterPosition=this.currentSegment.dataStartPos+R(e,o)}break;case L.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=R(e,o);break;case L.SimpleBlock:{if(!this.currentCluster)break;let t=Kn(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Ga(e),i=q(e),a=i>>1&3,c=!!(i&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=K(e,o-(e.filePos-s)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:a,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case L.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,o)),this.currentBlock=null;break;case L.Block:{if(!this.currentCluster)break;let t=Kn(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Ga(e),i=q(e)>>1&3,a=K(e,o-(e.filePos-s)),c=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:a,lacing:i,decoded:!c,postProcessed:!1,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case L.BlockAdditions:this.readContiguousElements(e.slice(s,o));break;case L.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,o)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case L.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=K(e,o);break;case L.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=R(e,o);break;case L.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=R(e,o);break;case L.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case L.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,o));break;case L.Targets:this.readContiguousElements(e.slice(s,o));break;case L.TargetTypeValue:R(e,o)!==50&&(this.currentTagTargetIsMovie=!1);break;case L.TagTrackUID:case L.TagEditionUID:case L.TagChapterUID:case L.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case L.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,o));break;case L.TagName:this.currentSimpleTagName=Qn(e,o);break;case L.TagString:{if(!this.currentSimpleTagName)break;let t=Qn(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case L.TagBinary:{if(!this.currentSimpleTagName)break;let t=K(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case L.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,o));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Ve(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 e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case L.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=qn(e,o);break;case L.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Qn(e,o);break;case L.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Zn(e,o);break;case L.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=K(e,o);break;case L.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Qn(e,o);break;case L.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,o)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case L.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ar.Block,data:null},this.readContiguousElements(e.slice(s,o)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case L.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=R(e,o);break;case L.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=R(e,o);break;case L.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:or.Zlib,settings:null},this.readContiguousElements(e.slice(s,o));break;case L.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=R(e,o);break;case L.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=K(e,o);break;case L.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`};break}return e.filePos=s+o,!0}decodeBlockData(e,n){t(e.decodingInstructions.length>0);let r=n;for(let n of e.decodingInstructions)switch(t(n.data),n.data.type){case`decompress`:switch(n.data.algorithm){case or.HeaderStripping:if(n.data.settings&&n.data.settings.length>0){let e=n.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}break;default:}break;default:}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},ur=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(),n=0;for(let r of e.segments)for(let e of r.tracks)if(e.trackBacking.getType()===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw 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,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return le(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=C(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.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 n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=te(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,n){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let n=e.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){let e=n.blocks.findIndex(e=>e.isKeyFrame);return t(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,n)}async fetchPacketInCluster(e,n,r){if(n===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[n];if(t(i),i.decoded||=(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),!0),!i.postProcessed){if(this.internalTrack.info?.codec===`prores`&&!(i.data.length>=8&&i.data[4]===105&&i.data[5]===99&&i.data[6]===112&&i.data[7]===102)){let e=new Uint8Array(i.data.length+8);s(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(i.data,8),i.data=e}i.postProcessed=!0}let a=r.metadataOnly?N:i.data,o=i.timestamp/this.internalTrack.segment.timestampFactor,c=i.duration/this.internalTrack.segment.timestampFactor,l={};i.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(l.alpha=r.metadataOnly?N:i.mainAdditional,l.alphaByteLength=i.mainAdditional.byteLength);let u=new P(a,i.isKeyFrame?`key`:`delta`,o,c,e.dataStartPos+n,i.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:n}),u}async performClusterLookup(e,n,r,i,a){let{demuxer:o,segment:s}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:t,correctBlockFound:r}=n(e);if(r)return this.fetchPacketInCluster(e,t,a);t!==-1&&(l=e,u=t)}let d=C(this.internalTrack.cuePoints,r,e=>e.time),f=d===-1?null:this.internalTrack.cuePoints[d],p=C(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),m=p===-1?null:this.internalTrack.clusterPositionCache[p],h=Math.max(f?.clusterPosition??0,m?.elementStartPos??0)||null,g;for(e?h===null||e.elementStartPos>=h?(g=e.elementEndPos,c=e):g=h:g=h??s.clusterSeekStartPos;s.elementEndPos===null||g<=s.elementEndPos-2;){if(c){let e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=o.reader.requestSliceRange(g,2,16);if(e instanceof Promise&&(e=await e),!e)break;let r=g,d=Xn(e);if(!d||!Un.includes(d.id)&&d.id!==L.Void){let e=await tr(o.reader,r,Un,Math.min(s.elementEndPos??1/0,r+cr));if(e){g=e;continue}else break}let f=d.id,p=d.size,m=e.filePos;if(f===L.Cluster){c=await o.readCluster(r,s),p=c.elementEndPos-m;let{blockIndex:e,correctBlockFound:t}=n(c);if(t)return this.fetchPacketInCluster(c,e,a);e!==-1&&(l=c,u=e)}p===void 0&&(t(f!==L.Cluster),p=(await er(o.reader,m,Wn,s.elementEndPos)).pos-m);let h=m+p;if(s.elementEndPos===null){let e=o.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(Jn(e)===L.Segment){s.elementEndPos=h;break}}g=h}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let e=this.internalTrack.cuePoints[d-1];t(!e||e.time<f.time);let r=e?.time??-1/0;return this.performClusterLookup(null,n,r,i,a)}return l?this.fetchPacketInCluster(l,u,a):null}},dr=class extends ur{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||this.internalTrack.info.codec===`prores`&&(this.internalTrack.info.proresFormat===`ap4h`||this.internalTrack.info.proresFormat===`ap4x`)}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 t={codec:Qe({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?wt(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Nt(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?Ht(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?Wt(e.data):null,proresFormat:this.internalTrack.info.proresFormat}),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)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}},fr=class extends ur{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:$e({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}};
|
|
146
|
+
/*!
|
|
147
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
148
|
+
*
|
|
149
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
150
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
151
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
152
|
+
*/
|
|
153
|
+
let pr=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===null?i:Math.min(i,n-a),o=e.requestSliceRange(a,4,t);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=lt(Y(o),e.fileSize===null?null:e.fileSize-a);if(n.header&&(!r||n.header.sampleRate===r.sampleRate&&n.header.mpegVersionId===r.mpegVersionId&&n.header.layer===r.layer&&ft(n.header.channel)===ft(r.channel)))return{header:n.header,startPos:a};o.filePos=t+n.bytesAdvanced,a=o.filePos}}return null};
|
|
154
|
+
/*!
|
|
155
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
156
|
+
*
|
|
157
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
158
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
159
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
160
|
+
*/
|
|
161
|
+
var mr=class extends M{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 _,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 Error(`No valid MP3 frame found.`);this.trackBackings=[new hr(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Q(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await pr(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 n=ct(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let t=Y(r);if(t===1483304551||t===1231971951){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+n+4,12);if(t instanceof Promise&&(t=await t),t){let e=s(K(t,12)),n=e.getUint32(0,!1);this.xingData={frameCount:n&dt.FrameCount?e.getUint32(4,!1):null,fileSize:n&dt.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,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 e=0,n=!1;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let r=Q(t);if(!r)break;n=!0;let i=this.reader.requestSlice(t.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;so(i,r,this.metadataTags),e=t.filePos+r.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),t(e),Z(e,3)===`TAG`&&ao(e,this.metadataTags)}return this.metadataTags}finally{e()}}},hr=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return t(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(t(e.firstFrameHeader!==null),t(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=st(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.firstFrameHeader),ft(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...He}}async getDecoderConfig(){return t(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:ft(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=N;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=K(e,n.dataSize)}return new P(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=S(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=C(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
|
|
162
|
+
/*!
|
|
163
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
164
|
+
*
|
|
165
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
166
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
167
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
168
|
+
*/
|
|
169
|
+
;let gr=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^79764919:t<<1;gr[e]=t>>>0&4294967295}let _r=e=>{let t=s(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^gr[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},vr=(e,n,r)=>{let i=0,a=null;if(e.length>0)if(n.codec===`vorbis`){t(n.vorbisInfo);let o=n.vorbisInfo.modeBlockflags.length,s=(1<<pe(o-1))-1<<1,c=(e[0]&s)>>1;if(c>=n.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let l=r,u=n.vorbisInfo.modeBlockflags[c];if(a=n.vorbisInfo.blocksizes[u],u===1){let t=(s|1)+1,r=e[0]&t?1:0;l=n.vorbisInfo.blocksizes[r]}i=l===null?0:l+a>>2}else n.codec===`opus`&&(i=qt(e).durationInSamples);return{durationInSamples:i,vorbisBlockSize:a}},yr=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},br=e=>{
|
|
170
|
+
/*!
|
|
171
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
172
|
+
*
|
|
173
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
174
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
175
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
176
|
+
*/
|
|
177
|
+
let t=e.filePos;if(qa(e)!==1399285583)return null;e.skip(1);let n=q(e),r=Qa(e),i=qa(e),a=qa(e),o=qa(e),s=q(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=q(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},xr=(e,t)=>{for(;e.filePos<t-3;){let t=qa(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(!(n!==79&&r!==79&&i!==79&&a!==79)){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1};
|
|
178
|
+
/*!
|
|
179
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
180
|
+
*
|
|
181
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
182
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
183
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
184
|
+
*/
|
|
185
|
+
var Sr=class extends M{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,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=br(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.trackBackings.push(new Cr(e,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let c=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(r.data,1+a.length+e.data.length),c.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=c,t.lastMetadataPacket=i;let l=s(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:Jt(i.data).modeBlockflags},Zt(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=Gt(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=et,t.codecInfo.opusInfo={preSkip:i.preSkip},Zt(r.data.subarray(8),this.metadataTags)}async readPacket(e,n){t(n<e.lacingValues.length);let r=0;for(let t=0;t<n;t++)r+=e.lacingValues[t];let i=e,a=r,o=n,s=[];outer:for(;;){let n=this.reader.requestSlice(i.dataStartPos,i.dataSize);n instanceof Promise&&(n=await n),t(n);let c=K(n,i.dataSize);for(;;){if(o===i.lacingValues.length){s.push(c.subarray(r,a));break}let e=i.lacingValues[o];if(a+=e,e<255){s.push(c.subarray(r,a));break outer}o++}let l=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(l,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=br(t);if(!n)return null;if(i=n,i.serialNumber===e.serialNumber)break;l=i.headerStartPos+i.totalSize}r=0,a=0,o=0}let c=s.reduce((e,t)=>e+t.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let e=0;e<s.length;e++){let t=s[e];l.set(t,u),u+=t.length}return{data:l,endPage:i,endSegmentIndex:o}}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 t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=br(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),yr({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Cr=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new _,this.internalSampleRate=e.codecInfo.codec===`opus`?et:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return t(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 t(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`und`}getDisposition(){return{...He,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(t(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=vr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new P(n.metadataOnly?N:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){t(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let r=0;this.bitstream.codecInfo.codec===`opus`&&(t(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,n){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,n);let r=le(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(n);if(r<0)return null;t(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let a=i.startPage,o=this.demuxer.reader.fileSize,s=[a];outer:for(;a.headerStartPos+a.totalSize<o;){let e=a.headerStartPos,n=Math.floor((e+o)/2),i=n;for(;;){let e=Math.min(i+65307,o-27),c=this.demuxer.reader.requestSlice(i,e-i);if(c instanceof Promise&&(c=await c),t(c),!xr(c,e)){o=n+27;continue outer}let l=this.demuxer.reader.requestSliceRange(c.filePos,27,282);l instanceof Promise&&(l=await l),t(l);let u=br(l);t(u);let d=!1;if(u.serialNumber===this.bitstream.serialNumber)d=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);e instanceof Promise&&(e=await e),t(e),d=_r(K(e,u.totalSize))===u.checksum}if(!d){i=u.headerStartPos+4;continue}if(d&&u.serialNumber!==this.bitstream.serialNumber){i=u.headerStartPos+u.totalSize;continue}if(u.granulePosition===-1){i=u.headerStartPos+u.totalSize;continue}this.granulePositionToTimestampInSamples(u.granulePosition)>r?o=u.headerStartPos:(a=u,s.push(u));continue outer}}let c=i.startPage;for(let e of s){if(e.granulePosition===a.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let l=c,u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===a.granulePosition);){let e=l.headerStartPos+l.totalSize,n=this.demuxer.reader.requestSliceRange(e,27,282);n instanceof Promise&&(n=await n),t(n);let r=br(n);t(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}t(l.granulePosition!==-1);let d=null,f,p,m=l,h=0;if(l.headerStartPos===i.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),p=!0,d=0;else{f=0,p=!1;for(let e=l.lacingValues.length-1;e>=0;e--)if(l.lacingValues[e]<255){d=e+1;break}if(d===null)throw Error(`Invalid page with granule position: no packets end on this page.`);h=d-1;let e={data:N,endPage:m,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(e)){let e=Tr(u,l,d);t(e);let n=wr(u,e.page,e.segmentIndex);n&&(l=n.page,d=n.segmentIndex)}else for(;;){let e=Tr(u,l,d);if(!e)break;let t=wr(u,e.page,e.segmentIndex);if(!t)break;if(l=t.page,d=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,h=e.segmentIndex;break}}}let g=null,_=null;for(;l!==null;){t(d!==null);let e=await this.demuxer.readPacket(l,d);if(!e)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:f,vorbisLastBlocksize:_?.vorbisBlockSize??null},n);t(i);let a=this.encodedPacketToMetadata.get(i);if(t(a),!p&&e.endPage.headerStartPos===m.headerStartPos&&e.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(l.granulePosition),p=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:f-a.durationInSamples,vorbisLastBlocksize:_?.vorbisBlockSize??null},n),t(i),a=this.encodedPacketToMetadata.get(i),t(a)):f+=a.durationInSamples,g=i,_=a,p&&(Math.max(f,0)>r||Math.max(a.timestampInSamples,0)===r))break}let a=await this.demuxer.findNextPacketStart(e);if(!a)break;l=a.startPage,d=a.startSegmentIndex}return g}async getPacketSequential(e,n){let i=await this.sequentialScanMutex.acquire();try{let i=le(e*this.internalSampleRate);e=i/this.internalSampleRate;let a=C(this.sequentialScanCache,i,e=>e.timestampInSamples),o;if(a!==-1){let e=this.sequentialScanCache[a];o=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},n)}else o=await this.getFirstPacket(n);let s=0;for(;o&&o.timestamp<e;){let i=await this.getNextPacket(o,n);if(!i||i.timestamp>e)break;if(o=i,s++,s===100){s=0;let e=this.encodedPacketToMetadata.get(o);t(e),this.sequentialScanCache.length>0&&t(r(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return o}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};let wr=(e,n,r)=>{let i=n,a=r;outer:for(;;){for(a--;a>=0;a--)if(i.lacingValues[a]<255){a++;break outer}if(t(a===-1),!(i.headerType&1)){a=0;break}let n=E(e,e=>e.headerStartPos<i.headerStartPos);if(!n)return null;i=n,a=i.lacingValues.length}if(t(a!==-1),a===i.lacingValues.length){let n=e[e.indexOf(i)+1];t(n),i=n,a=0}return{page:i,segmentIndex:a}},Tr=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=E(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};
|
|
186
|
+
/*!
|
|
187
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
188
|
+
*
|
|
189
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
190
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
191
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
192
|
+
*/
|
|
193
|
+
var B;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(B||={});var Er=class extends M{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),t(e);let n=Z(e,4),r=n!==`RIFX`,i=n===`RF64`,a=Ka(e,r),o=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if(Z(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let s=0,c=null,l=e.filePos;for(;o===null||l<o;){let e=this.reader.requestSlice(l,8);if(e instanceof Promise&&(e=await e),!e)break;let t=Z(e,4),n=Ka(e,r),a=e.filePos;if(i&&s===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(a,n,r);else if(t===`data`){if(c??=n,this.dataStart=e.filePos,this.dataSize=Math.min(c,(o??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(a,n);if(e instanceof Promise&&(e=await e),!e)break;let t=Xa(e,r);c=Xa(e,r),o=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(a,n,r):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(a,n);l=a+n+(n&1),s++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.trackBackings.push(new Or(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=Ua(r,n),a=Ua(r,n),o=Ka(r,n);r.skip(4);let s=Ua(r,n),c;if(c=t===14?8:Ua(r,n),t>=18&&i!==357){let e=Ua(r,n),a=t-18;if(Math.min(a,e)>=22&&i===B.EXTENSIBLE){r.skip(6);let e=K(r,16);i=e[0]|e[1]<<8}}if((i===B.MULAW||i===B.ALAW)&&(c=8),i!==B.PCM&&i!==B.IEEE_FLOAT&&i!==B.ALAW&&i!==B.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===B.PCM&&![8,16,24,32].includes(c))throw Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(i===B.IEEE_FLOAT&&![32,64].includes(c))throw Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=Z(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=Z(r,4),t=Ka(r,n),i=K(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s;break}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=Q(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&so(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(t(this.audioInfo),this.audioInfo.format===B.MULAW)return`ulaw`;if(this.audioInfo.format===B.ALAW)return`alaw`;if(this.audioInfo.format===B.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`}if(this.audioInfo.format===B.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return`pcm-f32`;if(this.audioInfo.sampleSizeInBytes===8)return`pcm-f64`}t(!1)}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}};let Dr=2048;var Or=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(t(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return t(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 t(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...He}}async getPacketAtIndex(e,n){t(e>=0),t(this.demuxer.audioInfo);let r=e*Dr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let i=Math.min(Dr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(e instanceof Promise&&(e=await e),!e)return null}let a;if(n.metadataOnly)a=N;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);e instanceof Promise&&(e=await e),t(e),a=K(e,i)}let o=e*Dr/this.demuxer.audioInfo.sampleRate,s=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new P(a,`key`,o,s,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,n){t(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Dr,(this.demuxer.dataSize-1)/(Dr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let i=await this.getPacketAtIndex(r,n);if(i)return i;if(r===0)return null;t(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,n);for(;a;){let e=await this.getNextPacket(a,n);if(!e)break;a=e}return a}getNextPacket(e,n){t(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Dr);return this.getPacketAtIndex(r+1,n)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};
|
|
194
|
+
/*!
|
|
195
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
196
|
+
*
|
|
197
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
198
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
199
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
200
|
+
*/
|
|
201
|
+
let kr=e=>{let t=e.filePos,n=new O(K(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},Ar=1024
|
|
202
|
+
/*!
|
|
203
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
204
|
+
*
|
|
205
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
206
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
207
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
208
|
+
*/
|
|
209
|
+
;var jr=class extends M{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new _,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();t(this.firstFrameHeader),this.trackBackings=[new Mr(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Q(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let n=kr(e);if(!n){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&n.startPos+n.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=n;let r=Ue[n.samplingFrequencyIndex];t(r!==void 0);let i=Ar/r,a={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Ar,this.lastLoadedPos=n.startPos+n.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 e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=Q(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;so(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},Mr=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ar}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`und`}getCodec(){return`aac`}getInternalCodecId(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){t(this.demuxer.firstFrameHeader);let e=We[this.demuxer.firstFrameHeader.channelConfiguration];return t(e!==void 0),e}getSampleRate(){t(this.demuxer.firstFrameHeader);let e=Ue[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return t(e!==void 0),e}getDisposition(){return{...He}}async getDecoderConfig(){return t(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 n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=N;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=K(e,n.dataSize)}return new P(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=S(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=C(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};
|
|
210
|
+
/*!
|
|
211
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
212
|
+
*
|
|
213
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
214
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
215
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
216
|
+
*/
|
|
217
|
+
let Nr=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,Pr=(e,t)=>{switch(e){case 0:return t;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}},Fr=e=>{let t=0,n=new O(K(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new O(K(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},Ir=(e,n)=>{if(n===`uncommon-u16`)return J(e)+1;if(n===`uncommon-u8`)return q(e)+1;if(typeof n==`number`)return n;ie(n),t(!1)},Lr=(e,t)=>t===`uncommon-u16`?J(e):t===`uncommon-u16-10`?J(e)*10:t===`uncommon-u8`?q(e):typeof t==`number`?t:null,Rr=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t};
|
|
218
|
+
/*!
|
|
219
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
220
|
+
*
|
|
221
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
222
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
223
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
224
|
+
*/
|
|
225
|
+
var zr=class extends M{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 _,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),t(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n){this.lastSampleLoaded=!0;return}let r=Q(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);i instanceof Promise&&(i=await i),t(i),so(i,r,this.metadataTags),e=n.filePos+r.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let n=this.reader.requestSlice(e,4);if(n instanceof Promise&&(n=await n),e+=4,n===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);t(n);let r=q(n),i=Wa(n),a=(r&128)!=0;switch(r&127){case Xt.STREAMINFO:{let n=this.reader.requestSlice(e,i);if(n instanceof Promise&&(n=await n),t(n),n===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let r=K(n,34),a=new O(r),o=a.readBits(16),s=a.readBits(16),c=a.readBits(24),l=a.readBits(24),u=a.readBits(20),d=a.readBits(3)+1;a.readBits(5);let f=a.readBits(36);a.skipBits(128);let p=new Uint8Array(42);p.set(new Uint8Array([102,76,97,67]),0),p.set(new Uint8Array([128,0,0,34]),4),p.set(r,8),this.audioInfo={numberOfChannels:d,sampleRate:u,totalSamples:f,minimumBlockSize:o,maximumBlockSize:s,minimumFrameSize:c,maximumFrameSize:l,description:p},this.trackBacking=new Br(this);break}case Xt.VORBIS_COMMENT:{let n=this.reader.requestSlice(e,i);n instanceof Promise&&(n=await n),t(n),Zt(K(n,i),this.metadataTags);break}case Xt.PICTURE:{let n=this.reader.requestSlice(e,i);n instanceof Promise&&(n=await n),t(n);let r=Y(n),a=Y(n),o=c.decode(K(n,a)),s=Y(n),l=c.decode(K(n,s));n.skip(16);let u=Y(n),d=K(n,u);this.metadataTags.images??=[],this.metadataTags.images.push({data:d,mimeType:o,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,description:l});break}default:break}if(e+=i,a){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error(`Missing STREAMINFO metadata block! Corrupted FLAC file.`)})()}async readNextFlacFrame({startPos:e,isFirstPacket:n}){t(this.audioInfo);let r=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,i=this.audioInfo.minimumFrameSize||10,a=(this.audioInfo.maximumFrameSize||r)+16,o=await this.reader.requestSliceRange(e,16,a);if(!o)return null;let s=this.readFlacFrameHeader({slice:o,isFirstPacket:n});if(!s)return null;for(o.filePos=e+i;;){if(o.filePos>o.end-6)return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:o.end-e,isLastFrame:!0};if(q(o)===255){let t=o.filePos;if(q(o)!==(this.blockingBit===1?249:248)){o.filePos=t;continue}o.skip(-2);let n=o.filePos-e,r=this.readFlacFrameHeader({slice:o,isFirstPacket:!1});if(!r){o.filePos=t;continue}if(this.blockingBit===0){if(r.num-s.num!==1){o.filePos=t;continue}}else if(r.num-s.num!==s.blockSize){o.filePos=t;continue}return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:n}){let r=e.filePos,i=new O(K(e,4));if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){t(n);let e=i.readBits(1);this.blockingBit=e}else if(this.blockingBit===1){if(t(!n),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(t(!n),i.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let a=Nr(i.readBits(4));if(!a)return null;t(this.audioInfo);let o=Pr(i.readBits(4),this.audioInfo.sampleRate);if(!o||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let s=Fr(e),c=Ir(e,a),l=Lr(e,o);if(l===null||l!==this.audioInfo.sampleRate)return null;let u=e.filePos-r,d=q(e);return e.skip(-u),e.skip(-1),d===Rr(K(e,u))?{num:s,blockSize:c,sampleRate:l}:null}async advanceReader(){await this.readMetadata(),t(this.lastLoadedPos!==null),t(this.audioInfo);let e=this.lastLoadedPos,n=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!n){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:n.blockSize,byteOffset:e,byteSize:n.size};if(this.lastLoadedPos+=n.size,this.loadedSamples.push(i),n.isLastFrame){this.lastSampleLoaded=!0;return}}},Br=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return t(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 t(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...He}}async getDecoderConfig(){return t(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,n){if(t(this.demuxer.audioInfo),e<0)return null;let r=await this.demuxer.readingMutex.acquire();try{for(;;){let t=C(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(t===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[t];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,n);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(t,n)}}finally{r()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,n){let r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(n.metadataOnly)i=N;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;i=K(e,r.byteSize)}t(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,o=r.blockSize/this.demuxer.audioInfo.sampleRate;return new P(i,`key`,a,o,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}};
|
|
226
|
+
/*!
|
|
227
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
228
|
+
*
|
|
229
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
230
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
231
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
232
|
+
*/
|
|
233
|
+
let Vr=9e4,Hr=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},Ur=`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.`,Wr=new Set
|
|
234
|
+
/*!
|
|
235
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
236
|
+
*
|
|
237
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
238
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
239
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
240
|
+
*/
|
|
241
|
+
;var Gr=class extends M{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=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),t(e);let n=K(e,205);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let r=this.packetOffset,i=null,a=!1,o=!1;for(;;){let e=await this.readPacketHeader(r);if(!e)break;if(e.payloadUnitStartIndicator===0){r+=this.packetStride;continue}if(o&&!this.elementaryStreams.some(t=>t.pid===e.pid)){r+=this.packetStride;continue}let n=await this.readSection(r,!0,!o);if(!n)break;let s=!1;if(!o&&n.pid!==0&&!(n.payload[0]===0&&n.payload[1]===0&&n.payload[2]===1)){let e=new O(n.payload),t=e.readAlignedByte();e.skipBits(8*t),s=e.readBits(8)===2}if(n.pid===0&&!a){let e=new O(n.payload),t=e.readAlignedByte();e.skipBits(8*t),e.skipBits(14);let r=e.readBits(10);for(e.skipBits(40);8*(r+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let n=e.readBits(13);if(t!==0){if(i!==null)throw Error(`Only files with a single program are supported.`);i=n}}if(i===null)throw Error(`Program Association Table must link to a Program Map Table.`);a=!0}else if((n.pid===i||s)&&!o){let e=new O(n.payload),t=e.readAlignedByte();e.skipBits(8*t),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10);for(e.skipBits(8*i);8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8);t===106?a=!0:(t===122||t===204)&&(o=!0),e.skipBits(8*n)}let s=null;switch(t){case 27:case 36:s={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 e;if(t===3||t===4)e=`mp3`;else if(t===15)e=`aac`;else if(t===129)e=`ac3`;else if(t===135)e=`eac3`;else throw Error(`Unreachable.`);s={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?s={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:a&&(s={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:Wr.has(t)||(D._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Wr.add(t))}s&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:s,referencePesPackets:[]})}o=!0}else{let e=this.elementaryStreams.find(e=>e.pid===n.pid);outer:if(e&&!e.initialized){let r=qr(n,!0);if(!r)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=n,e.canBeTrustedWithKeyPackets=n.randomAccessIndicator===1,this.input._initInput){let t=(await this.input._initInput._getDemuxer()).elementaryStreams.find(t=>t.pid===n.pid&&t.info.codec===e.info.codec);if(t){e.info=t.info,e.initialized=!0;break outer}}let i=new Qr(e,r);if(e.info.type===`video`){for(;;){let n=i;if(n.suppliedPacket=null,await i.markNextPacket(),e.info.codec===`avc`){if(!i.suppliedPacket)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.`);if(e.info.avcCodecInfo=wt(i.suppliedPacket.data),!e.info.avcCodecInfo)continue;let n=e.info.avcCodecInfo.sequenceParameterSets[0];t(n);let r=Dt(n);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;a>0&&o>0&&(a>o?(e.info.squarePixelWidth=Math.round(e.info.width*a/o),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*o/a))),e.info.colorSpace={primaries:d[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:h[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}else if(e.info.codec===`hevc`){if(!i.suppliedPacket)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);if(e.info.hevcCodecInfo=Nt(i.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let n=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===A.SPS_NUT).nalUnits[0];t(n);let r=Mt(n);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:d[r.colourPrimaries],transfer:p[r.transferCharacteristics],matrix:h[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}else throw Error(`Unhandled.`)}e.info.decoderConfig={codec:Qe({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},(e.info.width!==e.info.squarePixelWidth||e.info.height!==e.info.squarePixelHeight)&&(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await i.markNextPacket(),!i.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if(e.info.codec===`aac`){let t=kr(Ha.tempFromBytes(i.suppliedPacket.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=We[t.channelConfiguration],e.info.sampleRate=Ue[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=lt(Y(Ha.tempFromBytes(i.suppliedPacket.data)),i.suppliedPacket.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=ft(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=$t(i.suppliedPacket.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=Qt[t.acmod]+t.lfeon,e.info.sampleRate=pt[t.fscod]}else if(e.info.codec===`eac3`){let t=nn(i.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=an(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=on(t),e.info.sampleRate=n}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:$e({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}if(o&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!o)throw Error(a?`No Program Map Table found in the file.`:`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.info.type===`video`?this.trackBackingEntries.push(new Yr(e)):this.trackBackingEntries.push(new Xr(e))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),Hr(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(S(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=C(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(q(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=J(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=q(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=K(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}};let Kr=(e,t)=>{if(e.payload.byteLength<3)return null;let n=new O(e.payload);if(n.readBits(24)!==1)return null;let r=n.readBits(8);if(n.skipBits(16),r===188||r===190||r===191||r===240||r===241||r===255||r===242||r===248)return null;n.skipBits(8);let i=n.readBits(2);n.skipBits(14);let a=null;if(i===2||i===3)a=0,n.skipBits(4),a+=n.readBits(3)*(1<<30),n.skipBits(1),a+=n.readBits(15)*32768,n.skipBits(1),a+=n.readBits(15);else if(t)throw Error(Ur);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:a,randomAccessIndicator:e.randomAccessIndicator}},qr=(e,n)=>{t(e.endPos!==null);let r=Kr(e,n);if(!r)return null;let i=new O(e.payload);i.skipBits(32);let a=i.readBits(16);i.skipBits(16);let o=i.readBits(8),s=i.pos+8*o;i.pos=s;let c=s/8;t(Number.isInteger(c));let l=e.payload.subarray(c,a>0?6+a:e.payload.byteLength);return{...r,data:l}};var Jr=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let n=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,i=0;for(let a of n.trackBackingEntries)if(a.getType()===r&&i++,t(a instanceof e),a.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...He,primary:!1}}getTimeResolution(){return Vr}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,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new P(n.metadataOnly?N:e.data,r,e.pts/Vr,Math.max(t/Vr,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let n=this.elementaryStream.firstSection;t(n);let r=qr(n,!0);t(r);let i=new Qr(this.elementaryStream,r),a=new $r(this,i),o=await a.readNext();if(!o)return null;let s=this.createEncodedPacket(o.packet,o.duration,e);return this.packetBuffers.set(s,a),this.packetSectionStarts.set(s,o.packet.sectionStartPos),s}async getNextPacket(e,n){let r=this.packetBuffers.get(e);if(r){let t=await r.readNext();if(!t)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(t.packet,t.duration,n);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,t.packet.sectionStartPos),i}let i=this.packetSectionStarts.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);let a=await this.elementaryStream.demuxer.readSection(i,!0);t(a);let o=qr(a,!0);t(o);let s=new Qr(this.elementaryStream,o);r=new $r(this,s);let c=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){let t=this.createEncodedPacket(e.packet,e.duration,n);return this.packetBuffers.set(t,r),this.packetSectionStarts.set(t,e.packet.sectionStartPos),t}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,n,i){let a=le(e*Vr),o=this.elementaryStream.demuxer,{reader:s,seekChunkSize:c}=o,l=this.elementaryStream.pid,u=async(e,t,n)=>{let r=e;for(;r<t;){let e=await o.readPacketHeader(r);if(!e)return null;if(e.pid===l&&e.payloadUnitStartIndicator===1){let e=await o.readSection(r,n);if(!e)return null;let t=Kr(e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=o.packetStride}return null},d=this.elementaryStream.firstSection;t(d);let f=Kr(d,!0);if(t(f),a<f.pts)return null;let p,m=this.elementaryStream.referencePesPackets,h=C(m,a,e=>e.pts),g=h===-1?null:m[h];if(g&&a-g.pts<9e4/2)p=g.sectionStartPos;else{let e=0;if(s.fileSize!==null){let t=Math.ceil(s.fileSize/c);if(t>1){let n=0,r=t-1;for(e=n;n<=r;){let t=Math.floor((n+r)/2),i=fe(t*c,o.packetStride)+f.sectionStartPos,s=await u(i,i+c,!1);if(!s){r=t-1;continue}s.pesPacketHeader.pts<=a?(e=t,n=t+1):r=t-1}}}p=fe(e*c,o.packetStride)+f.sectionStartPos}let _=(await u(p,s.fileSize??1/0,!1))?.pesPacketHeader??null;_||=f;let v=this.getReorderSize(),y=async(e,n)=>{let s=await o.readSection(e,!0);t(s);let c=qr(s,!0);t(c);let l=new Qr(this.elementaryStream,c),u=new $r(this,l);for(;!((r(u.presentationOrderPackets)?.pts??-1/0)>=a||!await u.readNextPacket()););let d=te(u.presentationOrderPackets,n);if(d===-1)return null;let f=u.presentationOrderPackets[d],p=d===0?0:f.pts-u.presentationOrderPackets[d-1].pts;for(;u.decodeOrderPackets[0]!==f;)u.decodeOrderPackets.shift();u.lastDuration=p;let m=await u.readNext();t(m);let h=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(h,u),this.packetSectionStarts.set(h,m.packet.sectionStartPos),h};if(!n||this.allPacketsAreKeyPackets()){outer:for(;;){let e=_.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,!1);if(t){let e=Kr(t,!1);if(e&&e.pts!==null){if(e.pts>a)break outer;_=e,Zr(this.elementaryStream,_);break}}}e+=o.packetStride}}outer:for(let e=0;e<v+1;e++){let e=_.sectionStartPos-o.packetStride;for(;e>=o.packetOffset;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,!1);if(t){let e=Kr(t,!1);if(e&&e.pts!==null){_=e;break}}}e-=o.packetStride}}return y(_.sectionStartPos,e=>e.pts<=a)}else{let e=p,n=null,r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let i=null,p=e<=f.sectionStartPos,m,h=null;if(p)m=f,h=d;else{let t=await u(e,s.fileSize??1/0,r);m=t?.pesPacketHeader??null,h=t?.section??null}let g=!1,_=0;outer:for(;m&&!(n!==null&&m.sectionStartPos>=n);){if(m.pts<=a){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=m.randomAccessIndicator===1;else{t(h);let n=qr(h,!0);t(n);let r=new Qr(this.elementaryStream,n);await r.markNextPacket(),e=r.suppliedPacket?.randomAccessIndicator===1}e&&(i=m)}if(m.pts>a&&(g=!0),g&&(_++,_>v))break;let e=m.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,r);if(t){let e=Kr(t,!1);if(e&&e.pts!==null){m=e,h=t,Zr(this.elementaryStream,m);break}}}e+=o.packetStride}}if(i){let e=i;if(_===0)outer:for(let t=0;t<v;t++){let t=e.sectionStartPos-o.packetStride;for(;t>=o.packetOffset;){let n=await o.readPacketHeader(t);if(!n)break outer;if(n.pid===l&&n.payloadUnitStartIndicator===1){let n=await o.readSection(t,r);if(n){let t=Kr(n,!1);if(t&&t.pts!==null){e=t;break}}}t-=o.packetStride}}let n=await y(e.sectionStartPos,e=>e.pts<=a&&e.randomAccessIndicator===1);return t(n),n}if(p)return null;n=e,e=Math.max(fe(e-f.sectionStartPos-c,o.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}},Yr=class extends Jr{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 t(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Xr=class extends Jr{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return t(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}};let Zr=(e,t)=>{let n=e.referencePesPackets,r=C(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0};var Qr=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 t(e),e}async bufferData(e){let n=this.endPos+e;for(;this.endPos<n;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let n=r(this.pesPackets).sectionEndPos;for(t(n!==null);;){let t=await this.demuxer.readPacketHeader(n);if(!t)return;if(t.pid===this.pid){let t=await this.demuxer.readSection(n,!0);if(!t)return;let r=qr(t,!1);if(r){e=r;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}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 e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)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(){t(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type===`video`){let t=e.info.codec,n=1024;if(t!==`avc`&&t!==`hevc`)throw Error(`Unhandled.`);let r=t===`avc`?1:2,a=null,o=!1,s=0;for(;;){let e=this.ensureBuffered(n);if(e instanceof Promise&&(e=await e),e===0)break;let c=this.currentPos,l=this.readBytes(e),u=l.byteLength,d=0;for(;d<u;){let e=l.indexOf(0,d);if(e===-1||e>=u)break;d=e;let n=c+d;if(d+3>=u){this.seekTo(n);break}let f=l[d+1],p=l[d+2],m=l[d+3],h=0;if(f===0&&p===0&&m===1?h=4:f===0&&p===1&&(h=3),h===0){d++;continue}let g=n;a??=g;let _=d+h,v=_+r;if(v+(t===`avc`?6:1)>u){this.seekTo(n);break}let y=l[_],b,x,S;if(t===`avc`)b=vt(y),x=b===k.NON_IDR_SLICE||b===k.SLICE_DPA||b===k.IDR,S=b===k.SEI||b===k.SPS||b===k.PPS||b===k.AUD;else{if(b=jt(y),((y&1)<<5|l[_+1]>>3)>0){d+=h;continue}x=b<=A.RASL_R||b>=A.BLA_W_LP&&b<=21,S=b>=A.VPS_NUT&&b<=37||b===A.PREFIX_SEI_NUT||b>=41&&b<=44||b>=48&&b<=55}let C=!1;if(x){let e;if(t===`avc`){let t=i(new O(l.subarray(v,v+6)));e=!o||t<=s,s=t}else e=l[v]>>7==1;e&&(o?C=!0:o=!0)}else S&&o&&(C=!0);if(C){let e=g-a;return this.seekTo(a),this.supplyPacket(e,0)}d+=h}if(e<n)break}if(a!==null&&this.endPos>a){let e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{let n=e.info.codec;for(;;){let r=this.ensureBuffered(128);r instanceof Promise&&(r=await r);let i=this.currentPos;for(;this.currentPos-i<r;){let r=this.readU8();if(n===`aac`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(9);if(n instanceof Promise&&(n=await n),n<9)return;let i=this.readBytes(9),a=kr(Ha.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return n instanceof Promise&&(n=await n),this.supplyPacket(n,Math.round(Ar*Vr/e.info.sampleRate))}else this.seekTo(t+1)}else if(n===`mp3`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(4);if(n instanceof Promise&&(n=await n),n<4)return;let i=lt(s(this.readBytes(4)).getUint32(0),null);if(i.header){this.seekTo(t);let n=this.ensureBuffered(i.header.totalSize);n instanceof Promise&&(n=await n);let r=i.header.audioSamplesInFrame*Vr/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}else this.seekTo(t+1)}else if(n===`ac3`){if(r!==11)continue;this.skip(-1);let n=this.currentPos,i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=this.readBytes(5);if(a[0]!==11||a[1]!==119){this.seekTo(n+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){this.seekTo(n+1);continue}let c=en[3*s+o];t(c!==void 0),this.seekTo(n),i=this.ensureBuffered(c),i instanceof Promise&&(i=await i);let l=Math.round(1536*Vr/e.info.sampleRate);return this.supplyPacket(i,l)}else if(n===`eac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(5);if(n instanceof Promise&&(n=await n),n<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=(((i[2]&7)<<8|i[3])+1)*2,o=tn[i[4]>>6==3?3:i[4]>>4&3];this.seekTo(t),n=this.ensureBuffered(a),n instanceof Promise&&(n=await n);let s=o*256,c=Math.round(s*Vr/e.info.sampleRate);return this.supplyPacket(n,c)}else throw Error(`Unhandled.`)}if(r<128)break}}}supplyPacket(e,n){let r=this.getCurrentPesPacket(),i;if(this.lastSuppliedPesPacket===r)t(this.nextPts!==null),i=this.nextPts;else{if(r.pts===null)throw Error(Ur);i=r.pts,Zr(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=i+n;let a=r.sectionStartPos,o=a+(this.currentPos-this.currentPesPacketPos),s=this.readBytes(e),c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)c=1;else if(this.elementaryStream.info.decoderConfig){let e=Yt(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,s)===`key`;c=Number(e)}}this.suppliedPacket={pts:i,data:s,sequenceNumber:o,sectionStartPos:a,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},$r=class{constructor(e,n){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=n,this.reorderSize=e.getReorderSize(),t(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],n=this.presentationOrderPackets.indexOf(e);t(n!==-1);let r;for(n===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[n+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return 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(t(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 e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};
|
|
242
|
+
/*!
|
|
243
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
244
|
+
*
|
|
245
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
246
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
247
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
248
|
+
*/
|
|
249
|
+
let ei=`application/vnd.apple.mpegurl`,ti=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`);var ni=class{constructor(e){this._attributes={};let t=``,n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];o===`"`?i=!i:o===`=`&&!r&&!i?r=!0:o===`,`&&!i?(t&&(this._attributes[t.trim().toLowerCase()]=n),t=``,n=``,r=!1):r?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}},ri=class{constructor(e,t,n){
|
|
250
|
+
/*!
|
|
251
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
252
|
+
*
|
|
253
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
254
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
255
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
256
|
+
*/
|
|
257
|
+
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=n}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 n=e-t.timestamp;return t.unixEpochTimestamp+n}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type===`video`){let n=Ne(e,e=>e.getType()===`video`)+1;e.push(new ai(this,t,n))}else if(t.type===`audio`){let n=Ne(e,e=>e.getType()===`audio`)+1;e.push(new oi(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of t)if(n.type===`video`){let t=Ne(e,e=>e.getType()===`video`)+1;e.push(new ai(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=Ne(e,e=>e.getType()===`audio`)+1;e.push(new oi(this,{id:e.length+1,type:`audio`},t))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,r;if(this.firstSegmentFirstTimestamps.has(n))r=this.firstSegmentFirstTimestamps.get(n);else{let e=this.getInputForSegment(n);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(n,r)}if(n===e)return n.timestamp-r;let i=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,o=i-r-a;return Math.abs(o)<=Math.min(.25,a)?n.timestamp-r:e.timestamp-i}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},ii=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error(`Missing first segment, can't retrieve track.`);let e=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!e)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=e})()}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(),t(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,n,r){t(e.sequenceNumber>=0),t(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(n,r.input),a=n.timestamp-this.segmentedInput.firstSegment.timestamp,o=e.clone({timestamp:de(e.timestamp+i,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(o,{segment:n,track:r,sourcePacket:e}),o}async getFirstPacket(e){await this.hydrate(),t(this.segmentedInput.firstSegment),t(this.firstInputTrack);let n=await this.firstInputTrack._backing.getFirstPacket(e);return n?this.createAdjustedPacket(n,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,n){let r=this.packetInfos.get(e);if(!r)throw Error(`Packet was not created from this track.`);let i=n?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(i)return this.createAdjustedPacket(i,r.segment,r.track);let a=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!e)return null;let n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){a=e;continue}let i=await n._backing.getFirstPacket(t);return i?this.createAdjustedPacket(i,e,n):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){let i=this.segmentedInput.getInputForSegment(r),a=(await i.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!a){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}let o=e-await this.segmentedInput.getMediaOffset(r,i),s=n?await a._backing.getKeyPacket(o,t):await a._backing.getPacket(o,t);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(s,r,a)}return null}},ai=class extends ii{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())}},oi=class extends ii{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())}}
|
|
258
|
+
/*!
|
|
259
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
260
|
+
*
|
|
261
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
262
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
263
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
264
|
+
*/
|
|
265
|
+
;e(((e,t)=>{t.exports={}}))(),Ae();let si=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var V=class extends Re{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 W;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,si),e=this._getFileSize(),t(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new W;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new _i(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new ci(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},ci=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;t(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},li=class extends V{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof V||e instanceof ci))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof V?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(n):n(t)}};let ui=(e,t)=>e.path===t.path;var di=class extends li{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,n,r,i){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),n=e=>{let t=e instanceof V?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(n):(n(e),t(this._root))}if(this._rootRequest)return this._rootRequest.then(t=>t.source._read(e,n,r,i))}return this._root.source._read(e,n,r,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},fi=class extends V{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError(`blob must be a Blob.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!je(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(t.useStreamReader!==void 0&&typeof t.useStreamReader!=`boolean`)throw TypeError(`options.useStreamReader, when provided, must be a boolean.`);super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new gi({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:hi.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,r){return this._orchestrator.read(e,t,n,r)}async _runWorker(e){t(e.strictTarget);let n=this._readers.get(e);for(n===void 0&&(n=(`stream`in this._blob)&&!ye()&&this._options.useStreamReader!==!1?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,n));e.currentPos<e.targetPos&&!e.aborted;)if(n){let{done:t,value:r}=await n.read();if(t)throw this._orchestrator.onWorkerFinished(e),Error(`Blob reader stopped unexpectedly before all requested data was read.`);if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await n?.cancel()}_dispose(){this._orchestrator.dispose()}};let pi=.5*2**20;var mi=class extends V{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError(`stream must be a ReadableStream.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!je(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=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 n=C(this._cache,e,e=>e.start),r=n===-1?null:this._cache[n];if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let i=e,a=new Uint8Array(t-e);if(n!==-1)for(let r=n;r<this._cache.length;r++){let n=this._cache[r];if(n.start>=t)break;let o=Math.max(e,n.start);o>i&&this._throwDueToCacheMiss();let s=Math.min(t,n.end);o<s&&(a.set(n.bytes.subarray(o-n.start,s-n.start),o-e),i=s)}if(i===t)return{bytes:a,view:s(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:c,reject:l}=w();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(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else throw e})),o}_throwDueToCacheMiss(){throw Error(`Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`)}async _pull(){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 e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(n,r);for(let e=0;e<this._pendingSlices.length;e++){let i=this._pendingSlices[e],a=Math.max(n,i.start),o=Math.min(r,i.end);a<o&&(i.bytes.set(t.subarray(a-n,o-n),a-i.start),o===i.end&&(i.resolve({bytes:i.bytes,view:s(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:s(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.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()}};let hi={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{let n=2**16;return e=Math.floor((e-n)/n)*n,t=Math.ceil((t+n)/n)*n,{start:e,end:t}},network:(e,t,n)=>{let r=2**16;e=Math.max(0,Math.floor((e-r)/r)*r);for(let r of n){let n=8*2**20,i=Math.max((r.startPos+r.targetPos)/2,r.targetPos-n);if(De(e,t,i,r.targetPos)){let e=r.targetPos-r.startPos,i=Math.ceil((e+1)/n)*n,a=2**Math.ceil(Math.log2(e+1)),o=Math.min(a,i);t=Math.max(t,r.startPos+o)}}return t=Math.max(t,e+pi),{start:e,end:t}}};var gi=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,n,r,i){t(!this.disposed);let a=this.options.prefetchProfile(e,n,this.workers),o=Math.max(a.start,r),c=Math.min(a.end,this.fileSize??1/0,i);t(o<=e&&n<=c);let l=null,u=C(this.cache,e,e=>e.start),d=u===-1?null:this.cache[u];d&&d.start<=e&&n<=d.end&&(d.age=this.nextAge++,l={bytes:d.bytes,view:d.view,offset:d.start});let f=C(this.cache,o,e=>e.start),p=l?null:new Uint8Array(n-e),m=0,h=o,g=[];if(f!==-1){for(let r=f;r<this.cache.length;r++){let i=this.cache[r];if(i.start>=c)break;if(i.end<=o)continue;let a=Math.max(o,i.start),s=Math.min(c,i.end);if(t(a<=s),h<a&&g.push({start:h,end:a}),h=s,p){let t=Math.max(e,i.start),r=Math.min(n,i.end);if(t<r){let n=t-e;p.set(i.bytes.subarray(t-i.start,r-i.start),n),n===m&&(m=r-e)}}i.age=this.nextAge++}h<c&&g.push({start:h,end:c})}else g.push({start:o,end:c});if(p&&m>=p.length&&(l={bytes:p,view:s(p),offset:e}),g.length===0)return t(l),l;let{promise:_,resolve:v,reject:y}=w(),b=[];for(let t of g){let r=Math.max(e,t.start),i=Math.min(n,t.end);r===t.start&&i===t.end?b.push(t):r<i&&b.push({start:r,end:i})}let x=p&&{start:e,bytes:p,holes:b,resolve:v,reject:y};outer:for(let e of g){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,x?[x]:[])){this.checkQueuedReadsAgainstWorker(t);continue outer}let t=e.end<c||this.fileSize!==null,n=this.createWorker(e.start,e.end,t);if(n)x&&(n.pendingSlices=[x]),this.runWorker(n);else{let n=C(this.queuedReads,e.start,e=>e.hole.start),r=n===-1?null:this.queuedReads[n];for(r&&e.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,e.end),r.strictTarget&&=t,x&&r.pendingSlices.push(x)):(n++,r={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:x?[x]:[],age:this.nextAge++},this.queuedReads.splice(n,0,r));n+1<this.queuedReads.length;){let e=this.queuedReads[n+1];if(e.hole.start>r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&=e.strictTarget,r.age=Math.min(r.age,e.age),this.queuedReads.splice(n+1,1)}}}return l?_.catch(e=>{if(!this.disposed)throw e}):(t(p),l=_.then(t=>t&&{bytes:t,view:s(t),offset:e})),l}checkHoleAgainstWorker(e,t,n){if(De(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<n.length;t++){let r=n[t];e.pendingSlices.includes(r)||e.pendingSlices.push(r)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){let r=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,r.hole,r.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,n,r){if(this.workers.length>=this.options.maxWorkerCount){let e=null,n=null;for(let t=0;t<this.workers.length;t++){let r=this.workers[t];!r.running&&r.pendingSlices.length===0&&(!e||r.age<e.age)&&(n=t,e=r)}if(e)t(n!==null),t(e.pendingSlices.length===0),this.workers.splice(n,1);else return null}let i={startPos:e,currentPos:e,targetPos:n,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){t(!e.running),t(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(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let t=1;t<this.queuedReads.length;t++)this.queuedReads[t].age<this.queuedReads[e].age&&(e=t);let t=this.queuedReads[e],n=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);if(!n)return;this.queuedReads.splice(e,1),n.pendingSlices=t.pendingSlices,this.runWorker(n)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){let r=this.workers[n];if(r!==e){for(let e of r.pendingSlices)t.add(e);r.aborted=!0,r.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let e=0;e<this.queuedReads.length;e++){let n=this.queuedReads[e];for(let e of n.pendingSlices)t.add(e)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,n){t(!e.aborted);let r=e.currentPos,i=r+n.length;this.insertIntoCache({start:r,end:i,bytes:n,view:s(n),age:this.nextAge++}),e.currentPos+=n.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let t=0;t<e.pendingSlices.length;t++){let a=e.pendingSlices[t],o=Math.max(r,a.start),s=Math.min(i,a.start+a.bytes.length);o<s&&a.bytes.set(n.subarray(o-r,s-r),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];r<=t.start&&i>t.start&&(t.start=i),t.end<=t.start&&(a.holes.splice(e,1),e--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(t,1),t--)}for(let t=0;t<this.workers.length;t++){let n=this.workers[t];e===n||n.running||De(r,i,n.currentPos,n.targetPos)&&(this.workers.splice(t,1),t--)}}supplyFileSize(e){t(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){let r=t.pendingSlices[n];for(let i of r.holes)if(i.end>e){r.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){let n=this.queuedReads[t];if(n.hole.start>=e){for(let e of n.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let t=0;t<n.pendingSlices.length;t++){let r=n.pendingSlices[t];r.start>=e&&(r.resolve(null),n.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let n=this.workers.indexOf(e);t(n!==-1),e.running=!1,this.workers.splice(n,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let t of e.pendingSlices)t.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=C(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=s(r),n.end=e.end,t--,e=n}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 n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=s(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}},_i=class extends V{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:ce(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r),a=e=>e?(e.offset-=this._offset,e):null;return i instanceof Promise?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},vi=function(e,t,n){
|
|
266
|
+
/*!
|
|
267
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
268
|
+
*
|
|
269
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
270
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
271
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
272
|
+
*/
|
|
273
|
+
if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},yi=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});let bi=/^0[xX][0-9a-fA-F]+$/,xi=/^data:.*;base64,/i;var Si=class extends ri{constructor(e,t,n,r){super(e.input,t,n),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=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Le(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 n={stack:[],error:void 0,hasError:!1};try{let r=vi(n,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=await new Va(r.source).requestEntireFile();t(i),e=to(i,i.length,{ignore:ti}),r.source instanceof li&&(this.rootPath=r.source.rootPath)}catch(e){n.error=e,n.hasError=!0}finally{yi(n)}}let n=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,i=!1,a=0,o=null,c=null,l=null,u=0,d=null,f=null,p=null,m=null,h=null,g=null,_=!1,v=r(this.segments)??null,y=e=>{let t=e.indexOf(`@`),n=Number(t===-1?e:e.slice(0,t));if(!Number.isInteger(n)||n<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(t!==-1&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:n,offset:r}},b=e=>{u=e,v&&(t(v.sequenceNumber!==null),v.sequenceNumber<e&&(a=v.timestamp+v.duration,d=v.firstSegment,f=v.initSegment,h=v.lastProgramDateTimeSeconds,o=v.unixEpochTimestamp===null?null:v.unixEpochTimestamp+v.duration,v=null))};for(let t=0;t<e.length;t++){let x=e[t];if(!i){if(x!==`#EXTM3U`)throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);i=!0;continue}if(!x.startsWith(`#`)){if(!v){if(c===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=l;if(e&&e.method===`AES-128`&&!e.iv){let t=new Uint8Array(16),n=s(t);n.setUint32(8,Math.floor(u/2**32)),n.setUint32(12,u),e={...e,iv:t}}let t={path:Me(this.rootPath,x),offset:m?.offset??0,length:m?.length??null},n={timestamp:a,unixEpochTimestamp:o,firstSegment:d,sequenceNumber:u,location:t,duration:c,encryption:e,initSegment:f,lastProgramDateTimeSeconds:h};d??=n,a+=c,o!==null&&(o+=c),this.segments.push(n)}c=null,m===null?p=null:m=null,b(u+1)}if(x.startsWith(`#EXTINF:`)){if(v){_=!0;continue}_||=(h===null&&u>0&&g!==null&&(a=u*g),!0);let e=x.slice(8),t=e.indexOf(`,`),n=t===-1?e:e.slice(0,t),r=Number(n);if(!Number.isFinite(r)||r<0)throw Error(`Invalid #EXTINF tag duration '${n}'.`);c=r}else if(x.startsWith(`#EXT-X-MAP:`)){let e=new ni(x.slice(11)),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),r=null;if(n!==null&&(r=y(n)),r&&r.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!v){let e={path:Me(this.rootPath,t),offset:r?.offset??0,length:r?.length??null};if(l?.method===`AES-128`&&!l.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);f={timestamp:a,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:l,initSegment:null,lastProgramDateTimeSeconds:h}}c=null,m===null?p=null:m=null}else if(x.startsWith(`#EXT-X-KEY:`)){let e=new ni(x.slice(11)),t=e.get(`method`);if(t===`NONE`)l=null;else if(t===`AES-128`){let t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-KEY: AES-128 requires a URI attribute.`);let n=null,r=e.get(`iv`);if(r){if(!bi.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),n=new Uint8Array(16);for(let t=0;t<16;t++){let r=-32+t;n[t]=parseInt(e.slice(r,r+2),16)}}let i=e.get(`keyformat`)??`identity`;if(i!==`identity`)throw Error(`For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.`);l={method:`AES-128`,keyUri:Me(this.rootPath,t),iv:n,keyFormat:i}}else if(t===`SAMPLE-AES`||t===`SAMPLE-AES-CTR`){let n=e.get(`uri`);if(!n)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if((e.get(`keyformat`)??`identity`)===`identity`)throw 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 r=null;if(xi.test(n)){let e=n.indexOf(`,`),t=Oe(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=s(t).getUint32(0);r=cn(t.subarray(8,Math.min(e,t.length)))}}l={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(x.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)){let e=x.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);b(t)}else if(x.startsWith(`#EXT-X-BYTERANGE:`)){let e=y(x.slice(17));if(e.offset===null){if(p===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=p}m=e,p=e.offset+e.length}else if(x.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(v)continue;let e=x.slice(25),t=Date.parse(e);if(!Number.isFinite(t))continue;let i=t/1e3;if(h===i)continue;if(h===null&&this.segments.length>0){let e=r(this.segments),t=i-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+t,n&&(e.timestamp=e.unixEpochTimestamp)}h=i,o=i,n&&(a=i)}else if(x===`#EXT-X-DISCONTINUITY`)d=null;else if(x.startsWith(`#EXT-X-TARGETDURATION:`)){let e=x.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,g=t}else if(x===`#EXT-X-ENDLIST`){this.streamHasEnded=!0;break}else x.startsWith(`#EXT-X-PLAYLIST-TYPE:`)&&x.slice(21).toLowerCase()===`vod`&&(this.streamHasEnded=!0)}if(!i)throw 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 n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let r=C(this.segments,e,e=>e.timestamp);if(r===-1)return null;if(r<this.segments.length-1||this.streamHasEnded||n)return this.segments[r];let i=this.segments[r];if(e<i.timestamp+i.duration)return i;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,n){let r=this.segments.indexOf(e);t(r!==-1);let i=r+1,a=!!n.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),n.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){let n=this.segments.indexOf(e);return t(n!==-1),this.segments[n-1]??null}getInputForSegment(e){let n=e,r=this.inputCache.find(e=>e.segment===n);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(n.initSegment||n.firstSegment)&&(i=this.getInputForSegment(n.initSegment??n.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!n.encryption||!(n.encryption.method===`SAMPLE-AES`||n.encryption.method===`SAMPLE-AES-CTR`)||!n.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes,{psshBox:r}=n.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!t.some(e=>ln(e,r))&&(t=[...t,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:t})})}},o=new za({source:new di(n.location.path,async e=>{t(e.isRoot);let r={...e,isRoot:!1},i,a=n.location.offset>0||n.location.length!==null;if(!n.encryption||n.encryption.method===`SAMPLE-AES`||n.encryption.method===`SAMPLE-AES-CTR`){if(i=await this.input._getSourceCached(r),a){let e=i.source.slice(n.location.offset,n.location.length??void 0).ref();i.free(),i=e}}else if(n.encryption.method===`AES-128`){let e=n.encryption;t(e.iv);let o=await this.input._getSourceCached(r);if(a){let e=o.source.slice(n.location.offset,n.location.length??void 0).ref();o.free(),o=e}i=new mi(wn(new Va(o.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new Va(vi(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!n)throw Error(`Invalid AES-128 key; expected at least 16 bytes of data.`);return{key:K(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{yi(t)}},()=>{o.free()})).ref()}else t(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof Vi)),initInput:i??void 0,formatOptions:a});if(o._onFormatDetermined=e=>{if((n.encryption?.method===`SAMPLE-AES`||n.encryption?.method===`SAMPLE-AES-CTR`)&&!e._isIsobmff)throw Error(`The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.`)},this.inputCache.push({segment:n,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=Pe(this.inputCache,e=>e.age);t(e!==-1),this.inputCache.splice(e,1)}return o}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},Ci=class extends M{constructor(e){
|
|
274
|
+
/*!
|
|
275
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
276
|
+
*
|
|
277
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
278
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
279
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
280
|
+
*/
|
|
281
|
+
super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{t(this.input._rootSource instanceof li);let e=await this.input._reader.requestEntireFile();t(e);let n=to(e,e.length,{ignore:ti}),{rootPath:r}=this.input._rootSource,i=[],a=[];for(let e=1;e<n.length;e++){let t=n[e];if(t.startsWith(`#EXT-X-STREAM-INF:`)){let a=e,o=n[++e];if(o===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);let s=Me(r,o),c=new ni(t.slice(18));if(c.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);i.push({fullPath:s,attributes:c,lineNumber:a,hasOnlyKeyPackets:!1})}else if(t.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let n=new ni(t.slice(26)),a=n.get(`uri`);if(a===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(n.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);let o=Me(r,a);i.push({fullPath:o,attributes:n,lineNumber:e,hasOnlyKeyPackets:!0})}else if(t.startsWith(`#EXT-X-MEDIA:`)){let n=new ni(t.slice(13));if(n.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(n.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let i=null,o=n.get(`uri`);o!==null&&(i=Me(r,o)),a.push({fullPath:i,attributes:n,lineNumber:e})}else if(t!==`#EXT-X-I-FRAMES-ONLY`&&t.startsWith(`#EXTINF:`)){let e=new Si(this,r,null,n);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}let o=[...new Set(a.filter(e=>e.attributes.get(`type`).toLowerCase()===`video`).map(e=>e.attributes.get(`group-id`)))],s=[...new Set(a.filter(e=>e.attributes.get(`type`).toLowerCase()===`audio`).map(e=>e.attributes.get(`group-id`)))],c=await Promise.all(i.map(async(e,n)=>{let i=[],c=e.attributes.get(`codecs`),l;if(c)l=c.split(`,`).map(e=>e.trim());else{let t=await this.getSegmentedInputForPath(e.fullPath).getTrackBackings(),n=await Promise.all(t.map(async e=>({track:e,codec:await e.getCodec()})));l=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let u=e.attributes.get(`video`),d=e.attributes.get(`audio`),f=l.some(e=>Ke.includes(rt(e))),p=l.some(e=>Je.includes(rt(e)));if(u!==null&&!f){if(!o.includes(u))throw Error(`Invalid M3U8 file; variant stream references video group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let e=a.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===u&&n.toLowerCase()===`video`});outer:if(e){let n=e.attributes.get(`uri`);if(n===null)break outer;let i=Me(r,n),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`video`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);t(o!==null),l.push(o)}}if(d!==null&&!p){if(!s.includes(d))throw Error(`Invalid M3U8 file; variant stream references audio group "${d}" which is not defined in any #EXT-X-MEDIA tags.`);let e=a.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===d&&n.toLowerCase()===`audio`});outer:if(e){let n=e.attributes.get(`uri`);if(n===null)break outer;let i=Me(r,n),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`audio`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);t(o!==null),l.push(o)}}l=[...new Set(l)];let m=null,h=null,g=e.attributes.getAsNumber(`bandwidth`);t(g!==null);let _=e.attributes.getAsNumber(`average-bandwidth`),v=e.attributes.get(`name`);for(let t of l){let r=rt(t);if(r!==null){if(Ke.includes(r)){if(m!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);m=t;let r=e.attributes.get(`video`);if(r===null){let t=e.attributes.get(`resolution`),r=null,a=null;if(t){let e=t.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),a=Number(e[2]))}i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(n),peakBitrate:g,averageBitrate:_,name:v,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:r,height:a}})}else{if(!o.includes(r))throw Error(`Invalid M3U8 file; variant stream references video group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(let t of a){let a=t.attributes.get(`group-id`),o=t.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`video`)continue;let s=t.attributes.get(`resolution`)??e.attributes.get(`resolution`),c=null,l=null;if(s){let e=s.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}i.push({id:-1,demuxer:this,backingTrack:null,default:Di(t.attributes),autoselect:Di(t.attributes)||Oi(t.attributes),languageCode:ki(t.attributes.get(`language`)),lineNumber:t.lineNumber,fullPath:t.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(n),peakBitrate:null,averageBitrate:null,name:t.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}}else if(Je.includes(r)){if(h!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);h=t;let r=e.attributes.get(`audio`);if(r===null){let t=e.attributes.get(`channels`),r=t===null?null:Number(t.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:h,pairingMask:1n<<BigInt(n),peakBitrate:g,averageBitrate:_,name:v,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:r!==null&&Number.isInteger(r)&&r>0?r:null}})}else{if(!s.includes(r))throw Error(`Invalid M3U8 file; variant stream references audio group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(let t of a){let a=t.attributes.get(`group-id`),o=t.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`audio`)continue;let s=t.attributes.get(`channels`)??e.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:Di(t.attributes),autoselect:Di(t.attributes)||Oi(t.attributes),languageCode:ki(t.attributes.get(`language`)),lineNumber:t.lineNumber,fullPath:t.fullPath??e.fullPath,fullCodecString:h,pairingMask:1n<<BigInt(n),peakBitrate:null,averageBitrate:null,name:t.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}}return i})),l=[],u=e=>{let t=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),e.peakBitrate!==null&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),e.averageBitrate!==null&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===`und`&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(let e of c)for(let t of e)u(t);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of l)e.info.type===`video`?this.trackBackings.push(new Ti(e)):this.trackBackings.push(new Ei(e));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),t(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new Si(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ei}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},wi=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),n=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(r.length===1)n=r[0];else if(this instanceof Ti){for(let e of r)if(await e.getCodec()===this.getCodec()){n=e;break}}else{t(this instanceof Ei);for(let e of r)if(await e.getCodec()===this.getCodec()){n=e;break}}if(!n)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=n})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...He,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(){t(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,n=0;for(let t of this.internalTrack.demuxer.internalTracks)if(t.info.type===e&&n++,t===this.internalTrack)break;return n}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)}},Ti=class extends wi{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return rt(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()}},Ei=class extends wi{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return rt(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels===null?this.delegate(()=>this.backingAudioTrack.getNumberOfChannels()):this.internalTrack.info.numberOfChannels}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}};let Di=e=>{let t=e.get(`default`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Oi=e=>{let t=e.get(`autoselect`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},ki=e=>e===null?`und`:e.split(`-`)[0]||`und`;
|
|
282
|
+
/*!
|
|
283
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
284
|
+
*
|
|
285
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
286
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
287
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
288
|
+
*/
|
|
289
|
+
var H=class{constructor(){this._isIsobmff=!1}},Ai=class extends H{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 n=Z(t,4);return n!==`ftyp`&&n!==`styp`?null:Z(t,4)}_createDemuxer(e){return new Tn(e)}},ji=class extends Ai{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Z(n,4);return r===`moof`||r===`sidx`}get name(){return`MP4`}get mimeType(){return`video/mp4`}},Mi=class extends Ai{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Ni=class extends H{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Gn(n);if(r===null||r<1||r>8||R(n,r)!==L.EBML)return!1;let i=Yn(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=Xn(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case L.EBMLVersion:if(R(a,r)!==1)return!1;break;case L.EBMLReadVersion:if(R(a,r)!==1)return!1;break;case L.DocType:if(Zn(a,r)!==t)return!1;break;case L.DocTypeVersion:if(R(a,r)>4)return!1;break}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new lr(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},Pi=class extends Ni{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},Fi=class extends H{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Q(n);if(!r)break;t=n.filePos+r.size}let n=await pr(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=ct(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=Y(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await pr(e._reader,t,t+4);if(!s)return!1;let c=s.header;return!(r.channel!==c.channel||r.sampleRate!==c.sampleRate)}_createDemuxer(e){return new mr(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},Ii=class extends H{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=Z(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),Z(t,4)===`WAVE`)}_createDemuxer(e){return new Er(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},Li=class extends H{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?Z(t,4)===`OggS`:!1}_createDemuxer(e){return new Sr(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},Ri=class extends H{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Q(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?Z(n,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new zr(e)}},zi=class extends H{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Q(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=kr(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=kr(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new jr(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},Bi=class extends H{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=K(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71||n[4]===71&&n[196]===71}_createDemuxer(e){return new Gr(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Vi=class extends H{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||Z(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof li))throw 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 Ci(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return ei}};let Hi=[new Vi,new ji,new Mi,new Ni,new Pi,new Ii,new Li,new Ri,new Fi,new zi,new Bi],Ui=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(e.hls!==void 0){if(!e.hls||typeof e.hls!=`object`)throw TypeError(`${t}.hls, when provided, must be an object.`);if(e.hls.offsetTimestampsByDateTime!==void 0&&typeof e.hls.offsetTimestampsByDateTime!=`boolean`)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};
|
|
290
|
+
/*!
|
|
291
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
292
|
+
*
|
|
293
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
294
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
295
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
296
|
+
*/
|
|
297
|
+
var Wi=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Gi=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});Ae();let Ki=-1/0,qi=-1/0,Ji=null;typeof FinalizationRegistry<`u`&&(Ji=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-Ki>=1e3&&(D._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.`),Ki=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-qi>=1e3&&(D._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.`),qi=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var Yi=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}};let Xi=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],Zi=new Set(Xi);var Qi=class e{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(ge*this.timestamp)}get microsecondDuration(){return Math.trunc(ge*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!Zi.has(n.format))throw TypeError(`init.format must be one of: `+Xi.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&Ie(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0;let e=n.layout??ca(n.format,n.codedWidth,n.codedHeight),r=n.colorSpace??null;r===null&&(r=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth),this._data=n._doNotCopy?o(t):o(t).slice(),this._layout=e,this.colorSpace=new ra(r)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&Ie(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6,this.colorSpace=new ra(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*ge),duration:Math.trunc((n.duration??0)*ge)||void 0}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=new OffscreenCanvas(r,i),o=a.getContext(`2d`,{alpha:xe(),willReadFrequently:!0});if(!o)throw Error(`OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.`);o.drawImage(t,0,0),this._data=a,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:r,height:i},this.squarePixelWidth=r,this.squarePixelHeight=i,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new ra({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof Yi){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!Xi.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=t.getColorSpace()}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=Fe({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ji?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return t(this._data!==null),this._data instanceof Yi?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ia(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(t(this._layout),new e(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 e(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||=(Ji?.unregister(this),this._data instanceof Yi?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ia(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(sa(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return ia(this._data)?this._data.allocationSize(e):ua(this,e).allocationSize}async copyTo(n,r={}){if(!g(n))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(sa(r),this._closed)throw Error(`VideoSample is closed.`);if((r.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(t(this._data!==null),ia(this._data))return this._data.copyTo(n,r);if(r.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(r.format))if(this._data instanceof Yi){let t={stack:[],error:void 0,hasError:!1};try{let i=Wi(t,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},r.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(n,r)}catch(e){t.error=e,t.hasError=!0}finally{Gi(t)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame(),t=await e.copyTo(n,r);return e.close(),t}let i=ua(this,r);t(this.format);let a=o(n);if(a.byteLength<i.allocationSize)throw TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);let s=la(this.format),c;if(this._data instanceof Yi){let e=this._data.getDataPlanes();if(e instanceof Promise&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);c=e}else if(this._data instanceof Uint8Array)t(this._layout),t(this._layout.length===s.length),c=this._layout.map((e,t)=>{let n=Math.ceil(this.codedHeight/s[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);t(e),c=[{data:o(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}let l=[],u=s.length;for(let e=0;e<u;e++){let t=i.computedLayouts[e],n=c[e].stride,r=c[e].data,o=t.sourceTop*n;o+=t.sourceLeftBytes;let s=t.destinationOffset,u=t.sourceWidthBytes,d={offset:s,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(o+u>r.byteLength)throw Error(`Source buffer OOB read.`);if(s+u>a.byteLength)throw Error(`Destination buffer OOB write.`);let e=r.subarray(o,o+u);a.set(e,s),o+=n,s+=t.destinationStride}l.push(d)}if(r.format!==void 0){let e=this.format.startsWith(`RGB`)!==r.format.startsWith(`RGB`),t=this.format.includes(`X`)&&r.format.includes(`A`);if(e||t)for(let n=0;n<i.allocationSize;n+=4){if(e){let e=a[n];a[n]=a[n+2],a[n+2]=e}t&&(a[n+3]=255)}}return l}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(t(this._data!==null),this._data instanceof Yi){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(e instanceof Promise)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else if(ia(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});else if(this._data instanceof Uint8Array)return t(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight});else return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&oa(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&=aa(s,a,o);let c,l,u,d,{sx:f,sy:p,sWidth:m,sHeight:h}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)c=0,l=0,u=n,d=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],s=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);u=e*s,d=i*s,c=(n-u)/2,l=(r-d)/2}e.save();let g=i%180==0?1:u/d;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/g,g),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),f,p,m,h,c,l,u,d),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(t(this._data!==null),this._data instanceof Yi||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&oa(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let r=n(this.rotation+(t.rotate??0)),[i,a]=r%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=t.crop;o&&=aa(o,i,a);let s=o?o.width:i,c=o?o.height:a,l=s/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=s,d=c),u=ue(u,t.roundDimensionsTo??1),d=ue(d,t.roundDimensionsTo??1);let f={width:u,height:d,fit:t.fit??`fill`,rotation:r,crop:o??{left:0,top:0,width:i,height:a},alpha:t.alpha??`keep`};for(let e of $i){let t=e(this,f);if(t instanceof Promise&&(t=await t),t!==null)return t}let p=null,m=!1;for(let e of ta)if(e.canvas.width===f.width&&e.canvas.height===f.height){p=e.canvas,e.age=na++;break}if(p===null){if(typeof OffscreenCanvas<`u`)p=new OffscreenCanvas(f.width,f.height);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);p=document.createElement(`canvas`),p.width=f.width,p.height=f.height}m=!0,ta.length>=ea&&ta.splice(Pe(ta,e=>e.age),1),ta.push({canvas:p,age:na++})}let h=p.getContext(`2d`,{alpha:!0});if(!h)throw Error(`The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.`);return f.alpha===`discard`?(h.fillStyle=`black`,h.fillRect(0,0,f.width,f.height)):m||h.clearRect(0,0,f.width,f.height),this.drawWithFit(h,{fit:f.fit,rotation:f.rotation,crop:f.crop}),new e(p,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}setEncodeOptions(e){if(!e||typeof e!=`object`)throw TypeError(`newEncodeOptions must be an object.`);this.encodeOptions=e}[Symbol.dispose](){this.close()}};let $i=[],ea=3,ta=[],na=0;var ra=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(u);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(f);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(m);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw 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}}};let ia=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,aa=(e,n,r)=>{let i=Math.min(e.left,n),a=Math.min(e.top,r),o=Math.min(e.width,n-i),s=Math.min(e.height,r-a);return t(o>=0),t(s>=0),{left:i,top:a,width:o,height:s}},oa=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},sa=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},ca=(e,t,n)=>{let r=la(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},la=e=>{let n=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return n(1,1,2,2,!1);case`I420P10`:case`I420P12`:return n(2,2,2,2,!1);case`I420A`:return n(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return n(2,2,2,2,!0);case`I422`:return n(1,1,2,1,!1);case`I422P10`:case`I422P12`:return n(2,2,2,1,!1);case`I422A`:return n(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return n(2,2,2,1,!0);case`I444`:return n(1,1,1,1,!1);case`I444P10`:case`I444P12`:return n(2,2,1,1,!1);case`I444A`:return n(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return n(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:ie(e),t(!1)}},ua=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=da(n,r,e.codedWidth,e.codedHeight,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return pa(i,o,a)},da=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(t.width===0||t.height===0)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!fa(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},fa=(e,t)=>{if(e===null)return!0;let n=la(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},pa=(e,t,n)=>{let r=la(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},ma=[],ha=[],ga=e=>{
|
|
298
|
+
/*!
|
|
299
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
300
|
+
*
|
|
301
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
302
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
303
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
304
|
+
*/
|
|
305
|
+
/*!
|
|
306
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
307
|
+
*
|
|
308
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
309
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
310
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
311
|
+
*/
|
|
312
|
+
if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},_a=e=>{if(!je(e))throw TypeError(`timestamp must be a number.`)},va=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t;var ya=class{constructor(e){if(!(e instanceof Aa))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(ga(e),this._track.input._disposed)throw new W;return va(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){ga(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(_a(e),ga(t),this._track.input._disposed)throw new W;return va(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof P))throw TypeError(`packet must be an EncodedPacket.`);if(ga(t),this._track.input._disposed)throw new W;return va(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,n={}){if(_a(e),ga(n),this._track.input._disposed)throw new W;if(!n.verifyKeyPackets)return this._track._backing.getKeyPacket(e,n);let r=await this._track._backing.getKeyPacket(e,n);return r&&(t(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),n):r)}async getNextKeyPacket(e,n={}){if(!(e instanceof P))throw TypeError(`packet must be an EncodedPacket.`);if(ga(n),this._track.input._disposed)throw new W;if(!n.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,n);let r=await this._track._backing.getNextKeyPacket(e,n);return r&&(t(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getNextKeyPacket(r,n):r)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof P))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof P))throw TypeError(`endPacket must be an EncodedPacket.`);if(ga(n),this._track.input._disposed)throw new W;let r=[],{promise:i,resolve:a}=w(),{promise:o,resolve:s}=w(),c=!1,l=!1,u=null,d=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>p()){({promise:o,resolve:s}=w()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=w(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{d||(u=e,d=!0,a())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new W;else if(l)return{value:void 0,done:!0};else if(d)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(f.push(t);f.length>0&&t-f[0]>=1e3;)f.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},ba=class{constructor(e,t){this.onSample=e,this.onError=t}},xa=class{mediaSamplesInRange(e=-1/0,t=1/0,n){_a(e),_a(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=w(),{promise:c,resolve:l}=w(),u=!1,d=!1,f=!1,p=null,m=!1,h={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let n=await this._createDecoder(n=>{if(l(),n.timestamp>=t&&(d=!0),d){n.close();return}a&&(n.timestamp>e?(r.push(a),i=!0):a.close()),n.timestamp>=e&&(r.push(n),i=!0),a=i?null:n,r.length>0&&(s(),{promise:o,resolve:s}=w())},e=>{m||(p=e,m=!0,s())}),g=this._createPacketSink(),_=await g.getKeyPacket(e,h)??await g.getFirstKeyPacket(h),v=_,y=g.packets(_??void 0,void 0,h);for(await y.next();v&&!d&&!this._track.input._disposed;){let e=Sa(r.length);if(r.length+n.getDecodeQueueSize()>e){({promise:c,resolve:l}=w()),await c;continue}n.decode(v);let t=await y.next();if(t.done)break;v=t.value}await y.return(),!f&&!this._track.input._disposed&&await n.flush(),n.close(),!i&&a&&r.push(a),u=!0,s()})().catch(e=>{m||(p=e,m=!0,s())});let g=this._track,_=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(g.input._disposed)throw _(),new W;else if(f)return{value:void 0,done:!0};else if(m)throw _(),p;else if(r.length>0){let e=r.shift();return l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return f=!0,d=!0,l(),s(),_(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,n){re(e);let r=ne(e),i=[],a=[],{promise:o,resolve:s}=w(),{promise:c,resolve:l}=w(),u=!1,d=!1,f=null,p=!1,m=e=>{a.push(e),s(),{promise:o,resolve:s}=w()},h={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let e=await this._createDecoder(e=>{if(l(),d){e.close();return}let t=0;for(;i.length>0&&e.timestamp-i[0]>-1e-10;)t++,i.shift();if(t>0)for(let n=0;n<t;n++)m(n<t-1?e.clone():e);else e.close()},e=>{p||(f=e,p=!0,s())}),n=this._createPacketSink(),o=null,g=null,_=-1,v=async()=>{t(g);let r=g;for(e.decode(r);r.sequenceNumber<_;){let i=Sa(a.length);for(;a.length+e.getDecodeQueueSize()>i&&!d;)({promise:c,resolve:l}=w()),await c;if(d)break;let o=await n.getNextPacket(r,h);t(o),e.decode(o),r=o}_=-1},y=async()=>{await e.flush();for(let e=0;e<i.length;e++)m(null);i.length=0};for await(let e of r){if(_a(e),d||this._track.input._disposed)break;let t=await n.getPacket(e,h),r=t&&await n.getKeyPacket(e,h);if(!r){_!==-1&&(await v(),await y()),m(null),o=null;continue}o&&(r.sequenceNumber!==g.sequenceNumber||t.timestamp<o.timestamp)&&(await v(),await y()),i.push(t.timestamp),_=Math.max(t.sequenceNumber,_),o=t,g=r}!d&&!this._track.input._disposed&&(_!==-1&&await v(),await y()),e.close(),u=!0,s()})().catch(e=>{p||(f=e,p=!0,s())});let g=this._track,_=()=>{for(let e of a)e?.close()};return{async next(){for(;;)if(g.input._disposed)throw _(),new W;else if(d)return{value:void 0,done:!0};else if(p)throw _(),f;else if(a.length>0){let e=a.shift();return t(e!==void 0),l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return d=!0,l(),s(),_(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}};let Sa=e=>e===0?40:8;var Ca=class extends ba{constructor(e,n,r,i,a,s){super(e,n),this.codec=r,this.decoderConfig=i,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new _e,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let c=ma.find(e=>e.supports(r,i));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof Qi))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{n(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>n(e));else{let e=e=>{if(this.alphaQueue.length>0){let n=this.alphaQueue.shift();t(n!==void 0),this.mergeAlpha(e,n)}else this.colorQueue.push(e)};if(r===`avc`&&this.decoderConfig.description&&Ce()){let e=Tt(o(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=Dt(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let n=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=n,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(t(this.decoder),ye()||ee(this.inputTimestamps,e.timestamp,e=>e),Ce()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[],n=!1;for(let r of _t(e.data,this.decoderConfig)){let i=vt(e.data[r.offset]);if(n||=i>=1&&i<=5,i===k.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}e=new P(Ct(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=Vt(e.data,this.decoderConfig);t&&(e=new P(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||=new Ta,!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let n=this.colorQueue.shift();t(n!==void 0),this.mergeAlpha(n,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();t(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},n=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=n,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let n=Yt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=n===`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(n??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 At(e,this.decoderConfig)){let n=jt(e[t.offset]);if(n===A.RASL_N||n===A.RASL_R)return!0}return!1}sampleHandler(e){if(ye()){if(this.sampleQueue.length>0&&e.timestamp>=r(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ee(this.sampleQueue,e,e=>e.timestamp)}else{let n=this.inputTimestamps.shift();t(n!==void 0),e.setTimestamp(n),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,n){let r=w();this.mergeAlphaPromises.push(r.promise);let i={sample:null};this.finalSamples.push(i);try{for(n?(t(this.merger),i.sample=new Qi(await this.merger.merge(e,n))):i.sample=new Qi(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){T(this.finalSamples,i),this.onError(e)}finally{T(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),ye()){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()):(t(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}};let wa=null;var Ta=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!wa){let e=new Blob([`(${Ea.toString()})()`],{type:`application/javascript`});wa=URL.createObjectURL(e)}let e=ce(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(wa);e.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame))}),e.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let n=this.nextRequestId++,r=w();this.pendingRequests.set(n,r);let i=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,i.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};let Ea=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,n);if(n===`NV12`)return await o(e,t);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,r,i,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:n===`RGBX`||n===`RGBA`?`RGBA`:`BGRA`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=n.includes(`P10`),o=n.includes(`P12`),c=a||o?2:1,l,u;n.startsWith(`I420`)?(l=Math.ceil(r/2),u=Math.ceil(i/2)):n.startsWith(`I422`)?(l=Math.ceil(r/2),u=i):(l=r,u=i);let d=r*i,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,r,i,c),y=p+2*m;_.set(v,y);let b={format:n.slice(0,4)+`A`+n.slice(4),codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();(!t||t.byteLength!==c)&&(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();(!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}else return e.subarray(0,n*r*i)}},Da=e=>{if(!e||typeof e!=`object`)throw TypeError(`decoderOptions must be an object.`);if(e.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!=`boolean`)throw TypeError(`decoderOptions.optimizeForLatency, when provided, must be a boolean.`)};var Oa=class extends xa{constructor(e,t={}){if(!(e instanceof Ma))throw TypeError(`videoTrack must be an InputVideoTrack.`);Da(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,n){if(!await this._track.canDecode())throw Error(`This video track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getRotation(),a=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return t(r&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Ca(e,n,r,a,i,o)}_createPacketSink(){return new ya(this._track)}async getSample(e,t={}){_a(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},ka=class{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Ma))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&oa(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);t.decoderOptions!==void 0&&Da(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new Oa(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),i=await t.getSquarePixelHeight(),[a,o]=n%180==0?[r,i]:[i,r],s=e.crop;s&&=aa(s,a,o);let[c,l]=s?[s.width,s.height]:[a,o],u=c/l;e.width!==void 0&&e.height===void 0?(c=e.width,l=Math.round(c/u)):e.width===void 0&&e.height!==void 0?(l=e.height,c=Math.round(l*u)):e.width!==void 0&&e.height!==void 0&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=n,this._crop=s})()}_videoSampleToWrappedCanvas(e){let n=this._width,r=this._height,i=this._canvasPool[this._nextCanvasIndex],a=!1;i||(typeof document<`u`?(i=document.createElement(`canvas`),i.width=n,i.height=r):i=new OffscreenCanvas(n,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=i),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=i.getContext(`2d`,{alpha:this._alpha||xe()});t(o),o.resetTransform(),a||(!this._alpha&&xe()?(o.fillStyle=`black`,o.fillRect(0,0,n,r)):o.clearRect(0,0,n,r)),e.drawWithFit(o,{fit:this._fit,rotation:this._rotation,crop:this._crop});let s={canvas:i,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e,t){_a(e),await this._ensureInit();let n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*se(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*se(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},Aa=class e{constructor(e,t){
|
|
313
|
+
/*!
|
|
314
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
315
|
+
*
|
|
316
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
317
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
318
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
319
|
+
*/
|
|
320
|
+
this.input=e,this._backing=t}isVideoTrack(){return this instanceof Ma}isAudioTrack(){return this instanceof Na}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return U(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return U(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return U(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return U(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 U(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});return de((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new ya(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(La({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(La({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(La({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(La({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(La({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=ja(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=ja(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=ja(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}};let U=(e,t,n)=>{if(e instanceof Promise)throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},ja=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return r instanceof Promise?r.then(n):n(r)}:void 0};var Ma=class extends Aa{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 U(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()===`prores`}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return U(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return U(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getRotation(){return this._backing.getRotation()}get rotation(){return U(this._backing.getRotation(),`rotation`,`getRotation`)}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return U(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return U(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Fe({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Fe({num:U(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*U(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:U(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*U(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=U(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}let t=U(this._backing.getRotation(),`displayWidth`,`getDisplayWidth`)%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return U(t,`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=U(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}let t=U(this._backing.getRotation(),`displayHeight`,`getDisplayHeight`)%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return U(t,`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(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let n=await this._backing.getCodec();return t(n!==null),ma.some(t=>t.supports(n,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return D._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof P))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let n=await this.getCodec();if(n===null)return null;let r=await this.getDecoderConfig();return t(r),Yt(n,r,e.data)}},Na=class extends Aa{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return U(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return U(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return U(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let n=await this._backing.getCodec();return t(n!==null),ha.some(t=>t.supports(n,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return D._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof P))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}};let Pa=e=>-(e??-1/0),Fa=e=>-e,Ia=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return r instanceof Promise?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return r instanceof Promise?r.then(n):n(r)}:void 0}},La=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||i instanceof Promise?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),Ra=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>e instanceof Promise)?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)};
|
|
321
|
+
/*!
|
|
322
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
323
|
+
*
|
|
324
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
325
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
326
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
327
|
+
*/
|
|
328
|
+
Ae();var za=class e extends Re{get disposed(){return this._disposed}constructor(t){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,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof H)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof V||t.source instanceof ci))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof V&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&Ui(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},t.source instanceof V?this._rootRef=t.source.ref():this._rootRef=t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){t(this._rootSource instanceof li);let n=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:n.source,request:e,isRoot:e.isRoot}),n}_getSourceCached(e,n=1){let r=this._sourceCache.find(t=>t.cacheGroup===n&&ui(t.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());let i=this._sourceCachePromises.find(t=>t.cacheGroup===n&&ui(t.request,e));if(i)return i.promise.then(e=>e.sourceRef.source.ref());let a=(async()=>{let r=await this._getSourceUncached(e);if(Ne(this._sourceCache,e=>e.cacheGroup===n&&e.sourceRef.source._refCount===1)>=4){let e=Pe(this._sourceCache,e=>e.cacheGroup===n&&e.sourceRef.source._refCount===1?e.age:1/0);t(e!==-1);let r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),T(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);let i=this._sourceCachePromises.findIndex(t=>t.request===e);return t(i!==-1),this._sourceCachePromises.splice(i,1),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:n}})();return this._sourceCachePromises.push({request:e,cacheGroup:n,promise:a}),a.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Va(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 Ba})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),t(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Ba)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=Ia(e),Ra((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=Ia(e),Ra((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=Ia(e),Ra((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=Ia(e);let t=La(e,{sortBy:async e=>[Fa((await e.getDisposition()).default),Fa(await e.hasPairableAudioTrack()),Fa(!await e.hasOnlyKeyPackets()),Pa(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Ia(e);let t=await this.getPrimaryVideoTrack(),n=La(e,{sortBy:async e=>[Fa(!t||e.canBePairedWith(t)),Fa((await e.getDisposition()).default),Pa(await e.getBitrate())]});return(await this.getAudioTracks(n))[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 n=e.getType()===`video`?new Ma(this,e):new Na(this,e);return this._backingToTrack.set(e,n),n}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()}},Ba=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},W=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},Va=class{constructor(e){
|
|
329
|
+
/*!
|
|
330
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
331
|
+
*
|
|
332
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
333
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
334
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
335
|
+
*/
|
|
336
|
+
this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw 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 W;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=new Uint8Array;return new Ha(t,s(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,si);return r instanceof Promise?r.then(t=>t?new Ha(t.bytes,t.view,t.offset,e,n):null):r?new Ha(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new W;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,ce(this.fileSizeNonStrict-e,n,r));{let i=this.requestSlice(e,r),a=i=>i||(t(this.fileSizeNonStrict!==null),this.requestSlice(e,ce(this.fileSizeNonStrict-e,n,r)));return i instanceof Promise?i.then(a):a(i)}}requestEntireFile(){return this.fileSizeNonStrict===null?(async()=>{let e=[],t=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let n=this.requestSliceRange(t,0,1024);if(n instanceof Promise&&(n=await n),!n||n.length===0)break;let r=K(n,n.length);e.push(r),t+=n.length}let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new Ha(n,s(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},Ha=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,s(t),0,0,t.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(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}};let G=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},K=(e,t)=>{G(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},q=e=>(G(e,1),e.view.getUint8(e.bufferPos++)),Ua=(e,t)=>{G(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},J=e=>{G(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Wa=e=>{G(e,3);let t=ae(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ga=e=>{G(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Ka=(e,t)=>{G(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Y=e=>{G(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},qa=e=>{G(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Ja=e=>{G(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Ya=e=>{G(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},Xa=(e,t)=>{let n,r;return t?(n=Ka(e,!0),r=Ka(e,!0)):(r=Ka(e,!1),n=Ka(e,!1)),r*4294967296+n},X=e=>{let t=Y(e),n=Y(e);return t*4294967296+n},Za=e=>{let t=Ja(e),n=Y(e);return t*4294967296+n},Qa=e=>{let t=qa(e);return Ya(e)*4294967296+t},$a=e=>{G(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},eo=e=>{G(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Z=(e,t)=>{G(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},to=(e,t,n)=>c.decode(K(e,t)).split(`
|
|
337
|
+
`).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e));
|
|
338
|
+
/*!
|
|
339
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
340
|
+
*
|
|
341
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
342
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
343
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
344
|
+
*/
|
|
345
|
+
var no;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(no||={});var ro;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(ro||={});let io=`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`.split(`.`),ao=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=K(e,125),e.filePos=n;let r=oo(e,30);r&&(t.title??=r);let i=oo(e,30);i&&(t.artist??=i);let a=oo(e,30);a&&(t.album??=a);let o=oo(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=K(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=oo(e,28),e.skip(2)}else e.skip(-30),l=oo(e,30);l&&(t.comment??=l);let u=q(e);u<io.length&&(t.genre??=io[u])},oo=(e,t)=>{let n=K(e,t),r=Ee(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},Q=e=>{let t=e.filePos,n=Z(e,3),r=q(e),i=q(e),a=q(e),o=Y(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=ut(o);return a&no.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},so=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){D._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new co(t,K(e,t.flags&no.Footer?t.size-10:t.size));if(t.flags&no.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&no.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&no.Unsynchronisation)),o){D._warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){D._warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}if(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=r.readId3V2TextEncoding(),i=r.readId3V2Text(t,a),o=r.readId3V2Text(t,a);e[i]??=o}else e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size);switch(r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(io[e]!==void 0){n.genre??=io[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(io[e]!==void 0){n.genre??=io[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size;break}r.pos=a}};var co=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 n=this.bytes[t];e.push(n),n===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 n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.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 n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}else{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?ut(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:ut(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case ro.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case ro.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=Ee(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=Ee(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else{let e=Ee(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),c.decode(r.subarray(0,e))}case ro.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=Ee(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case ro.UTF_8:{let e=Ee(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),c.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}};let lo=1e6,uo=(e,t)=>{if(!Number.isFinite(e))throw TypeError(`${t} 必须是有限数字`);if(e<0)throw RangeError(`${t} 不能为负数`)},fo=e=>Number.isSafeInteger(e)&&e>=0,po=e=>{uo(e,`timeUs`);let t=Math.round(e);if(!Number.isSafeInteger(t))throw RangeError(`timeUs 超出安全整数范围`);return t},mo=e=>(uo(e,`seconds`),po(e*lo)),ho=e=>{if(!fo(e))throw RangeError(`timeUs 必须是非负安全整数`);return e/lo},go=e=>typeof e==`object`&&!!e,_o=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,vo=e=>_o(e)&&e>0&&e<=256,yo=e=>go(e)&&_o(e.index)&&typeof e.timeUs==`number`&&fo(e.timeUs),bo=e=>go(e)?e.type===`dispose`?!0:e.type===`open`?e.blob instanceof Blob&&vo(e.outputHeight):e.type===`extract`&&Array.isArray(e.frames)&&e.frames.every(yo):!1,xo=null,So=null,Co=0,wo=!1,To=!1,$=e=>{self.postMessage(e)},Eo=e=>`convertToBlob`in e?e.convertToBlob({quality:.72,type:`image/jpeg`}):new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(Error(`Mediabunny 无法编码视频缩略图`))},`image/jpeg`,.72)}),Do=()=>{wo||(wo=!0,xo?.dispose(),xo=null,So=null)},Oo=e=>e instanceof Ba?{code:`invalid-media`,message:`Mediabunny 无法解析该视频容器`,type:`error`}:{code:`decode`,message:e instanceof Error?`Mediabunny 视频缩略图解码失败:${e.message}`:`Mediabunny 视频缩略图解码失败`,type:`error`},ko=async(e,t)=>{xo=new za({formats:Hi,source:new fi(e)});try{let e=await xo.getPrimaryVideoTrack();if(!e){$({code:`invalid-media`,message:`Mediabunny 未找到可用的视频轨道`,type:`error`}),Do();return}if(!await e.canDecode()){$({code:`unsupported`,message:`当前浏览器不支持该视频编码格式的 WebCodecs 解码`,type:`error`}),Do();return}let[n,r,i,a]=await Promise.all([e.getDisplayHeight(),e.getDisplayWidth(),e.getFirstTimestamp(),e.computeDuration()]);if(!Number.isFinite(n)||n<=0||!Number.isFinite(r)||r<=0)throw Error(`Mediabunny 返回了无效的视频帧尺寸`);if(!Number.isFinite(i)||!Number.isFinite(a)||a<=i)throw Error(`Mediabunny 返回了无效的视频时长`);if(wo)return;Co=i,So=new ka(e,{height:t,poolSize:1}),$({frameWidth:Math.max(1,Math.round(r/n*t)),mediaDurationUs:mo(a-i),type:`ready`})}catch(e){if(wo||e instanceof W)return;$(Oo(e)),Do()}},Ao=async e=>{if(!So||To){$({code:`decode`,message:`Mediabunny 视频缩略图提取状态无效`,type:`error`});return}To=!0;let t=[...e].sort((e,t)=>e.timeUs-t.timeUs||e.index-t.index),n=t.map(e=>Co+ho(e.timeUs)),r=0;try{for await(let e of So.canvasesAtTimestamps(n)){let n=t[r];if(r+=1,!n||!e||wo)continue;let i=await Eo(e.canvas);if(wo)return;$({...n,blob:i,type:`frame`})}wo||$({type:`complete`})}catch(e){if(wo||e instanceof W)return;$(Oo(e))}finally{To=!1}};self.addEventListener(`message`,e=>{if(!(!bo(e.data)||wo)){if(e.data.type===`dispose`){Do(),$({type:`disposed`}),self.close();return}if(e.data.type===`open`){if(xo){$({code:`decode`,message:`Mediabunny 视频缩略图输入已打开`,type:`error`});return}ko(e.data.blob,e.data.outputHeight);return}Ao(e.data.frames)}})})();
|