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.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +224 -0
  3. package/dist/.dist-D4zXwUWp.js +81 -0
  4. package/dist/assets/audio-waveform.worker-DiTI_wJb.js +353 -0
  5. package/dist/assets/fonts/alibaba-puhuiti-2-regular.woff2 +0 -0
  6. package/dist/assets/fonts/licenses/source-han-sans-OFL-1.1.txt +96 -0
  7. package/dist/assets/fonts/licenses/zcool-gaoduanhei-usage-statement.txt +52 -0
  8. package/dist/assets/fonts/source-han-sans-cn-regular.otf +0 -0
  9. package/dist/assets/fonts/zcool-canger-yuyang-w03.ttf +0 -0
  10. package/dist/assets/fonts/zcool-gaoduanhei.ttf +0 -0
  11. package/dist/assets/fonts/zcool-kuaile.ttf +0 -0
  12. package/dist/assets/fonts/zcool-kuhei.ttf +0 -0
  13. package/dist/assets/fonts/zcool-wenyi.ttf +0 -0
  14. package/dist/assets/fonts/zcool-xiaowei-logo.otf +0 -0
  15. package/dist/assets/frame-preview.worker-ruBHl77w.js +345 -0
  16. package/dist/assets/soundtouch-processor-BKTidsbT.js +2062 -0
  17. package/dist/index.js +10802 -0
  18. package/dist/styles.css +1 -0
  19. package/dist/types/editor/EaseCut.d.ts +4 -0
  20. package/dist/types/editor/EaseCut.d.ts.map +1 -0
  21. package/dist/types/editor/api/create-easecut-api.d.ts +12 -0
  22. package/dist/types/editor/api/create-easecut-api.d.ts.map +1 -0
  23. package/dist/types/editor/api/easecut-api-context.d.ts +12 -0
  24. package/dist/types/editor/api/easecut-api-context.d.ts.map +1 -0
  25. package/dist/types/editor/api/errors.d.ts +6 -0
  26. package/dist/types/editor/api/errors.d.ts.map +1 -0
  27. package/dist/types/editor/api/index.d.ts +3 -0
  28. package/dist/types/editor/api/index.d.ts.map +1 -0
  29. package/dist/types/editor/api/source-input.d.ts +7 -0
  30. package/dist/types/editor/api/source-input.d.ts.map +1 -0
  31. package/dist/types/editor/api/source-store.d.ts +16 -0
  32. package/dist/types/editor/api/source-store.d.ts.map +1 -0
  33. package/dist/types/editor/api/types.d.ts +78 -0
  34. package/dist/types/editor/api/types.d.ts.map +1 -0
  35. package/dist/types/editor/components/AudioFloatingInspector.d.ts +10 -0
  36. package/dist/types/editor/components/AudioFloatingInspector.d.ts.map +1 -0
  37. package/dist/types/editor/components/CanvasRatioPanel.d.ts +2 -0
  38. package/dist/types/editor/components/CanvasRatioPanel.d.ts.map +1 -0
  39. package/dist/types/editor/components/ExportMenu.d.ts +8 -0
  40. package/dist/types/editor/components/ExportMenu.d.ts.map +1 -0
  41. package/dist/types/editor/components/FloatingInspector.d.ts +11 -0
  42. package/dist/types/editor/components/FloatingInspector.d.ts.map +1 -0
  43. package/dist/types/editor/components/FloatingInspectorBasicPanel.d.ts +10 -0
  44. package/dist/types/editor/components/FloatingInspectorBasicPanel.d.ts.map +1 -0
  45. package/dist/types/editor/components/FloatingInspectorShell.d.ts +15 -0
  46. package/dist/types/editor/components/FloatingInspectorShell.d.ts.map +1 -0
  47. package/dist/types/editor/components/FloatingInspectorSpeedPanel.d.ts +7 -0
  48. package/dist/types/editor/components/FloatingInspectorSpeedPanel.d.ts.map +1 -0
  49. package/dist/types/editor/components/FormDialog.d.ts +16 -0
  50. package/dist/types/editor/components/FormDialog.d.ts.map +1 -0
  51. package/dist/types/editor/components/PreviewPanel.d.ts +9 -0
  52. package/dist/types/editor/components/PreviewPanel.d.ts.map +1 -0
  53. package/dist/types/editor/components/TextFloatingInspector.d.ts +12 -0
  54. package/dist/types/editor/components/TextFloatingInspector.d.ts.map +1 -0
  55. package/dist/types/editor/components/TimelineToolbar.d.ts +8 -0
  56. package/dist/types/editor/components/TimelineToolbar.d.ts.map +1 -0
  57. package/dist/types/editor/components/TitleContentTextarea.d.ts +8 -0
  58. package/dist/types/editor/components/TitleContentTextarea.d.ts.map +1 -0
  59. package/dist/types/editor/components/VideoFloatingInspector.d.ts +12 -0
  60. package/dist/types/editor/components/VideoFloatingInspector.d.ts.map +1 -0
  61. package/dist/types/editor/components/ui/ColorInput.d.ts +15 -0
  62. package/dist/types/editor/components/ui/ColorInput.d.ts.map +1 -0
  63. package/dist/types/editor/components/ui/IconButton.d.ts +15 -0
  64. package/dist/types/editor/components/ui/IconButton.d.ts.map +1 -0
  65. package/dist/types/editor/components/ui/InputNumber.d.ts +13 -0
  66. package/dist/types/editor/components/ui/InputNumber.d.ts.map +1 -0
  67. package/dist/types/editor/components/ui/Select.d.ts +14 -0
  68. package/dist/types/editor/components/ui/Select.d.ts.map +1 -0
  69. package/dist/types/editor/components/ui/TextInput.d.ts +10 -0
  70. package/dist/types/editor/components/ui/TextInput.d.ts.map +1 -0
  71. package/dist/types/editor/core/audio-waveform-bars.d.ts +50 -0
  72. package/dist/types/editor/core/audio-waveform-bars.d.ts.map +1 -0
  73. package/dist/types/editor/core/canvas-size.d.ts +44 -0
  74. package/dist/types/editor/core/canvas-size.d.ts.map +1 -0
  75. package/dist/types/editor/core/clip-speed.d.ts +11 -0
  76. package/dist/types/editor/core/clip-speed.d.ts.map +1 -0
  77. package/dist/types/editor/core/collision.d.ts +96 -0
  78. package/dist/types/editor/core/collision.d.ts.map +1 -0
  79. package/dist/types/editor/core/composition.d.ts +47 -0
  80. package/dist/types/editor/core/composition.d.ts.map +1 -0
  81. package/dist/types/editor/core/export-schema.d.ts +5 -0
  82. package/dist/types/editor/core/export-schema.d.ts.map +1 -0
  83. package/dist/types/editor/core/index.d.ts +11 -0
  84. package/dist/types/editor/core/index.d.ts.map +1 -0
  85. package/dist/types/editor/core/model.d.ts +187 -0
  86. package/dist/types/editor/core/model.d.ts.map +1 -0
  87. package/dist/types/editor/core/preview-snapping.d.ts +27 -0
  88. package/dist/types/editor/core/preview-snapping.d.ts.map +1 -0
  89. package/dist/types/editor/core/text-fonts.d.ts +76 -0
  90. package/dist/types/editor/core/text-fonts.d.ts.map +1 -0
  91. package/dist/types/editor/core/time.d.ts +15 -0
  92. package/dist/types/editor/core/time.d.ts.map +1 -0
  93. package/dist/types/editor/core/timeline-commands.d.ts +143 -0
  94. package/dist/types/editor/core/timeline-commands.d.ts.map +1 -0
  95. package/dist/types/editor/core/timeline-layout.d.ts +25 -0
  96. package/dist/types/editor/core/timeline-layout.d.ts.map +1 -0
  97. package/dist/types/editor/core/timeline-math.d.ts +22 -0
  98. package/dist/types/editor/core/timeline-math.d.ts.map +1 -0
  99. package/dist/types/editor/core/timeline-tracks.d.ts +47 -0
  100. package/dist/types/editor/core/timeline-tracks.d.ts.map +1 -0
  101. package/dist/types/editor/media/audio-waveform-peaks.d.ts +17 -0
  102. package/dist/types/editor/media/audio-waveform-peaks.d.ts.map +1 -0
  103. package/dist/types/editor/media/audio-waveform.d.ts +8 -0
  104. package/dist/types/editor/media/audio-waveform.d.ts.map +1 -0
  105. package/dist/types/editor/media/frame-preview.d.ts +25 -0
  106. package/dist/types/editor/media/frame-preview.d.ts.map +1 -0
  107. package/dist/types/editor/media/index.d.ts +6 -0
  108. package/dist/types/editor/media/index.d.ts.map +1 -0
  109. package/dist/types/editor/media/media-runtime.d.ts +47 -0
  110. package/dist/types/editor/media/media-runtime.d.ts.map +1 -0
  111. package/dist/types/editor/media/mediabunny-audio-waveform.d.ts +8 -0
  112. package/dist/types/editor/media/mediabunny-audio-waveform.d.ts.map +1 -0
  113. package/dist/types/editor/media/mediabunny-frame-preview.d.ts +21 -0
  114. package/dist/types/editor/media/mediabunny-frame-preview.d.ts.map +1 -0
  115. package/dist/types/editor/media/preview-audio-engine.d.ts +23 -0
  116. package/dist/types/editor/media/preview-audio-engine.d.ts.map +1 -0
  117. package/dist/types/editor/media/preview-playback-controller.d.ts +26 -0
  118. package/dist/types/editor/media/preview-playback-controller.d.ts.map +1 -0
  119. package/dist/types/editor/media/single-frame-preview.d.ts +30 -0
  120. package/dist/types/editor/media/single-frame-preview.d.ts.map +1 -0
  121. package/dist/types/editor/media/text-layout-runtime.d.ts +27 -0
  122. package/dist/types/editor/media/text-layout-runtime.d.ts.map +1 -0
  123. package/dist/types/editor/store/index.d.ts +3 -0
  124. package/dist/types/editor/store/index.d.ts.map +1 -0
  125. package/dist/types/editor/store/timeline-store-context.d.ts +14 -0
  126. package/dist/types/editor/store/timeline-store-context.d.ts.map +1 -0
  127. package/dist/types/editor/store/timeline-store.d.ts +115 -0
  128. package/dist/types/editor/store/timeline-store.d.ts.map +1 -0
  129. package/dist/types/editor/timeline/AudioWaveformCanvas.d.ts +13 -0
  130. package/dist/types/editor/timeline/AudioWaveformCanvas.d.ts.map +1 -0
  131. package/dist/types/editor/timeline/TimelineClip.d.ts +41 -0
  132. package/dist/types/editor/timeline/TimelineClip.d.ts.map +1 -0
  133. package/dist/types/editor/timeline/TimelineDragGhost.d.ts +9 -0
  134. package/dist/types/editor/timeline/TimelineDragGhost.d.ts.map +1 -0
  135. package/dist/types/editor/timeline/TimelinePanel.d.ts +11 -0
  136. package/dist/types/editor/timeline/TimelinePanel.d.ts.map +1 -0
  137. package/dist/types/editor/timeline/TimelineRuler.d.ts +14 -0
  138. package/dist/types/editor/timeline/TimelineRuler.d.ts.map +1 -0
  139. package/dist/types/editor/timeline/TimelineTrimHandle.d.ts +12 -0
  140. package/dist/types/editor/timeline/TimelineTrimHandle.d.ts.map +1 -0
  141. package/dist/types/editor/timeline/TimelineViewport.d.ts +8 -0
  142. package/dist/types/editor/timeline/TimelineViewport.d.ts.map +1 -0
  143. package/dist/types/editor/timeline/clip-reveal.d.ts +29 -0
  144. package/dist/types/editor/timeline/clip-reveal.d.ts.map +1 -0
  145. package/dist/types/editor/timeline/timeline-interaction.d.ts +79 -0
  146. package/dist/types/editor/timeline/timeline-interaction.d.ts.map +1 -0
  147. package/dist/types/editor/timeline/useTimelineController.d.ts +22 -0
  148. package/dist/types/editor/timeline/useTimelineController.d.ts.map +1 -0
  149. package/dist/types/editor/types.d.ts +52 -0
  150. package/dist/types/editor/types.d.ts.map +1 -0
  151. package/dist/types/editor/util/abort-error.d.ts +3 -0
  152. package/dist/types/editor/util/abort-error.d.ts.map +1 -0
  153. package/dist/types/editor/util/browser.d.ts +5 -0
  154. package/dist/types/editor/util/browser.d.ts.map +1 -0
  155. package/dist/types/editor/util/format-canvas-font.d.ts +7 -0
  156. package/dist/types/editor/util/format-canvas-font.d.ts.map +1 -0
  157. package/dist/types/editor/util/format-media-label.d.ts +4 -0
  158. package/dist/types/editor/util/format-media-label.d.ts.map +1 -0
  159. package/dist/types/editor/util/format-text-color.d.ts +4 -0
  160. package/dist/types/editor/util/format-text-color.d.ts.map +1 -0
  161. package/dist/types/editor/util/format-timeline-time.d.ts +6 -0
  162. package/dist/types/editor/util/format-timeline-time.d.ts.map +1 -0
  163. package/dist/types/editor/util/id.d.ts +2 -0
  164. package/dist/types/editor/util/id.d.ts.map +1 -0
  165. package/dist/types/editor/util/media-file-format.d.ts +6 -0
  166. package/dist/types/editor/util/media-file-format.d.ts.map +1 -0
  167. package/dist/types/editor/util/number.d.ts +6 -0
  168. package/dist/types/editor/util/number.d.ts.map +1 -0
  169. package/dist/types/editor/util/text.d.ts +2 -0
  170. package/dist/types/editor/util/text.d.ts.map +1 -0
  171. package/dist/types/editor/util/url.d.ts +5 -0
  172. package/dist/types/editor/util/url.d.ts.map +1 -0
  173. package/dist/types/editor/util/value.d.ts +3 -0
  174. package/dist/types/editor/util/value.d.ts.map +1 -0
  175. package/dist/types/editor/workers/audio-waveform-protocol.d.ts +24 -0
  176. package/dist/types/editor/workers/audio-waveform-protocol.d.ts.map +1 -0
  177. package/dist/types/editor/workers/audio-waveform.worker.d.ts +2 -0
  178. package/dist/types/editor/workers/audio-waveform.worker.d.ts.map +1 -0
  179. package/dist/types/editor/workers/frame-preview-protocol.d.ts +35 -0
  180. package/dist/types/editor/workers/frame-preview-protocol.d.ts.map +1 -0
  181. package/dist/types/editor/workers/frame-preview.worker.d.ts +2 -0
  182. package/dist/types/editor/workers/frame-preview.worker.d.ts.map +1 -0
  183. package/dist/types/index.d.ts +7 -0
  184. package/dist/types/index.d.ts.map +1 -0
  185. package/package.json +74 -0
@@ -0,0 +1,353 @@
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},w=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},ee=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},T=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},E=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},te=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},ne=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},re=e=>{throw Error(`Unexpected value: ${e}`)},ie=(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},ae=(e,t,n)=>ie(e,t,n)<<8>>8,oe=(e,t,n)=>Math.max(t,Math.min(n,e)),se=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},ce=(e,t)=>Math.round(e/t)*t,le=(e,t)=>Math.round(e*t)/t,ue=(e,t)=>Math.floor(e/t)*t,de=e=>{let t=0;for(;e;)t++,e>>=1;return t},fe=/^[a-z]{3}$/,pe=e=>fe.test(e),me=1e6*(1+2**-52);var he=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}};let ge=null,_e=()=>ge===null?ge=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):ge,ve=null,ye=()=>ve===null?ve=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):ve,be=null,xe=()=>{if(be!==null)return be;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?be=Number(e[1]):null},Se=(e,t)=>e===-1?t:e,Ce=(e,t,n,r)=>e<=r&&n<=t,we=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},Te=(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},Ee=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},De=e=>typeof e==`number`&&!Number.isNaN(e),Oe=(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(`/`)},ke=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},Ae=(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},je=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}},Me=e=>new Promise(t=>setTimeout(t,e));var Ne=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)}}},Pe
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`})(Pe||={});var D=class e{constructor(){}static get level(){return e._level}static set level(t){if(t!==Pe.Silent&&t!==Pe.Errors&&t!==Pe.Warnings&&t!==Pe.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 Ne}static on(t,n,r){return e._emitter.on(t,n,r)}static _error(...t){e._emitter._emit(`error`,t),e._level>=Pe.Errors&&console.error(...t)}static _warn(...t){e._emitter._emit(`warn`,t),e._level>=Pe.Warnings&&console.warn(...t)}static _info(...t){e._emitter._emit(`info`,t),e._level>=Pe.Info&&console.info(...t)}};D._level=Pe.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 Fe=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.`)}},Ie=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 O={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 k=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 Le=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Re=[-1,1,2,3,4,5,6,8],ze=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new k(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<Le.length&&(i=Le[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=Re[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},Be=[`avc`,`hevc`,`vp9`,`av1`,`vp8`,`prores`],Ve=[`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`],He=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`,...Ve],Ue=[{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}],We=[{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}],Ge=[`ap4x`,`ap4h`,`apch`,`apcn`,`apcs`,`apco`],Ke=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(We).level;for(let e of We)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(We).level;for(let e of We)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&&re(n);throw TypeError(`Unhandled codec '${n}'.`)},qe=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?ze(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&&Ve.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Je=48e3,Ye=/^pcm-([usf])(\d+)(be)?$/,Xe=e=>{if(t(Ve.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=Ye.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}},Ze=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`:Ge.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`:Ye.test(e)?e:e===`webvtt`?`webvtt`:null;[...Ge];
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 Qe=[44100,48e3,32e3],$e=[-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],et=(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,tt=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,nt=(e,t)=>e===3?t===3?21:36:t===3?13:21,rt=(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=$e[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=Qe[d]>>o+s,x=et(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}},it=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n};var at;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(at||={});let ot=e=>e===3?1:2,st=[48e3,44100,32e3],ct=[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 A;(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`})(A||={});var j;(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`})(j||={});let lt=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})},ut=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=ie(i,r,!1):(t(n===4),e=i.getUint32(r,!1)),r+=n,yield{offset:r,length:e},r+=e}},dt=(e,t)=>{if(t.description){let n=(o(t.description)[4]&3)+1;return ut(e,n)}else return lt(e)},ft=e=>e&31,pt=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)};new Uint8Array([0,0,0,1]);let mt=e=>{try{let n=[],r=[],i=[];for(let t of lt(e)){let a=e.subarray(t.offset,t.offset+t.length),o=ft(a[0]);o===A.SPS?n.push(a):o===A.PPS?r.push(a):o===A.SPS_EXT&&i.push(a)}if(n.length===0||r.length===0)return null;let a=n[0],o=gt(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}},ht={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}},gt=e=>{try{let n=new k(pt(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,w=0,ee={num:1,den:1},T=null,E=null;if(n.readBits(1)){if(n.readBits(1)){let e=n.readBits(8);if(e===255)ee={num:n.readBits(16),den:n.readBits(16)};else{let t=ht[e];t&&(ee=t)}}n.readBits(1)&&n.skipBits(1),n.readBits(1)&&(n.skipBits(3),w=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&&_t(n);let t=n.readBits(1);t&&_t(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=Ue.find(e=>e.level>=c)??r(Ue),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:ee,colourPrimaries:x,matrixCoefficients:C,transferCharacteristics:S,fullRangeFlag:w,numReorderFrames:T,maxDecFrameBuffering:E}}catch(e){return D._error(`Error parsing AVC SPS:`,e),null}},_t=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)},vt=(e,t)=>{if(t.description){let n=(o(t.description)[21]&3)+1;return ut(e,n)}else return lt(e)},yt=e=>e>>1&63,bt=e=>{try{let t=new k(pt(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}=St(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)&&Ct(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(wt(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,w=2,ee=0,T=0,E={num:1,den:1};if(t.readBits(1)){let e=Et(t,n);E=e.pixelAspectRatio,S=e.colourPrimaries,C=e.transferCharacteristics,w=e.matrixCoefficients,ee=e.fullRangeFlag,T=e.minSpatialSegmentationIdc}return{displayWidth:h,displayHeight:g,pixelAspectRatio:E,colourPrimaries:S,transferCharacteristics:C,matrixCoefficients:w,fullRangeFlag:ee,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}},xt=e=>{try{let t=[],n=[],r=[],o=[];for(let i of lt(e)){let a=e.subarray(i.offset,i.offset+i.length),s=yt(a[0]);s===j.VPS_NUT?t.push(a):s===j.SPS_NUT?n.push(a):s===j.PPS_NUT?r.push(a):(s===j.PREFIX_SEI_NUT||s===j.SUFFIX_SEI_NUT)&&o.push(a)}if(n.length===0||r.length===0)return null;let s=bt(n[0]);if(!s)return null;let c=0;if(r.length>0){let e=r[0],t=new k(pt(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:j.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:j.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:j.PPS_NUT,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:yt(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}},St=(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}},Ct=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)}},wt=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Tt(e,r,t,n)},Tt=(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},Et=(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=ht[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)&&Dt(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}},Dt=(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&&Ot(e,c,o),a&&Ot(e,c,o)}},Ot=(e,t,n)=>{for(let r=0;r<t;r++)i(e),i(e),n&&(i(e),i(e)),e.readBits(1)};var kt;(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`})(kt||={});let At=e=>{let t=new k(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(We).level;for(let e of We)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}},jt=function*(e){let n=new k(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)}},Mt=e=>{for(let{type:t,data:n}of jt(e)){if(t!==1)continue;let e=new k(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},Nt=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}},Pt=[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],Ft=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:Pt[t]*r}},It=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 k(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}},Lt=(e,n,r)=>{switch(e){case`avc`:for(let e of dt(r,n)){let t=r[e.offset],n=ft(t);if(n>=A.NON_IDR_SLICE&&n<=A.SLICE_DPC)return`delta`;if(n===A.IDR)return`key`;if(n===A.SEI&&(!ye()||xe()>=144)){let t=r.subarray(e.offset,e.offset+e.length),n=pt(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 k(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 vt(r,n)){let t=yt(r[e.offset]);if(t<j.BLA_W_LP)return`delta`;if(t<=j.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return r[0]&1?`delta`:`key`;case`vp9`:{let e=new k(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 jt(r))if(t===1){let t=new k(n);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new k(n);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}case`prores`:return`key`;default:re(e),t(!1)}};var Rt;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(Rt||={});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=we(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}}},Bt=[2,1,2,3,3,4,4,5],Vt=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new k(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)}},Ht=[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 Ut=[1,2,3,6],Wt=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new k(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=Ut[o],d;return d=i<3?st[i]/1e3:ct[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}]}},Gt=e=>{if(e.length<2)return null;let t=new k(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}},Kt=e=>{let n=e.substreams[0];return t(n),n.fscod<3?st[n.fscod]:n.fscod2!==null&&n.fscod2<3?ct[n.fscod2]:null},qt=e=>{let n=e.substreams[0];t(n);let r=Bt[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(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*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 Jt=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},Yt=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)}},Xt=(e,t)=>e.systemId===t.systemId&&Te(e.data,t.data),Zt=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=Z(e),n=$(e,4),r=8;t===1&&(t=Q(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},Qt=e=>ba(e)/65536,$t=e=>ba(e)/1073741824,en=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=Y(e);if(t|=n&127,!(n&128))break}return t},F=e=>{let t=X(e);return e.skip(2),t=Math.min(t,e.remainingLength),c.decode(J(e,t))},tn=e=>{let t=Zt(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=Z(e);e.skip(4);let r=J(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 Fe(r,`image/jpeg`);case 14:return new Fe(r,`image/png`);case 27:return new Fe(r,`image/bmp`);default:return r}},I=new Uint32Array(256),nn=new Uint32Array(256),rn=new Uint32Array(256),an=new Uint32Array(256),on=new Uint32Array(256),L=new Uint32Array(256),sn=new Uint32Array(10),cn=!1,ln=()=>{
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);I[t]=n<<24|n<<16|n<<8|n,L[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;nn[t]=l,rn[t]=l>>>8|l<<24,an[t]=l>>>16|l<<16,on[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)sn[e]=i<<24,i=i<<1^(i&128?283:0);cn=!0};var un=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),cn||ln();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]^I[t>>>16&255]&4278190080^I[t>>>8&255]&16711680^I[t>>>0&255]&65280^I[t>>>24&255]&255^sn[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]=nn[I[n>>>24&255]&255]^rn[I[n>>>16&255]&255]^an[I[n>>>8&255]&255]^on[I[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=nn[e>>>24]^rn[r>>>16&255]^an[n>>>8&255]^on[t&255]^this.roundkey[a],l=nn[t>>>24]^rn[e>>>16&255]^an[r>>>8&255]^on[n&255]^this.roundkey[a+1],u=nn[n>>>24]^rn[t>>>16&255]^an[e>>>8&255]^on[r&255]^this.roundkey[a+2],d=nn[r>>>24]^rn[n>>>16&255]^an[t>>>8&255]^on[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=L[e>>>24&255]&4278190080^L[r>>>16&255]&16711680^L[n>>>8&255]&65280^L[t>>>0&255]&255^this.roundkey[40],p=L[t>>>24&255]&4278190080^L[e>>>16&255]&16711680^L[r>>>8&255]&65280^L[n>>>0&255]&255^this.roundkey[41],m=L[n>>>24&255]&4278190080^L[t>>>16&255]&16711680^L[e>>>8&255]&65280^L[r>>>0&255]&255^this.roundkey[42],h=L[r>>>24&255]&4278190080^L[n>>>16&255]&16711680^L[t>>>8&255]&65280^L[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 dn=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new un;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=J(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 fn=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 Jt({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=Zt(i);if(!o)break;if(o.name===`ftyp`||o.name===`styp`){let e=$(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 mn(n),this.tracks.push(n)):n.info.type===`audio`&&n.info.numberOfChannels!==-1&&(n.trackBacking=new hn(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=Z(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=Zt(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&&Ve.includes(e.info.codec)&&n.sampleCompositionTimeOffsets.length===0){t(e.info?.type===`audio`);let i=Xe(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=Zt(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)bn(e,r.timestamp);else{let t=C(n,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];bn(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 wn(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=Zt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let i=e.filePos,a=Zt(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=Y(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=Z(e),this.movieDurationInTimescale=Q(e)):(e.skip(8),this.movieTimescale=Z(e),this.movieDurationInTimescale=Z(e))}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...O,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 mn(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new hn(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let r=this.currentTrack;if(!r)break;let i=Y(e),a=!!(ga(e)&1);if(r.disposition.default=a,i===0)e.skip(8),r.id=Z(e),e.skip(4),r.durationInMovieTimescale=Z(e);else if(i===1)e.skip(16),r.id=Z(e),e.skip(4),r.durationInMovieTimescale=Q(e);else throw Error(`Incorrect track header version ${i}.`);e.skip(16);let o=[Qt(e),Qt(e),$t(e),Qt(e),Qt(e),$t(e),Qt(e),Qt(e),$t(e)],s=n(ce(xn(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=Y(e);e.skip(3);let r=!1,i=0,a=Z(e);for(let o=0;o<a;o++){let a=n===1?Q(e):Z(e),o=n===1?Ca(e):ba(e),s=Qt(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=Y(e);e.skip(3),n===0?(e.skip(8),t.timescale=Z(e),t.durationInMediaTimescale=Z(e)):n===1&&(e.skip(16),t.timescale=Z(e),t.durationInMediaTimescale=Q(e));let r=X(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;pe(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=$(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=Y(e);e.skip(3);let r=Z(e);for(let i=0;i<r;i++){let r=e.filePos,i=Zt(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=X(e),t.info.height=X(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`:Ge.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=X(e);e.skip(6);let s=X(e),c=X(e);e.skip(4);let l=Z(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*Z(e),e.skip(8)):o===2&&(e.skip(4),l=Ea(e),s=Z(e),e.skip(4),c=Z(e),u=Z(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=Je;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=$(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=$(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=Y(e);e.skip(3),e.skip(1);let r=Y(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=Y(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=Y(e),t.encryptionInfo.defaultKid=y(J(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=Y(e),r=new Uint8Array(16);r.set(J(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let n=this.currentTrack;if(!n)break;t(n.info),n.info.codecDescription=J(e,a.contentSize)}break;case`hvcC`:{let n=this.currentTrack;if(!n)break;t(n.info),n.info.codecDescription=J(e,a.contentSize)}break;case`vpcC`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`video`),e.skip(4);let r=Y(e),i=Y(e),a=Y(e),o=a>>4,s=a>>1&7,c=a&1,l=Y(e),u=Y(e),d=Y(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=Y(e),i=r>>5,a=r&31,o=Y(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=$(e,4);if(r!==`nclx`&&r!==`nclc`)break;let i=X(e),a=X(e),o=X(e),s;r===`nclx`&&(s=!!(Y(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=Z(e),i=Z(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(Y(e)===3),en(e),e.skip(2);let r=Y(e),i=(r&128)!=0,a=(r&64)!=0,o=(r&32)!=0;if(i&&e.skip(2),a){let t=Y(e);e.skip(t)}o&&e.skip(2),t(Y(e)===4);let s=en(e),c=e.filePos,l=Y(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(Y(e)===5);let r=en(e);if(n.info.codecDescription=J(e,r),n.info.codec===`aac`){let e=ze(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=!!(X(e)&255)}break;case`pcmC`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(4);let r=Y(e);n.info.pcmLittleEndian=!!(r&1),n.info.pcmSampleSize=Y(e)}break;case`dOps`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`),e.skip(1);let r=Y(e),i=X(e),a=Z(e),o=_a(e),s=Y(e),c;c=s===0?new Uint8Array:J(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=Y(e),r=ga(e);if((t&127)===Rt.STREAMINFO){e.skip(10);let t=Z(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=J(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 k(J(e,3)),i=r.readBits(2);r.skipBits(8);let a=r.readBits(3),o=r.readBits(1);i<3&&(n.info.sampleRate=st[i]),n.info.numberOfChannels=Bt[a]+o}break;case`dec3`:{let n=this.currentTrack;if(!n)break;t(n.info?.type===`audio`);let r=Gt(J(e,a.contentSize));if(!r){D._warn(`Invalid dec3 box contents, ignoring.`);break}let i=Kt(r);i!==null&&(n.info.sampleRate=i),n.info.numberOfChannels=qt(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Z(e),r=0,i=0;for(let a=0;a<n;a++){let n=Z(e),a=Z(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=Z(e),r=0;for(let i=0;i<n;i++){let n=Z(e),i=ba(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=Z(e),r=Z(e);if(n===0)for(let n=0;n<r;n++){let n=Z(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=Y(e),r=Z(e),i=new k(J(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=Z(e);for(let r=0;r<n;r++){let n=Z(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=Z(e);for(let r=0;r<n;r++){let n=Z(e)-1,r=Z(e),i=Z(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=Z(e);for(let r=0;r<n;r++){let n=Z(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Z(e);for(let r=0;r<n;r++){let n=Q(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`mehd`:{let t=Y(e);e.skip(3);let n=t===1?Q(e):Z(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=Z(e),n=Z(e),r=Z(e),i=Z(e),a=Z(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=Y(e);e.skip(3);let n=Z(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=Z(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[Y,X,ga,Z],l=c[a],u=c[o],d=c[s],f=Z(e);for(let n=0;n<f;n++){let n=t===1?Q(e):Z(e),i=t===1?Q(e):Z(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&&(bn(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=Yt(J(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=ga(e),r=!!(n&1),i=!!(n&2),a=!!(n&8),o=!!(n&16),s=!!(n&32),c=!!(n&65536),l=!!(n&131072),u=Z(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=Q(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(d.currentFragmentState.sampleDescriptionIndex=Z(e)),a&&(d.currentFragmentState.defaultSampleDuration=Z(e)),o&&(d.currentFragmentState.defaultSampleSize=Z(e)),s&&(d.currentFragmentState.defaultSampleFlags=Z(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let n=this.currentTrack;if(!n)break;t(n.currentFragmentState);let r=Y(e);e.skip(3);let i=r===0?Z(e):Q(e);n.currentFragmentState.startTimestamp=i}break;case`trun`:{let n=this.currentTrack;if(!n)break;t(this.currentFragment),t(n.currentFragmentState);let r=Y(e),i=ga(e),a=!!(i&1),o=!!(i&4),s=!!(i&256),c=!!(i&512),l=!!(i&1024),u=!!(i&2048),d=Z(e),f=null;a&&(f=ba(e));let p=null;o&&(p=Z(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=Z(e):(t(n.currentFragmentState.defaultSampleDuration!==null),a=n.currentFragmentState.defaultSampleDuration);let o;c?o=Z(e):(t(n.currentFragmentState.defaultSampleSize!==null),o=n.currentFragmentState.defaultSampleSize);let d;l?d=Z(e):(t(n.currentFragmentState.defaultSampleFlags!==null),d=n.currentFragmentState.defaultSampleFlags),i===0&&p!==null&&(d=p);let f=0;u&&(f=r===0?Z(e):ba(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),ga(e)&1){let n=$(e,4),r=Z(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=Y(e),r=Z(e),i=null;n===0&&r>0&&(i=J(e,r));let a=Cn(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=Y(e);if(ga(e)&1){let n=$(e,4),r=Z(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=Z(e);if(r===0)break;r>1&&D._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?Z(e):Number(Q(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Cn(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=!!(ga(e)&2),a=Z(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(J(e,o),0):a.set(n.encryptionInfo.defaultConstantIv,0);let s=null;if(i){let t=X(e);s=[];for(let n=0;n<t;n++){let t=X(e),n=Z(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]??=J(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(J(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=Z(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=Z(e);for(let n=0;n<t;n++){let t=Z(e);e.skip(4);let r=c.decode(J(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=tn(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 Fe?(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}},pn=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 se(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=gn(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Sn(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=_n(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Sn(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=E(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=yn(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=vn(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=J(n,i.sampleSize),this.internalTrack.encryptionAuxInfo){t(this.internalTrack.encryptionInfo);let n=await wn(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(a=await Tn(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=J(t,i.byteSize),i.encryption&&(a=await Tn(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=Zt(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}},mn=class extends pn{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&&At(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Mt(e.data)}let e={codec:Ke(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}},hn=class extends pn{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:qe(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}};let gn=(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)}},_n=(e,t)=>{if(!e.keySampleIndices)return gn(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=gn(e,t),r=C(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},vn=(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}},yn=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=C(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},bn=(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},xn=e=>{let[t,n]=e,r=Math.atan2(n,t);return Number.isFinite(r)?180/Math.PI*r:0},Sn=e=>e.sampleSizes.length===0,Cn=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},wn=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(J(a,o),0):i.set(n.defaultConstantIv,0);let c=null;if(t>o){let e=X(a);c=[];for(let t=0;t<e;t++){let e=X(a),t=Z(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},Tn=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++)Xt(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`?En(s,a,n,r):Dn(s,a,n,r)},En=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=On(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},Dn=(e,n,r,i)=>{let a=new un;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=On(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},On=(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 R;(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`})(R||={});let kn=[R.EBML,R.Segment],An=[R.SeekHead,R.Info,R.Cluster,R.Tracks,R.Cues,R.Attachments,R.Chapters,R.Tags],jn=[...kn,...An],Mn=e=>{if(e.remainingLength<1)return null;let t=Y(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},Nn=e=>{if(e.remainingLength<1)return null;let t=Y(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+=Y(e);return i},z=(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+=Y(e);return n},Pn=(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(Y(e));return n},Fn=e=>{let t=Mn(e);return t===null||e.remainingLength<t?null:z(e,t)},In=e=>{if(e.remainingLength<1)return null;if(Y(e)===255)return;e.skip(-1);let t=Nn(e);if(t===null)return null;if(t!==72057594037927940)return t},B=e=>{t(e.remainingLength>=2);let n=Fn(e);if(n===null)return null;let r=In(e);return r===null?null:{id:n,size:r}},Ln=(e,t)=>{let n=J(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},Rn=(e,t)=>{let n=J(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return c.decode(n.subarray(0,r))},zn=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?Ta(e):Ea(e)},Bn=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=B(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Hn(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},Vn=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=Fn(t);if(e!==null&&a.has(e))return o;o++}}return null},V={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 Hn(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 Un=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 Wn;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(Wn||={});var Gn;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(Gn||={});var Kn;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(Kn||={});let qn=[{id:R.SeekHead,flag:`seekHeadSeen`},{id:R.Info,flag:`infoSeen`},{id:R.Tracks,flag:`tracksSeen`},{id:R.Cues,flag:`cuesSeen`}],Jn=10*2**20;var Yn=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 Un({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=B(t);if(!n)break;let i=n.id,a=n.size,o=t.filePos;if(i===R.EBML){Hn(a);let e=this.reader.requestSlice(o,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(i===R.Segment){if(await this.readSegment(o,a),a===void 0||this.reader.fileSize===null)break}else if(i===R.Cluster){if(this.reader.fileSize===null)break;a===void 0&&(a=(await Bn(this.reader,o,jn,this.reader.fileSize)).pos-o);let e=r(this.segments);e&&(e.elementEndPos=o+a)}Hn(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=B(e);if(!r||!An.includes(r.id)&&r.id!==R.Void){let e=await Vn(this.reader,t,An,Math.min(this.currentSegment.elementEndPos??1/0,t+Jn));if(e){n=e;continue}else break}let{id:i,size:a}=r,o=e.filePos,s=qn.findIndex(e=>e.id===i);if(s!==-1){let e=qn[s].flag;this.currentSegment[e]=!0,Hn(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===R.Tags||i===R.Attachments){i===R.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Hn(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===R.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=qn.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=B(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Hn(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=B(i);t(o);let s=o.id;t(s===R.Cluster);let c=o.size,l=i.filePos;c===void 0&&(c=(await Bn(this.reader,l,jn,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,jn));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!==Wn.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===Wn.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===Wn.None)continue;i.decoded||=(i.data=this.decodeBlockData(n,i.data),!0);let a=ma.tempFromBytes(i.data),o=[],s=Y(a)+1;switch(i.lacing){case Wn.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){let n=Y(a);if(t+=n,n<255){o.push(t),e+=t;break}}}o.push(a.length-(a.bufferPos+e))}break;case Wn.FixedSize:{let e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)o.push(t)}break;case Wn.Ebml:{let e=Nn(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=Nn(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=J(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:Wn.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(let n of e.seekEntries){if(!(n.id===R.Tags&&!e.tagsSeen)&&!(n.id===R.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=B(r);if(!i||i.id!==n.id)continue;let{size:a}=i;Hn(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===R.Tags?e.tagsSeen=!0:n.id===R.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=B(e);if(!i||r&&r.includes(i.id))return!1;let{id:a,size:o}=i,s=e.filePos;switch(Hn(o),a){case R.DocType:this.isWebM=Ln(e,o)===`webm`;break;case R.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 R.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=z(e,o)}break;case R.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=z(e,o)}break;case R.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=z(e,o),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case R.Duration:if(!this.currentSegment)break;this.currentSegment.duration=zn(e,o);break;case R.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...O,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!==Gn.Block||e.data.algorithm!==Kn.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===V.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===V.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===V.vp8)this.currentTrack.info.codec=`vp8`;else if(t===V.vp9)this.currentTrack.info.codec=`vp9`;else if(t===V.av1)this.currentTrack.info.codec=`av1`;else if(t===V.prores){let e=this.currentTrack.codecPrivate?c.decode(this.currentTrack.codecPrivate):``;Ge.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new Zn(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===V.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===V.mp3?this.currentTrack.info.codec=`mp3`:t===V.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Je):t===V.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===V.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===V.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===V.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 Qn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case R.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=z(e,o);break;case R.TrackType:{if(!this.currentTrack)break;let t=z(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 R.FlagEnabled:if(!this.currentTrack)break;z(e,o)||(this.currentTrack=null);break;case R.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!z(e,o);break;case R.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!z(e,o);break;case R.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!z(e,o);break;case R.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!z(e,o);break;case R.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!z(e,o);break;case R.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!z(e,o);break;case R.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ln(e,o);break;case R.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=J(e,o);break;case R.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=z(e,o);break;case R.Name:if(!this.currentTrack)break;this.currentTrack.name=Rn(e,o);break;case R.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ln(e,o),pe(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case R.LanguageBCP47:{if(!this.currentTrack)break;let t=Ln(e,o).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case R.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case R.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=z(e,o);break;case R.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=z(e,o);break;case R.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=z(e,o);break;case R.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=z(e,o);break;case R.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=z(e,o);break;case R.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=z(e,o)===1;break;case R.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,o));break;case R.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=h[z(e,o)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case R.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=z(e,o)===2;break;case R.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=p[z(e,o)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case R.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=d[z(e,o)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case R.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case R.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-zn(e,o);try{this.currentTrack.info.rotation=n(t)}catch{}}break;case R.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(s,o));break;case R.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=zn(e,o);break;case R.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=z(e,o);break;case R.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=z(e,o);break;case R.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,o)),this.currentCueTime=null;break;case R.CueTime:this.currentCueTime=z(e,o);break;case R.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 R.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=z(e,o)}break;case R.CueClusterPosition:{let n=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!n)break;t(this.currentSegment),n.clusterPosition=this.currentSegment.dataStartPos+z(e,o)}break;case R.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=z(e,o);break;case R.SimpleBlock:{if(!this.currentCluster)break;let t=Nn(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=_a(e),i=Y(e),a=i>>1&3,c=!!(i&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=J(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 R.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,o)),this.currentBlock=null;break;case R.Block:{if(!this.currentCluster)break;let t=Nn(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=_a(e),i=Y(e)>>1&3,a=J(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 R.BlockAdditions:this.readContiguousElements(e.slice(s,o));break;case R.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 R.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=J(e,o);break;case R.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=z(e,o);break;case R.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=z(e,o);break;case R.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case R.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,o));break;case R.Targets:this.readContiguousElements(e.slice(s,o));break;case R.TargetTypeValue:z(e,o)!==50&&(this.currentTagTargetIsMovie=!1);break;case R.TagTrackUID:case R.TagEditionUID:case R.TagChapterUID:case R.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case R.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,o));break;case R.TagName:this.currentSimpleTagName=Rn(e,o);break;case R.TagString:{if(!this.currentSimpleTagName)break;let t=Rn(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case R.TagBinary:{if(!this.currentSimpleTagName)break;let t=J(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case R.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 Ie(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 R.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Pn(e,o);break;case R.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Rn(e,o);break;case R.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ln(e,o);break;case R.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=J(e,o);break;case R.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Rn(e,o);break;case R.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,o)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case R.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Gn.Block,data:null},this.readContiguousElements(e.slice(s,o)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case R.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=z(e,o);break;case R.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=z(e,o);break;case R.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:Kn.Zlib,settings:null},this.readContiguousElements(e.slice(s,o));break;case R.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=z(e,o);break;case R.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=J(e,o);break;case R.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 Kn.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}}},Xn=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 se(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=E(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=B(e);if(!d||!An.includes(d.id)&&d.id!==R.Void){let e=await Vn(o.reader,r,An,Math.min(s.elementEndPos??1/0,r+Jn));if(e){g=e;continue}else break}let f=d.id,p=d.size,m=e.filePos;if(f===R.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!==R.Cluster),p=(await Bn(o.reader,m,jn,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(Fn(e)===R.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}},Zn=class extends Xn{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:Ke({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?mt(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?xt(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?At(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?Mt(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}},Qn=class extends Xn{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:qe({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 $n=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=rt(Z(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&&ot(n.header.channel)===ot(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 er=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 tr(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=Na(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await $n(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=nt(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let t=Z(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(J(t,12)),n=e.getUint32(0,!1);this.xingData={frameCount:n&at.FrameCount?e.getUint32(4,!1):null,fileSize:n&at.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=Na(t);if(!r)break;n=!0;let i=this.reader.requestSlice(t.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;Pa(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),$(e,3)===`TAG`&&ja(e,this.metadataTags)}return this.metadataTags}finally{e()}}},tr=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=tt(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),ot(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...O}}async getDecoderConfig(){return t(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:ot(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=J(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 nr=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;nr[e]=t>>>0&4294967295}let rr=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^nr[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},ir=(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<<de(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=Ft(e).durationInSamples);return{durationInSamples:i,vorbisBlockSize:a}},ar=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},or=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(ya(e)!==1399285583)return null;e.skip(1);let n=Y(e),r=wa(e),i=ya(e),a=ya(e),o=ya(e),s=Y(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=Y(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}},sr=(e,t)=>{for(;e.filePos<t-3;){let t=ya(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 cr=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=or(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 lr(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:It(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=Nt(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Je,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=J(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=or(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=or(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(),ar({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}},lr=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`?Je: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{...O,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}=ir(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=se(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),!sr(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=or(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=rr(J(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=or(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=dr(u,l,d);t(e);let n=ur(u,e.page,e.segmentIndex);n&&(l=n.page,d=n.segmentIndex)}else for(;;){let e=dr(u,l,d);if(!e)break;let t=ur(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=se(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 ur=(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=T(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}},dr=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=T(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 H;(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`})(H||={});var fr=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=$(e,4),r=n!==`RIFX`,i=n===`RF64`,a=va(e,r),o=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if($(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=$(e,4),n=va(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=Sa(e,r);c=Sa(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 mr(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=ha(r,n),a=ha(r,n),o=va(r,n);r.skip(4);let s=ha(r,n),c;if(c=t===14?8:ha(r,n),t>=18&&i!==357){let e=ha(r,n),a=t-18;if(Math.min(a,e)>=22&&i===H.EXTENSIBLE){r.skip(6);let e=J(r,16);i=e[0]|e[1]<<8}}if((i===H.MULAW||i===H.ALAW)&&(c=8),i!==H.PCM&&i!==H.IEEE_FLOAT&&i!==H.ALAW&&i!==H.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===H.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===H.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=$(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=$(r,4),t=va(r,n),i=J(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=Na(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&Pa(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(t(this.audioInfo),this.audioInfo.format===H.MULAW)return`ulaw`;if(this.audioInfo.format===H.ALAW)return`alaw`;if(this.audioInfo.format===H.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===H.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 pr=2048;var mr=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{...O}}async getPacketAtIndex(e,n){t(e>=0),t(this.demuxer.audioInfo);let r=e*pr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let i=Math.min(pr*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=J(e,i)}let o=e*pr/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/pr,(this.demuxer.dataSize-1)/(pr*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/pr);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 hr=e=>{let t=e.filePos,n=new k(J(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}},gr=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 _r=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 vr(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=Na(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=hr(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=Le[n.samplingFrequencyIndex];t(r!==void 0);let i=gr/r,a={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:n.startPos,dataSize:n.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=gr,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=Na(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;Pa(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},vr=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/gr}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=Re[this.demuxer.firstFrameHeader.channelConfiguration];return t(e!==void 0),e}getSampleRate(){t(this.demuxer.firstFrameHeader);let e=Le[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return t(e!==void 0),e}getDisposition(){return{...O}}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=J(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 yr=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,br=(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}},xr=e=>{let t=0,n=new k(J(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new k(J(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)},Sr=(e,n)=>{if(n===`uncommon-u16`)return X(e)+1;if(n===`uncommon-u8`)return Y(e)+1;if(typeof n==`number`)return n;re(n),t(!1)},Cr=(e,t)=>t===`uncommon-u16`?X(e):t===`uncommon-u16-10`?X(e)*10:t===`uncommon-u8`?Y(e):typeof t==`number`?t:null,wr=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 Tr=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=Na(n);if(!r)break;let i=this.reader.requestSlice(n.filePos,r.size);i instanceof Promise&&(i=await i),t(i),Pa(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=Y(n),i=ga(n),a=(r&128)!=0;switch(r&127){case Rt.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=J(n,34),a=new k(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 Er(this);break}case Rt.VORBIS_COMMENT:{let n=this.reader.requestSlice(e,i);n instanceof Promise&&(n=await n),t(n),zt(J(n,i),this.metadataTags);break}case Rt.PICTURE:{let n=this.reader.requestSlice(e,i);n instanceof Promise&&(n=await n),t(n);let r=Z(n),a=Z(n),o=c.decode(J(n,a)),s=Z(n),l=c.decode(J(n,s));n.skip(16);let u=Z(n),d=J(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(Y(o)===255){let t=o.filePos;if(Y(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 k(J(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=yr(i.readBits(4));if(!a)return null;t(this.audioInfo);let o=br(i.readBits(4),this.audioInfo.sampleRate);if(!o||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let s=xr(e),c=Sr(e,a),l=Cr(e,o);if(l===null||l!==this.audioInfo.sampleRate)return null;let u=e.filePos-r,d=Y(e);return e.skip(-u),e.skip(-1),d===wr(J(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}}},Er=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{...O}}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=J(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 Dr=9e4,Or=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},kr=`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.`,Ar=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 jr=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=J(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 k(n.payload),t=e.readAlignedByte();e.skipBits(8*t),s=e.readBits(8)===2}if(n.pid===0&&!a){let e=new k(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 k(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:Ar.has(t)||(D._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Ar.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=Nr(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 Rr(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=mt(i.suppliedPacket.data),!e.info.avcCodecInfo)continue;let n=e.info.avcCodecInfo.sequenceParameterSets[0];t(n);let r=gt(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=xt(i.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let n=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===j.SPS_NUT).nalUnits[0];t(n);let r=bt(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:Ke({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=hr(ma.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=Re[t.channelConfiguration],e.info.sampleRate=Le[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=rt(Z(ma.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=ot(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=Vt(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=Bt[t.acmod]+t.lfeon,e.info.sampleRate=st[t.fscod]}else if(e.info.codec===`eac3`){let t=Wt(i.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=Kt(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=qt(t),e.info.sampleRate=n}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:qe({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 Fr(e)):this.trackBackingEntries.push(new Ir(e))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),Or(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(Y(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=X(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=Y(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=J(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 Mr=(e,t)=>{if(e.payload.byteLength<3)return null;let n=new k(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(kr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:a,randomAccessIndicator:e.randomAccessIndicator}},Nr=(e,n)=>{t(e.endPos!==null);let r=Mr(e,n);if(!r)return null;let i=new k(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 Pr=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{...O,primary:!1}}getTimeResolution(){return Dr}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/Dr,Math.max(t/Dr,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let n=this.elementaryStream.firstSection;t(n);let r=Nr(n,!0);t(r);let i=new Rr(this.elementaryStream,r),a=new zr(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=Nr(a,!0);t(o);let s=new Rr(this.elementaryStream,o);r=new zr(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=se(e*Dr),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=Mr(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=Mr(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=ue(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=ue(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=Nr(s,!0);t(c);let l=new Rr(this.elementaryStream,c),u=new zr(this,l);for(;!((r(u.presentationOrderPackets)?.pts??-1/0)>=a||!await u.readNextPacket()););let d=E(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=Mr(t,!1);if(e&&e.pts!==null){if(e.pts>a)break outer;_=e,Lr(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=Mr(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=Nr(h,!0);t(n);let r=new Rr(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=Mr(t,!1);if(e&&e.pts!==null){m=e,h=t,Lr(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=Mr(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(ue(e-f.sectionStartPos-c,o.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}},Fr=class extends Pr{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}},Ir=class extends Pr{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 Lr=(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 Rr=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=Nr(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=ft(y),x=b===A.NON_IDR_SLICE||b===A.SLICE_DPA||b===A.IDR,S=b===A.SEI||b===A.SPS||b===A.PPS||b===A.AUD;else{if(b=yt(y),((y&1)<<5|l[_+1]>>3)>0){d+=h;continue}x=b<=j.RASL_R||b>=j.BLA_W_LP&&b<=21,S=b>=j.VPS_NUT&&b<=37||b===j.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 k(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=hr(ma.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(gr*Dr/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=rt(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*Dr/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=Ht[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*Dr/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=Ut[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*Dr/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(kr);i=r.pts,Lr(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=Lt(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}},zr=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 Br=`application/vnd.apple.mpegurl`,Vr=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`);var Hr=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)}},Ur=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=ke(e,e=>e.getType()===`video`)+1;e.push(new Gr(this,t,n))}else if(t.type===`audio`){let n=ke(e,e=>e.getType()===`audio`)+1;e.push(new Kr(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=ke(e,e=>e.getType()===`video`)+1;e.push(new Gr(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=ke(e,e=>e.getType()===`audio`)+1;e.push(new Kr(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}},Wr=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:le(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}},Gr=class extends Wr{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())}},Kr=class extends Wr{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={}}))(),Ee();let qr=1/0;typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});var U=class extends Ne{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 K;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,qr),e=this._getFileSize(),t(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new K;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 ri(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Jr(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Jr=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()}},Yr=class extends U{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 U||e instanceof Jr))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof U?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(n):n(t)}};let Xr=(e,t)=>e.path===t.path;var Zr=class extends Yr{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 U?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())}},Qr=class extends U{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&&(!De(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 ni({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ti.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)&&!_e()&&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 $r=.5*2**20;var ei=class extends U{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&&(!De(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 ti={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(Ce(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+$r),{start:e,end:t}}};var ni=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(Ce(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||Ce(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}},ri=class extends U{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:oe(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()}},ii=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},ai=(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 oi=/^0[xX][0-9a-fA-F]+$/,si=/^data:.*;base64,/i;var ci=class extends Ur{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 Me(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=ii(n,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=await new pa(r.source).requestEntireFile();t(i),e=Da(i,i.length,{ignore:Vr}),r.source instanceof Yr&&(this.rootPath=r.source.rootPath)}catch(e){n.error=e,n.hasError=!0}finally{ai(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:Oe(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 Hr(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:Oe(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 Hr(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(!oi.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:Oe(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(si.test(n)){let e=n.indexOf(`,`),t=we(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=Yt(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=>Xt(e,r))&&(t=[...t,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:t})})}},o=new da({source:new Zr(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 ei(dn(new pa(o.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new pa(ii(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:J(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{ai(t)}},()=>{o.free()})).ref()}else t(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof Di)),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=Ae(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}},li=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 Yr);let e=await this.input._reader.requestEntireFile();t(e);let n=Da(e,e.length,{ignore:Vr}),{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=Oe(r,o),c=new Hr(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 Hr(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=Oe(r,a);i.push({fullPath:o,attributes:n,lineNumber:e,hasOnlyKeyPackets:!0})}else if(t.startsWith(`#EXT-X-MEDIA:`)){let n=new Hr(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=Oe(r,o)),a.push({fullPath:i,attributes:n,lineNumber:e})}else if(t!==`#EXT-X-I-FRAMES-ONLY`&&t.startsWith(`#EXTINF:`)){let e=new ci(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=>Be.includes(Ze(e))),p=l.some(e=>He.includes(Ze(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=Oe(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=Oe(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=Ze(t);if(r!==null){if(Be.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:pi(t.attributes),autoselect:pi(t.attributes)||mi(t.attributes),languageCode:hi(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(He.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:pi(t.attributes),autoselect:pi(t.attributes)||mi(t.attributes),languageCode:hi(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 di(e)):this.trackBackings.push(new fi(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 ci(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Br}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},ui=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 di){for(let e of r)if(await e.getCodec()===this.getCodec()){n=e;break}}else{t(this instanceof fi);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{...O,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)}},di=class extends ui{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return Ze(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}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()}},fi=class extends ui{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return Ze(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 pi=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}".`)},mi=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}".`)},hi=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 W=class{constructor(){this._isIsobmff=!1}},gi=class extends W{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=$(t,4);return n!==`ftyp`&&n!==`styp`?null:$(t,4)}_createDemuxer(e){return new fn(e)}},_i=class extends gi{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=$(n,4);return r===`moof`||r===`sidx`}get name(){return`MP4`}get mimeType(){return`video/mp4`}},vi=class extends gi{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},yi=class extends W{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Mn(n);if(r===null||r<1||r>8||z(n,r)!==R.EBML)return!1;let i=In(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=B(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case R.EBMLVersion:if(z(a,r)!==1)return!1;break;case R.EBMLReadVersion:if(z(a,r)!==1)return!1;break;case R.DocType:if(Ln(a,r)!==t)return!1;break;case R.DocTypeVersion:if(z(a,r)>4)return!1;break}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new Yn(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},bi=class extends yi{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},xi=class extends W{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=Na(n);if(!r)break;t=n.filePos+r.size}let n=await $n(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=nt(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=Z(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await $n(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 er(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},Si=class extends W{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=$(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),$(t,4)===`WAVE`)}_createDemuxer(e){return new fr(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},Ci=class extends W{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?$(t,4)===`OggS`:!1}_createDemuxer(e){return new cr(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},wi=class extends W{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=Na(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSlice(t,4);return n instanceof Promise&&(n=await n),n?$(n,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new Tr(e)}},Ti=class extends W{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=Na(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=hr(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=hr(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new _r(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},Ei=class extends W{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=J(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 jr(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Di=class extends W{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||$(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof Yr))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 li(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return Br}};let Oi=[new Di,new _i,new vi,new yi,new bi,new Si,new Ci,new wi,new xi,new Ti,new Ei],ki=(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
+ ;Ee();let Ai=-1/0,ji=-1/0,Mi=null;typeof FinalizationRegistry<`u`&&(Mi=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-Ai>=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.`),Ai=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-ji>=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.`),ji=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));let Ni=new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]);var Pi=class{constructor(){this._referenceCount=0}},Fi=class e{get microsecondTimestamp(){return Math.trunc(me*this.timestamp)}get microsecondDuration(){return Math.trunc(me*this.duration)}constructor(e){if(this._closed=!1,Bi(e)){if(e.format===null)throw TypeError(`AudioData with null format is not supported.`);this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Pi){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Ni.has(this.format))throw TypeError(`getFormat() must return an AudioSampleFormat.`);if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError(`getSampleRate() must return a positive integer.`);if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError(`getNumberOfFrames() must return a non-negative integer.`);if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError(`getNumberOfChannels() must return a positive integer.`);if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError(`getTimestamp() must return a finite number.`);this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!Ni.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(Ii(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw TypeError(`Invalid AudioDataInit: data size is not a multiple of frame size.`);this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*Ii(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}Mi?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!Ni.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=Ii(t),a=Li(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!g(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(t.format!==void 0&&!Ni.has(t.format))throw TypeError(`Invalid format.`);if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{format:n,frameCount:r,frameOffset:i}=t,{planeIndex:a}=t,o=this.format,c=n??this.format;if(!c)throw Error(`Destination format not determined`);let l=this.numberOfFrames,u=this.numberOfChannels,d=i??0;if(d>=l)throw RangeError(`frameOffset out of range`);let f=r===void 0?l-d:r;if(f>l-d)throw RangeError(`frameCount out of range`);let p=Ii(c),m=Li(c);if(m&&a>=u||!m&&a!==0)throw RangeError(`planeIndex out of range`);let h=(m?f:f*u)*p;if(e.byteLength<h)throw RangeError(`Destination buffer is too small`);let _=s(e),v=zi(c);if(Bi(this._data))_e()&&u>2&&c!==o?Vi(this._data,_,o,c,u,a,d,f):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});else{let e=Ri(o),t=Ii(o),n=Li(o),r;if(this._data instanceof Pi){let e=e=>{let r=this._data.getDataPlane(e);if(!(r instanceof Uint8Array))throw TypeError(`getDataPlane() must return a Uint8Array.`);let i=l*t*(n?1:u);if(r.byteLength!==i)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${r.byteLength} bytes.`);return r};if(n)if(m)r=e(a),a=0;else{r=new Uint8Array(l*t*u);for(let n=0;n<u;n++){let i=e(n);r.set(i,n*l*t)}}else r=e(0)}else r=this._data;let i=s(r);for(let r=0;r<f;r++)if(m){let o=r*p,s;s=n?(a*l+(r+d))*t:((r+d)*u+a)*t,v(_,o,e(i,s))}else for(let a=0;a<u;a++){let o=(r*u+a)*p,s;s=n?(a*l+(r+d))*t:((r+d)*u+a)*t,v(_,o,e(i,s))}}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(this._data instanceof Pi){let t=new e(this._data);return t.setTimestamp(this.timestamp),t}else if(Bi(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(t,n=this.numberOfFrames){if(!Number.isInteger(t)||t<0)throw TypeError(`startSample must be a non-negative integer.`);if(!Number.isInteger(n)||n<0)throw TypeError(`endSample must be a non-negative integer.`);if(t>this.numberOfFrames)throw RangeError(`startSample out of range.`);if(n>this.numberOfFrames)throw RangeError(`endSample out of range.`);if(n<t)throw RangeError(`endSample must not be less than startSample.`);if(this._closed)throw Error(`AudioSample is closed.`);let r=n-t,i=Ii(this.format),a;if(Li(this.format)){let e=r*i;if(a=new Uint8Array(e*this.numberOfChannels),r>0)for(let n=0;n<this.numberOfChannels;n++)this.copyTo(a.subarray(n*e,(n+1)*e),{planeIndex:n,format:this.format,frameOffset:t,frameCount:r})}else a=new Uint8Array(r*this.numberOfChannels*i),r>0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new e({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate})}close(){this._closed||=(Mi?.unregister(this),this._data instanceof Pi?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Bi(this._data)?this._data.close():this._data=new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);return this._data instanceof Pi?this._createAudioDataFromData():Bi(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Li(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw Error(`AudioSample is closed.`);let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:`f32-planar`})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u});l.push(d),s+=a,c-=a}return l}};let Ii=e=>{switch(e){case`u8`:case`u8-planar`:return 1;case`s16`:case`s16-planar`:return 2;case`s32`:case`s32-planar`:return 4;case`f32`:case`f32-planar`:return 4;default:throw Error(`Unknown AudioSampleFormat`)}},Li=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},Ri=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t)=>(e.getUint8(t)-128)/128;case`s16`:case`s16-planar`:return(e,t)=>e.getInt16(t,!0)/32768;case`s32`:case`s32-planar`:return(e,t)=>e.getInt32(t,!0)/2147483648;case`f32`:case`f32-planar`:return(e,t)=>e.getFloat32(t,!0)}},zi=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,oe((n+1)*127.5,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,oe(Math.round(n*32767),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,oe(Math.round(n*2147483647),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},Bi=e=>typeof AudioData<`u`&&e instanceof AudioData,Vi=(e,t,n,r,i,a,o,c)=>{let l=Ri(n),u=zi(r),d=Ii(n),f=Ii(r),p=Li(n);if(Li(r))if(p){let r=new ArrayBuffer(c*d),i=s(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:c,format:n});for(let e=0;e<c;e++){let n=e*d;u(t,e*f,l(i,n))}}else{let r=new ArrayBuffer(c*i*d),p=s(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:c,format:n});for(let e=0;e<c;e++){let n=(e*i+a)*d;u(t,e*f,l(p,n))}}else if(p){let r=c*d,a=new ArrayBuffer(r),p=s(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:c,format:n});for(let e=0;e<c;e++){let n=e*d;u(t,(e*i+r)*f,l(p,n))}}}else{let r=new ArrayBuffer(c*i*d),a=s(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:c,format:n});for(let e=0;e<c;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*d;u(t,r*f,l(a,o))}}},Hi=[],Ui=[],Wi=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
+ let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return t===0?i:-i},Gi=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,t===0?i:-i},Ki=e=>{
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
+ 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.`)},qi=e=>{if(!De(e))throw TypeError(`timestamp must be a number.`)},Ji=(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 Yi=class{constructor(e){if(!(e instanceof na))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(Ki(e),this._track.input._disposed)throw new K;return Ji(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Ki(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(qi(e),Ki(t),this._track.input._disposed)throw new K;return Ji(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(Ki(t),this._track.input._disposed)throw new K;return Ji(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,n={}){if(qi(e),Ki(n),this._track.input._disposed)throw new K;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(Ki(n),this._track.input._disposed)throw new K;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(Ki(n),this._track.input._disposed)throw new K;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 K;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}}}},Xi=class{constructor(e,t){this.onSample=e,this.onError=t}},Zi=class{mediaSamplesInRange(e=-1/0,t=1/0,n){qi(e),qi(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=Qi(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 K;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){ne(e);let r=te(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=Qi(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(qi(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 K;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 Qi=e=>e===0?40:8;var $i=class extends Xi{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new he,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let i=t=>{let n=t.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-n),n+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(n-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=n);let i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let a=r.sampleRate;t.setTimestamp(Math.round(i*a)/a),e(t)},a=Ui.find(e=>e.supports(n,r));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Fi))throw TypeError(`The argument passed to onSample must be an AudioSample.`);i(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=Error(`Decoding error`).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new Fi(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(t(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(t(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(t(this.decoder),this.decoder.close())}},ea=class extends Xi{constructor(e,n,r){super(e,n),this.decoderConfig=r,this.currentTimestamp=null,t(Ve.includes(r.codec)),this.codec=r.codec;let{dataType:i,sampleSize:a,littleEndian:o}=Xe(this.codec);switch(this.inputSampleSize=a,a){case 1:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-2**7:i===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):i===`ulaw`?this.readInputValue=(e,t)=>Wi(e.getUint8(t)):i===`alaw`?this.readInputValue=(e,t)=>Gi(e.getUint8(t)):t(!1);break;case 2:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,o)-2**15:i===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,o):t(!1);break;case 3:i===`unsigned`?this.readInputValue=(e,t)=>ie(e,t,o)-2**23:i===`signed`?this.readInputValue=(e,t)=>ae(e,t,o):t(!1);break;case 4:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,o)-2**31:i===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,o):i===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,o):t(!1);break;case 8:i===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,o):t(!1);break;default:re(a),t(!1)}switch(a){case 1:i===`ulaw`||i===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,i===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:re(a),t(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=s(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let c=this.currentTimestamp;this.currentTimestamp+=o;let l=new Fi({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}},ta=class extends Zi{constructor(e){if(!(e instanceof aa))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,n){if(!await this._track.canDecode())throw Error(`This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getDecoderConfig();return t(r&&i),Ve.includes(i.codec)?new ea(e,n,i):new $i(e,n,r,i)}_createPacketSink(){return new Yi(this._track)}async getSample(e,t={}){qi(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)}},na=class e{constructor(e,t){
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
+ this.input=e,this._backing=t}isVideoTrack(){return this instanceof ia}isAudioTrack(){return this instanceof aa}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return G(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return G(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return G(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return G(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 G(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 le((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 Yi(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&&=ra(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&&=ra(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=ra(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}};let G=(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},ra=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 ia=class extends na{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 G(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 G(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return G(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getRotation(){return this._backing.getRotation()}get rotation(){return G(this._backing.getRotation(),`rotation`,`getRotation`)}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return G(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return G(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=je({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=je({num:G(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*G(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:G(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*G(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=G(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}let t=G(this._backing.getRotation(),`displayWidth`,`getDisplayWidth`)%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return G(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=G(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}let t=G(this._backing.getRotation(),`displayHeight`,`getDisplayHeight`)%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return G(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),Hi.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),Lt(n,r,e.data)}},aa=class extends na{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return G(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return G(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return G(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),Ui.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 oa=e=>-(e??-1/0),sa=e=>-e,ca=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}),ua=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)};
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
+ Ee();var da=class e extends Ne{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 W)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof U||t.source instanceof Jr))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof U&&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&&ki(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},t.source instanceof U?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 Yr);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&&Xr(t.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());let i=this._sourceCachePromises.find(t=>t.cacheGroup===n&&Xr(t.request,e));if(i)return i.promise.then(e=>e.sourceRef.source.ref());let a=(async()=>{let r=await this._getSourceUncached(e);if(ke(this._sourceCache,e=>e.cacheGroup===n&&e.sourceRef.source._refCount===1)>=4){let e=Ae(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(),ee(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 pa(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 fa})()}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 fa)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&&=ca(e),ua((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=ca(e),ua((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=ca(e),ua((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=ca(e);let t=la(e,{sortBy:async e=>[sa((await e.getDisposition()).default),sa(await e.hasPairableAudioTrack()),sa(!await e.hasOnlyKeyPackets()),oa(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=ca(e);let t=await this.getPrimaryVideoTrack(),n=la(e,{sortBy:async e=>[sa(!t||e.canBePairedWith(t)),sa((await e.getDisposition()).default),oa(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 ia(this,e):new aa(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()}},fa=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},K=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},pa=class{constructor(e){
337
+ /*!
338
+ * Copyright (c) 2026-present, Vanilagy and contributors
339
+ *
340
+ * This Source Code Form is subject to the terms of the Mozilla Public
341
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
342
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
343
+ */
344
+ 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 K;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=new Uint8Array;return new ma(t,s(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,qr);return r instanceof Promise?r.then(t=>t?new ma(t.bytes,t.view,t.offset,e,n):null):r?new ma(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,n,r){if(this.source._disposed)throw new K;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,oe(this.fileSizeNonStrict-e,n,r));{let i=this.requestSlice(e,r),a=i=>i||(t(this.fileSizeNonStrict!==null),this.requestSlice(e,oe(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=J(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 ma(n,s(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},ma=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 q=(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.`)},J=(e,t)=>{q(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},Y=e=>(q(e,1),e.view.getUint8(e.bufferPos++)),ha=(e,t)=>{q(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},X=e=>{q(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},ga=e=>{q(e,3);let t=ie(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},_a=e=>{q(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},va=(e,t)=>{q(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Z=e=>{q(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},ya=e=>{q(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},ba=e=>{q(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},xa=e=>{q(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},Sa=(e,t)=>{let n,r;return t?(n=va(e,!0),r=va(e,!0)):(r=va(e,!1),n=va(e,!1)),r*4294967296+n},Q=e=>{let t=Z(e),n=Z(e);return t*4294967296+n},Ca=e=>{let t=ba(e),n=Z(e);return t*4294967296+n},wa=e=>{let t=ya(e);return xa(e)*4294967296+t},Ta=e=>{q(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Ea=e=>{q(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},$=(e,t)=>{q(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Da=(e,t,n)=>c.decode(J(e,t)).split(`
345
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e));
346
+ /*!
347
+ * Copyright (c) 2026-present, Vanilagy and contributors
348
+ *
349
+ * This Source Code Form is subject to the terms of the Mozilla Public
350
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
351
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
352
+ */
353
+ var Oa;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Oa||={});var ka;(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`})(ka||={});let Aa=`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(`.`),ja=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=J(e,125),e.filePos=n;let r=Ma(e,30);r&&(t.title??=r);let i=Ma(e,30);i&&(t.artist??=i);let a=Ma(e,30);a&&(t.album??=a);let o=Ma(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=J(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Ma(e,28),e.skip(2)}else e.skip(-30),l=Ma(e,30);l&&(t.comment??=l);let u=Y(e);u<Aa.length&&(t.genre??=Aa[u])},Ma=(e,t)=>{let n=J(e,t),r=Se(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()},Na=e=>{let t=e.filePos,n=$(e,3),r=Y(e),i=Y(e),a=Y(e),o=Z(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=it(o);return a&Oa.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},Pa=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){D._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new Fa(t,J(e,t.flags&Oa.Footer?t.size-10:t.size));if(t.flags&Oa.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&Oa.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&Oa.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(Aa[e]!==void 0){n.genre??=Aa[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(Aa[e]!==void 0){n.genre??=Aa[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 Fa=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?it(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:it(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 ka.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 ka.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=Se(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=Se(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=Se(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),c.decode(r.subarray(0,e))}case ka.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=Se(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 ka.UTF_8:{let e=Se(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 Ia=1e6,La=(e,t)=>{if(!Number.isFinite(e))throw TypeError(`${t} 必须是有限数字`);if(e<0)throw RangeError(`${t} 不能为负数`)},Ra=e=>Number.isSafeInteger(e)&&e>=0,za=e=>{La(e,`timeUs`);let t=Math.round(e);if(!Number.isSafeInteger(t))throw RangeError(`timeUs 超出安全整数范围`);return t},Ba=e=>(La(e,`seconds`),za(e*Ia)),Va=(e,t,n)=>{if(e.length===0||!Ra(t)||t===0||n.numberOfChannels<=0||n.numberOfFrames<=0||n.sampleRate<=0)return;let r={format:`f32-planar`,planeIndex:0},i=new Float32Array(n.allocationSize(r)/Float32Array.BYTES_PER_ELEMENT);for(let a=0;a<n.numberOfChannels;a+=1){n.copyTo(i,{...r,planeIndex:a});for(let r=0;r<n.numberOfFrames;r+=1){let a=Math.round((n.timestamp+r/n.sampleRate)*Ia);if(a<0||a>=t)continue;let o=Math.floor(a/t*e.length),s=i[r]??0,c=Number.isFinite(s)?Math.abs(s):0;c>(e[o]??0)&&(e[o]=c)}}},Ha=e=>{let t=0;for(let n of e)t=Math.max(t,n);if(t===0)return e;for(let n=0;n<e.length;n+=1)e[n]=(e[n]??0)/t;return e},Ua=e=>typeof e==`object`&&!!e,Wa=e=>typeof e==`number`&&Number.isFinite(e)&&Number.isInteger(e)&&e>=0,Ga=e=>Wa(e)&&e<=16384,Ka=e=>!Ua(e)||!Wa(e.requestId)?!1:e.type===`cancel`||e.type===`extract`&&e.blob instanceof Blob&&Ga(e.sampleCount),qa=new Set,Ja=new Map,Ya=new Set,Xa=Promise.resolve(),Za=(e,t)=>{self.postMessage(e,t??[])},Qa=(e,t)=>t instanceof fa?{code:`invalid-media`,message:`Mediabunny 无法解析该音频容器`,requestId:e,type:`error`}:{code:`decode`,message:t instanceof Error?`Mediabunny 音频解码失败:${t.message}`:`Mediabunny 音频解码失败`,requestId:e,type:`error`},$a=async e=>{if(Ya.delete(e.requestId),qa.delete(e.requestId))return;let t=new da({formats:Oi,source:new Qr(e.blob)});Ja.set(e.requestId,t);try{if(e.sampleCount===0){let t=new Float32Array;Za({requestId:e.requestId,samples:t,type:`complete`},[t.buffer]);return}let n=await t.getPrimaryAudioTrack();if(!n||!await n.canDecode()){Za({code:`unsupported`,message:`当前浏览器不支持该音频编码格式的 WebCodecs 解码`,requestId:e.requestId,type:`error`});return}let r=await n.computeDuration();if(!Number.isFinite(r)||r<=0)throw Error(`无法读取有效的音频时长`);let i=Ba(r),a=new Float32Array(e.sampleCount),o=new ta(n);for await(let t of o.samples())try{if(qa.has(e.requestId))return;Va(a,i,t)}finally{t.close()}if(qa.has(e.requestId))return;Ha(a),Za({requestId:e.requestId,samples:a,type:`complete`},[a.buffer])}catch(t){if(qa.has(e.requestId)||t instanceof K)return;Za(Qa(e.requestId,t))}finally{Ja.delete(e.requestId),qa.delete(e.requestId),t.dispose()}};self.addEventListener(`message`,e=>{if(!Ka(e.data))return;if(e.data.type===`cancel`){if(!Ya.has(e.data.requestId)&&!Ja.has(e.data.requestId))return;qa.add(e.data.requestId),Ja.get(e.data.requestId)?.dispose();return}let t=e.data;Ya.add(t.requestId),Xa=Xa.then(()=>$a(t),()=>$a(t))})})();