sliccy 6.256.0 → 6.256.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node-server/cloud-status.d.ts +8 -0
- package/dist/node-server/cloud-status.js +38 -0
- package/dist/ui/.vite/manifest.json +183 -183
- package/dist/ui/assets/{account-store-QxWo48Y1.js → account-store-CYXcTNmf.js} +1 -1
- package/dist/ui/assets/{account-store-DRK_jfiB.js → account-store-DLG3Av-u.js} +1 -1
- package/dist/ui/assets/{adobe-BwSa2oAU.js → adobe-DcrhMctx.js} +1 -1
- package/dist/ui/assets/{adobe-XnlO8IOa.js → adobe-OKBElK5I.js} +1 -1
- package/dist/ui/assets/{agent-panels-DLsxOOjW.js → agent-panels-ZG3ebUSL.js} +1 -1
- package/dist/ui/assets/{almost-bash-shell-headless-YXVG1DPI.js → almost-bash-shell-headless-RU8iANoA.js} +15 -15
- package/dist/ui/assets/{apply-layout-BtzT4Jrn.js → apply-layout-qj_IZphr.js} +1 -1
- package/dist/ui/assets/{azure-openai-BiTykqg3.js → azure-openai-DK0alNtF.js} +1 -1
- package/dist/ui/assets/{azure-openai-BH03ks5Y.js → azure-openai-DPYo4Wln.js} +1 -1
- package/dist/ui/assets/{bunny-probe-Bq1N-AVN.js → bunny-probe-DKhPxZeZ.js} +1 -1
- package/dist/ui/assets/{bunny-run-DyJVGqsu.js → bunny-run-DwKL9l6t.js} +1 -1
- package/dist/ui/assets/{cdp-Dm3JXxCN.js → cdp-DSFJzViN.js} +1 -1
- package/dist/ui/assets/{cerebras-Cj-dhgCb.js → cerebras-B9mbkTZf.js} +1 -1
- package/dist/ui/assets/{cerebras-B5dFzZuU.js → cerebras-Cm_8OStE.js} +1 -1
- package/dist/ui/assets/{composer-speech-0uRgiL71.js → composer-speech-CoFdC6Ue.js} +1 -1
- package/dist/ui/assets/{connect-surface-BQgwhG8d.js → connect-surface-BBRi7lly.js} +1 -1
- package/dist/ui/assets/{directed-approval-BxWIFFqA.js → directed-approval-DgdRwugK.js} +1 -1
- package/dist/ui/assets/{emscripten-vfs-hook-C73xuKfz.js → emscripten-vfs-hook-BGmnPBF-.js} +1 -1
- package/dist/ui/assets/{fast-path-hqxZk1HF.js → fast-path-D86NfZfu.js} +1 -1
- package/dist/ui/assets/{frozen-archive-writer-Cr1_j3pp.js → frozen-archive-writer-Dk602Q9A.js} +1 -1
- package/dist/ui/assets/{frozen-session-delete-CpcHR1XS.js → frozen-session-delete-D41KLb1Q.js} +1 -1
- package/dist/ui/assets/{frozen-session-identity-dpueujl9.js → frozen-session-identity-Wawl3rz4.js} +1 -1
- package/dist/ui/assets/{gelatiere-unit-PHQc3WNq.js → gelatiere-unit-NbtPiF37.js} +1 -1
- package/dist/ui/assets/{github-Bj8suNGU.js → github-C_k9XNGJ.js} +1 -1
- package/dist/ui/assets/{github-Dvjydy3P.js → github-D2A7mZDF.js} +1 -1
- package/dist/ui/assets/{github-copilot-CpJKXWfn.js → github-copilot-20yc0eqx.js} +1 -1
- package/dist/ui/assets/{github-copilot-D8DdUlya.js → github-copilot-D-lJD9JM.js} +1 -1
- package/dist/ui/assets/{hear-DDr5S4Od.js → hear-CS8KuGJo.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-CXD4SmqZ.js → js-realm-worker-CvBctwsA.js} +2 -2
- package/dist/ui/assets/{jsh-executor-BFwK2t97.js → jsh-executor-B54XDkz2.js} +3 -3
- package/dist/ui/assets/{kernel-worker-DadD3ayk.js → kernel-worker-DS575H__.js} +9 -9
- package/dist/ui/assets/{lick-ws-bridge-Bq9kUe4V.js → lick-ws-bridge-BBZpW-Dg.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-DMNf8klz.js → lick-ws-bridge-DMRxA0GE.js} +1 -1
- package/dist/ui/assets/{live-session-curation-CSJCW_xQ.js → live-session-curation-ChoGCSOH.js} +1 -1
- package/dist/ui/assets/{live-session-curation-CNk-iYCa.js → live-session-curation-nSX_c9Jb.js} +1 -1
- package/dist/ui/assets/{live-session-snapshot-BedjttIR.js → live-session-snapshot-BQcFx9d7.js} +1 -1
- package/dist/ui/assets/{local-llm-NE-qI2cb.js → local-llm-BdhJYy6M.js} +1 -1
- package/dist/ui/assets/{local-llm-qPIX8NMO.js → local-llm-cy-hboD7.js} +1 -1
- package/dist/ui/assets/{main-DVD6CfWm.js → main-BvTNS5M1.js} +3 -3
- package/dist/ui/assets/{main-cherry-ByF5f6AT.js → main-cherry-CLPxNUOm.js} +1 -1
- package/dist/ui/assets/{mcp-command-n1wIw393.js → mcp-command-Bshk9-8r.js} +10 -10
- package/dist/ui/assets/{memory-curation-seam-CjYHWDBt.js → memory-curation-seam-NFHXE0W5.js} +1 -1
- package/dist/ui/assets/{memory-health-DnbzPxqU.js → memory-health-DpXsg2PB.js} +1 -1
- package/dist/ui/assets/{memory-write-execute-BQg4KGxO.js → memory-write-execute-D4wz6znH.js} +1 -1
- package/dist/ui/assets/{merge-folded-cost-into-frozen-DA0swiNk.js → merge-folded-cost-into-frozen-Ce6e9pCy.js} +1 -1
- package/dist/ui/assets/{new-session-BHvzb7bp.js → new-session-DX7Em69X.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-CqivQ7HA.js → oauth-bootstrap-BIoESN8s.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-C6UC6cTM.js → onboarding-orchestrator-DgsmYqKs.js} +1 -1
- package/dist/ui/assets/{openai-codex-B7A6dTqN.js → openai-codex-2LN44-VU.js} +1 -1
- package/dist/ui/assets/{openai-codex-xtvQmRuH.js → openai-codex-BNDOGlHP.js} +1 -1
- package/dist/ui/assets/{openrouter-CQeyGGEy.js → openrouter-B-qvuFIC.js} +1 -1
- package/dist/ui/assets/{openrouter-_6zsj8-6.js → openrouter-Cbloo6-N.js} +1 -1
- package/dist/ui/assets/{openrouter-free-BM772ovL.js → openrouter-free-CPMEIAmD.js} +1 -1
- package/dist/ui/assets/{openrouter-free-Du1No0Z_.js → openrouter-free-YgWGIS-T.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BSSNY_G1.js → openrouter-oauth-DspK3V7c.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-D9dklyIn.js → openrouter-oauth-d_WhF-i_.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-rMOPHOSf.js → panel-rpc-handlers-CiVSlbYh.js} +2 -2
- package/dist/ui/assets/{panelize-shell-DLm7AfDp.js → panelize-shell-CszEdwrr.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-dq5caQ-R.js → pi-edit-execution-BOt2UG1t.js} +1 -1
- package/dist/ui/assets/{provider-4M0-Za9p.js → provider-Da_Xha6T.js} +1 -1
- package/dist/ui/assets/{provider-C6V5bKb2.js → provider-ic7srMSZ.js} +1 -1
- package/dist/ui/assets/{provider-settings-C46VEmp7.js → provider-settings-DXTVzWZr.js} +1 -1
- package/dist/ui/assets/provider-store-access-C1OIs0Sn.js +1 -0
- package/dist/ui/assets/provider-store-access-C94YO93f.js +1 -0
- package/dist/ui/assets/{providers-B5VMaUWX.js → providers-BwKmSpLH.js} +2 -2
- package/dist/ui/assets/{providers-Bw0birsa.js → providers-DinkpGvr.js} +1 -1
- package/dist/ui/assets/{quick-llm-D5hmdHQQ.js → quick-llm-4ddeV6ZI.js} +1 -1
- package/dist/ui/assets/{realm-inprocess-DsBZtVOH.js → realm-inprocess-gfLwWl-i.js} +2 -2
- package/dist/ui/assets/{realm-unhandled-rejections-BDHLlsLp.js → realm-unhandled-rejections-CkX1BGEd.js} +1 -1
- package/dist/ui/assets/{realm-unhandled-rejections-BDnl84l4.js → realm-unhandled-rejections-iuOFsoIO.js} +1 -1
- package/dist/ui/assets/{remote-terminal-view-DYm18AE3.js → remote-terminal-view-DM_rdDTN.js} +2 -2
- package/dist/ui/assets/{restore-CKcu1P_Z.js → restore-ku3NI9gU.js} +1 -1
- package/dist/ui/assets/{run-Ds-D_Vog.js → run-B9uXGQYv.js} +2 -2
- package/dist/ui/assets/{run-DS9gNHJH.js → run-BHLpn7EO.js} +2 -2
- package/dist/ui/assets/{run-BV4IO7_J.js → run-C9mlrs_A.js} +1 -1
- package/dist/ui/assets/{run-C4x_nui1.js → run-DbR82j2G.js} +2 -2
- package/dist/ui/assets/{run-C1jQodOF.js → run-YyW5Bd1z.js} +1 -1
- package/dist/ui/assets/{run-DYDjMUGP.js → run-kDywGyI_.js} +2 -2
- package/dist/ui/assets/{run-CRGyQPIr.js → run-oiQnjELg.js} +1 -1
- package/dist/ui/assets/{serve-command-Dxu0zqDl.js → serve-command-CYP3K9ID.js} +2 -2
- package/dist/ui/assets/{serve-runtime-CEmOBSkh.js → serve-runtime-CwPc5Ipg.js} +1 -1
- package/dist/ui/assets/{session-command-memory-CZZ78BU8.js → session-command-memory-Bjbktm7f.js} +2 -2
- package/dist/ui/assets/{session-jsonl-kHYH-7Ib.js → session-jsonl-DvM9G2Ke.js} +1 -1
- package/dist/ui/assets/{session-search-index-eJnlwzC6.js → session-search-index-DtkT95V1.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-Ci3nvXGY.js → setup-feature-flags-remote-DVDOwgnm.js} +1 -1
- package/dist/ui/assets/{setup-model-catalog-DWI-pcXH.js → setup-model-catalog-D_3w06PR.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-2lMvXpiU.js → silent-renew-backoff-CAjvUu0c.js} +1 -1
- package/dist/ui/assets/slicc-version-CJuEM6d6.js +1 -0
- package/dist/ui/assets/{soundscape-DK8vzDpK.js → soundscape-BBfqPI7l.js} +1 -1
- package/dist/ui/assets/{speak-D_AKrPu0.js → speak-BZjF8HVW.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-CJGReRLz.js → sprinkle-manager-CZEpPXOO.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-CcWhSBfB.js → sprinkle-renderer-BkwlbHXw.js} +1 -1
- package/dist/ui/assets/{src-DWA1MizA.js → src-BQREyqyX.js} +63 -63
- package/dist/ui/assets/{ssh-CAQr291h.js → ssh-COAG0Prl.js} +1 -1
- package/dist/ui/assets/{sudo-CSzJTCd9.js → sudo-wabmuIKV.js} +1 -1
- package/dist/ui/assets/{supervisor-DBofbxjT.js → supervisor-B2nXofh7.js} +1 -1
- package/dist/ui/assets/{sync-dialog-FwBEmm7W.js → sync-dialog-CHmuJIFU.js} +1 -1
- package/dist/ui/assets/{transformers-env-DfuTpXXR.js → transformers-env-CHgjo8-d.js} +1 -1
- package/dist/ui/assets/tray-leader-DG6Rmdd2.js +1 -0
- package/dist/ui/assets/{tray-leave-runtime-BoVSKaCt.js → tray-leave-runtime-CHqFireQ.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-CYuPitKs.js → tray-sidecar-DM4mHGds.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-B8TZhKUa.js → upgrade-detection-XwHj-EZO.js} +1 -1
- package/dist/ui/assets/{upgrade-to-seven-B2H6KnlF.js → upgrade-to-seven-DnMOrCDQ.js} +1 -1
- package/dist/ui/assets/{voice-reply-BKaB8Asb.js → voice-reply-DJEUbUbb.js} +1 -1
- package/dist/ui/assets/{wc-attach-CoR9zN1R.js → wc-attach-Blm4ssVC.js} +2 -2
- package/dist/ui/assets/{wc-browser-D2k3tkR-.js → wc-browser-DzD5njrA.js} +1 -1
- package/dist/ui/assets/{wc-computers-CPX2x6Th.js → wc-computers-BDapcAz_.js} +1 -1
- package/dist/ui/assets/{wc-detached-BHiC5h-Y.js → wc-detached-6AHVMP_P.js} +1 -1
- package/dist/ui/assets/{wc-extension-DnJc8F1P.js → wc-extension-Hao4ySoS.js} +2 -2
- package/dist/ui/assets/{wc-follower-CpqjednQ.js → wc-follower-CwMgvm3U.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-CjMFLgHd.js → wc-follower-oauth-DDwNrB05.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-B1UhGGlW.js → wc-gelatiere-BAPOL7Z1.js} +1 -1
- package/dist/ui/assets/{wc-live-MMV5wx1F.js → wc-live-Cw6xVOGo.js} +5 -5
- package/dist/ui/assets/{wc-nav-BLmah4u4.js → wc-nav-CMY9ERM1.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-BLjMaifw.js → wc-onboarding-bNg06Z62.js} +2 -2
- package/dist/ui/assets/{wc-permissions-BH_pyjzt.js → wc-permissions-D0w94vXH.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-B5m9keHf.js → wc-placeholder-Ch7fQFM1.js} +2 -2
- package/dist/ui/assets/{wc-profile-export-CUSnMx4l.js → wc-profile-export-BFF90Vk2.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-COrsGNVO.js → wc-secret-request-pXJeMHeS.js} +1 -1
- package/dist/ui/assets/{wc-settings-DbOCHvQA.js → wc-settings-KGpHvHOO.js} +3 -3
- package/dist/ui/assets/{wc-shell-Xrw2Q_l-.js → wc-shell-B5uhQoSH.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-BQBPwMA2.js → wc-shortcut-config-DCatL4tb.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-D752QtPV.js → wc-sprinkles-BQyYYsOa.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-DvAF0rPF.js → wc-transcript-export-DyqvXeuU.js} +2 -2
- package/dist/ui/assets/wc-tray-CjYFNQr2.js +5 -0
- package/dist/ui/assets/welcome-detection-t1oPE25e.js +1 -0
- package/dist/ui/assets/{whisper-session-CExf0vBt.js → whisper-session-6A5TUCSd.js} +2 -2
- package/dist/ui/assets/{xai-grok-iOYIBxH8.js → xai-grok-5TMXFoso.js} +1 -1
- package/dist/ui/assets/{xai-grok-Cfob0nrx.js → xai-grok-CFvK8Gfg.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/packages/webapp/index.html +3 -3
- package/dist/ui/packages/webapp/upgrade-to-seven.html +1 -1
- package/dist/ui/upgrade-to-seven.html +1 -1
- package/package.json +1 -1
- package/dist/ui/assets/provider-store-access-CgaKC7rB.js +0 -1
- package/dist/ui/assets/provider-store-access-DgrYdKML.js +0 -1
- package/dist/ui/assets/slicc-version-ComMn6Xo.js +0 -1
- package/dist/ui/assets/tray-leader-1ntSUEXa.js +0 -1
- package/dist/ui/assets/wc-tray-QWpxQYLb.js +0 -5
- package/dist/ui/assets/welcome-detection-Ny04c6Rd.js +0 -1
|
@@ -38,7 +38,7 @@ var j=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}
|
|
|
38
38
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
39
39
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
40
40
|
*/
|
|
41
|
-
const Gt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Kt=[-1,1,2,3,4,5,6,8],qt=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new j(e),n=Jt(t),{frequencyIndex:r,sampleRate:i}=Yt(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=Kt[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=Yt(t).sampleRate,s=Jt(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}Jt(t)===5&&t.readBits(1)&&(l=Yt(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},Jt=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},Yt=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<Gt.length?Gt[t]:null}},Xt=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=Kt.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),$t(r)===15&&(o+=24),t&&(o+=9,$t(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new j(c);return Zt(l,e.objectType),Qt(l,r),l.writeBits(4,a),t&&(Qt(l,e.outputSampleRate),Zt(l,2)),l.writeBits(3,0),c},Zt=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},Qt=(e,t)=>{let n=$t(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},$t=e=>{let t=Gt.indexOf(e);return t===-1?15:t},en=e=>{let t=/* @__PURE__ */ new Uint8Array(7),n=new j(t),{coreObjectType:r,frequencyIndex:i,channelConfiguration:a}=e,o=r-1;return n.writeBits(12,4095),n.writeBits(1,0),n.writeBits(2,0),n.writeBits(1,1),n.writeBits(2,o),n.writeBits(4,i),n.writeBits(1,0),n.writeBits(3,a),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.skipBits(13),n.writeBits(11,2047),n.writeBits(2,0),{header:t,bitstream:n}},tn=(e,t)=>{e.pos=30,e.writeBits(13,t)},nn=[48e3,44100,32e3],rn=[24e3,22050,16e3],an=`Mediabunny v1.61.
|
|
41
|
+
const Gt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Kt=[-1,1,2,3,4,5,6,8],qt=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new j(e),n=Jt(t),{frequencyIndex:r,sampleRate:i}=Yt(t),a=t.readBits(4),o=null;a>=1&&a<=7&&(o=Kt[a]);let s=n,c=!1,l=i;if(n===5||n===29)c=n===29,l=Yt(t).sampleRate,s=Jt(t),s===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let e=t.pos;if(t.readBits(11)!==695){t.pos=e+1;continue}Jt(t)===5&&t.readBits(1)&&(l=Yt(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return o!==null&&o>1&&(c=!1),{objectType:n,coreObjectType:s,frequencyIndex:r,channelConfiguration:a,outputSampleRate:l,outputNumberOfChannels:c&&o===1?2:o}},Jt=e=>{let t=e.readBits(5);return t===31?32+e.readBits(6):t},Yt=e=>{let t=e.readBits(4);return t===15?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<Gt.length?Gt[t]:null}},Xt=e=>{let t=e.objectType===5||e.objectType===29,n=e.objectType===29,r=t?e.outputSampleRate/2:e.outputSampleRate,i=n?1:e.outputNumberOfChannels,a=Kt.indexOf(i);if(a===-1)throw TypeError(`Unsupported number of channels: ${e.outputNumberOfChannels}`);let o=16;e.objectType>=32&&(o+=6),$t(r)===15&&(o+=24),t&&(o+=9,$t(e.outputSampleRate)===15&&(o+=24));let s=Math.ceil(o/8),c=new Uint8Array(s),l=new j(c);return Zt(l,e.objectType),Qt(l,r),l.writeBits(4,a),t&&(Qt(l,e.outputSampleRate),Zt(l,2)),l.writeBits(3,0),c},Zt=(e,t)=>{t<32?e.writeBits(5,t):(e.writeBits(5,31),e.writeBits(6,t-32))},Qt=(e,t)=>{let n=$t(t);e.writeBits(4,n),n===15&&e.writeBits(24,t)},$t=e=>{let t=Gt.indexOf(e);return t===-1?15:t},en=e=>{let t=/* @__PURE__ */ new Uint8Array(7),n=new j(t),{coreObjectType:r,frequencyIndex:i,channelConfiguration:a}=e,o=r-1;return n.writeBits(12,4095),n.writeBits(1,0),n.writeBits(2,0),n.writeBits(1,1),n.writeBits(2,o),n.writeBits(4,i),n.writeBits(1,0),n.writeBits(3,a),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.skipBits(13),n.writeBits(11,2047),n.writeBits(2,0),{header:t,bitstream:n}},tn=(e,t)=>{e.pos=30,e.writeBits(13,t)},nn=[48e3,44100,32e3],rn=[24e3,22050,16e3],an=`Mediabunny v1.61.6`
|
|
42
42
|
/*!
|
|
43
43
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
44
44
|
*
|
|
@@ -109,7 +109,7 @@ const gi=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.i
|
|
|
109
109
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
110
110
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
111
111
|
*/
|
|
112
|
-
let t=W(e),n=G(e,4),r=8;t===1&&(t=
|
|
112
|
+
let t=W(e),n=G(e,4),r=8;t===1&&(t=xu(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},bi=e=>vu(e)/65536,xi=e=>vu(e)/1073741824,Si=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=H(e);if(t|=n&127,!(n&128))break}return t},Ci=e=>{if(H(e)!==3)throw Error(`Invalid esds: expected ES_Descriptor.`);Si(e),e.skip(2);let t=H(e),n=!!(t&128),r=!!(t&64),i=!!(t&32);if(n&&e.skip(2),r){let t=H(e);e.skip(t)}if(i&&e.skip(2),H(e)!==4)throw Error(`Invalid esds: expected DecoderConfigDescriptor.`);let a=Si(e),o=e.filePos,s=H(e);e.skip(12);let c=null;if(a>e.filePos-o){if(H(e)!==5)throw Error(`Invalid esds: expected DecoderSpecificInfo.`);let t=Si(e);c=V(e,t)}return{objectTypeIndication:s,decoderSpecificInfo:c}},wi=e=>{let t=U(e);return e.skip(2),t=Math.min(t,e.remainingLength),w.decode(V(e,t))},Ti=e=>{let t=yi(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=W(e);e.skip(4);let r=V(e,t.contentSize-8);switch(n){case 1:return w.decode(r);case 2:return new te(`utf-16be`).decode(r);case 13:return new zt(r,`image/jpeg`);case 14:return new zt(r,`image/png`);case 27:return new zt(r,`image/bmp`);default:return r}},Ei=/* @__PURE__ */ new Uint32Array(256),Di=/* @__PURE__ */ new Uint32Array(256),Oi=/* @__PURE__ */ new Uint32Array(256),ki=/* @__PURE__ */ new Uint32Array(256),Ai=/* @__PURE__ */ new Uint32Array(256),ji=/* @__PURE__ */ new Uint32Array(256),Mi=/* @__PURE__ */ new Uint32Array(10)
|
|
113
113
|
/*!
|
|
114
114
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
115
115
|
*
|
|
@@ -117,7 +117,7 @@ let t=W(e),n=G(e,4),r=8;t===1&&(t=bu(e),r=16);let i=t-r;return i<0?null:{name:n,
|
|
|
117
117
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
118
118
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
119
119
|
*/
|
|
120
|
-
;let
|
|
120
|
+
;let Ni=!1;const Pi=()=>{let e=/* @__PURE__ */ new Uint8Array(256),t=/* @__PURE__ */ new Uint8Array(256),n=/* @__PURE__ */ 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);Ei[t]=n<<24|n<<16|n<<8|n,ji[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;Di[t]=l,Oi[t]=l>>>8|l<<24,ki[t]=l>>>16|l<<16,Ai[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)Mi[e]=i<<24,i=i<<1^(i&128?283:0);Ni=!0};var Fi=class{constructor(){this.roundkey=/* @__PURE__ */ new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=/* @__PURE__ */ new Uint8Array(16),this.out=/* @__PURE__ */ new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){n(e.byteLength===16),n(t.byteLength===16),Ni||Pi();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.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]^Ei[t>>>16&255]&4278190080^Ei[t>>>8&255]&16711680^Ei[t>>>0&255]&65280^Ei[t>>>24&255]&255^Mi[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]=Di[Ei[n>>>24&255]&255]^Oi[Ei[n>>>16&255]&255]^ki[Ei[n>>>8&255]&255]^Ai[Ei[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=Di[e>>>24]^Oi[r>>>16&255]^ki[n>>>8&255]^Ai[t&255]^this.roundkey[a],l=Di[t>>>24]^Oi[e>>>16&255]^ki[r>>>8&255]^Ai[n&255]^this.roundkey[a+1],u=Di[n>>>24]^Oi[t>>>16&255]^ki[e>>>8&255]^Ai[r&255]^this.roundkey[a+2],d=Di[r>>>24]^Oi[n>>>16&255]^ki[t>>>8&255]^Ai[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=ji[e>>>24&255]&4278190080^ji[r>>>16&255]&16711680^ji[n>>>8&255]&65280^ji[t>>>0&255]&255^this.roundkey[40],p=ji[t>>>24&255]&4278190080^ji[e>>>16&255]&16711680^ji[r>>>8&255]&65280^ji[n>>>0&255]&255^this.roundkey[41],m=ji[n>>>24&255]&4278190080^ji[t>>>16&255]&16711680^ji[e>>>8&255]&65280^ji[r>>>0&255]&255^this.roundkey[42],h=ji[r>>>24&255]&4278190080^ji[n>>>16&255]&16711680^ji[t>>>8&255]&65280^ji[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}};const Ii=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new Fi;return new ReadableStream({pull:async s=>{r||=(o.init(await t()),!0);let c=a+16,l=e.requestSliceRange(i,0,c);if(k(l)&&(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=V(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()}})};
|
|
121
121
|
/*!
|
|
122
122
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
123
123
|
*
|
|
@@ -125,7 +125,7 @@ let t=W(e),n=G(e,4),r=8;t===1&&(t=bu(e),r=16);let i=t-r;return i<0?null:{name:n,
|
|
|
125
125
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
126
126
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
127
127
|
*/
|
|
128
|
-
var Ii=class e extends mi{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=o,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ 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 gi({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 e=0,t=!1,r=!1;for(;;){let n=this.reader.requestSliceRange(e,8,16);if(k(n)&&(n=await n),!n)break;let i=e,a=yi(n);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=G(n,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(n.filePos,a.contentSize);if(k(e)&&(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)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,r=!0;break}else if(a.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.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,r=!0;break}e=i+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){n(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);k(e)&&(e=await e),n(e);let t=W(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(k(e)&&(e=await e),e){let t=yi(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);k(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let r=await t._getDemuxer();if(r.constructor!==e)throw Error(`Init input must match the input's format.`);await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let e of r.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,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,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(n(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Ri(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new zi(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;n(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&P.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){n(e.info?.type===`audio`);let r=Gr(e.info.codec),i=[],a=[];for(let n=0;n<t.sampleToChunk.length;n++){let o=t.sampleToChunk[n],s=t.sampleToChunk[n+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let n=0;n<c;n++){let s=o.startSampleIndex+n*o.samplesPerChunk,c=s+o.samplesPerChunk,l=E(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=E(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,g=h(i);g&&g.delta===m?g.count++:i.push({startIndex:o.startChunkIndex+n,startDecodeTimestamp:p,count:1,delta:m});let _=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;a.push(_)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=i,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);k(t)&&(t=await t),n(t);let r=yi(t);n(r?.name===`moof`);let i=this.reader.requestSlice(e,r.totalSize);k(i)&&(i=await i),n(i),this.traverseBox(i);let a=this.lastReadFragment;n(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)Wi(e,r.timestamp);else{let t=E(n,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Wi(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=E(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 Yi(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=yi(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,r=yi(e);if(!r)return!1;let i=e.filePos,a=t+r.totalSize;switch(r.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mvhd`:{let t=H(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=W(e),this.movieDurationInTimescale=bu(e)):(e.skip(8),this.movieTimescale=W(e),this.movieDurationInTimescale=W(e)),e.skip(16),this.movieMatrix=Gi(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...Ut,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:o,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(i,r.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Ri(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new zi(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=H(e),r=!!(pu(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=W(e),e.skip(4),t.durationInMovieTimescale=W(e);else if(n===1)e.skip(16),t.id=W(e),e.skip(4),t.durationInMovieTimescale=bu(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=Gi(e);t.matrix=p(i,this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=H(e);e.skip(3);let r=!1,i=0,a=W(e);for(let o=0;o<a;o++){let a=n===1?bu(e):W(e),o=n===1?xu(e):_u(e),s=bi(e);if(r){A._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){A._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=H(e);e.skip(3),n===0?(e.skip(8),t.timescale=W(e),t.durationInMediaTimescale=W(e)):n===1&&(e.skip(16),t.timescale=W(e),t.durationInMediaTimescale=bu(e));let r=U(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Ue(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=G(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...fe},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let n=this.currentTrack;if(!n)break;n.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=H(e);e.skip(3);let r=W(e);for(let i=0;i<r;i++){let r=e.filePos,i=yi(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=U(e),t.info.height=U(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`:Mr.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?A._warn(`Unknown encrypted video codec due to missing frma box.`):A._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=U(e);e.skip(6);let s=U(e),c=U(e);e.skip(4);let l=W(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*W(e),e.skip(8)):o===2&&(e.skip(4),l=wu(e),s=W(e),e.skip(4),c=W(e),u=W(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=Ur;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(Nr.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(A._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`:(A._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`:(A._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`:(A._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`:(A._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(A._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&&A._warn(`Unsupported PCM format.`)}else d===null?A._warn(`Unknown encrypted audio codec due to missing frma box.`):A._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=G(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=G(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:A._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);e.skip(3),e.skip(1);let r=H(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=H(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=H(e),t.encryptionInfo.defaultKid=ge(V(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=H(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(V(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(n(t.info),r.contentSize===0))break;t.info.codecDescription=V(e,r.contentSize);let i=yn(t.info.codecDescription)?.sequenceParameterSets[0],a=i&&xn(i);a&&Ki(t,a.pixelAspectRatio)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(n(t.info),r.contentSize===0))break;t.info.codecDescription=V(e,r.contentSize);let i=Ln(t.info.codecDescription)?.arrays.find(e=>e.nalUnitType===M.SPS_NUT)?.nalUnits[0],a=i&&Dn(i);a&&Ki(t,a.pixelAspectRatio)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(4);let r=H(e),i=H(e),a=H(e),o=a>>4,s=a>>1&7,c=a&1,l=H(e),u=H(e),d=H(e);t.info.vp9CodecInfo={profile:r,level:i,bitDepth:o,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(1);let i=H(e),a=i>>5,o=i&31,s=H(e),c=s>>7,l=s>>6&1,u=s>>5&1,d=s>>4&1,f=s>>3&1,p=s>>2&1,m=s&3,h=a===2&&l?u?12:10:l?10:8;e.skip(1);let g=V(e,r.contentSize-4),_=Wn(g);t.info.av1CodecInfo={profile:a,level:o,tier:c,bitDepth:h,monochrome:d,chromaSubsamplingX:f,chromaSubsamplingY:p,chromaSamplePosition:m,videoFullRangeFlag:_?.videoFullRangeFlag??0,colourPrimaries:_?.colourPrimaries??2,transferCharacteristics:_?.transferCharacteristics??2,matrixCoefficients:_?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`);let r=G(e,4);if(r!==`nclx`&&r!==`nclc`)break;let i=U(e),a=U(e),o=U(e),s;r===`nclx`&&(s=!!(H(e)&128)),t.info.colorSpace={primaries:ae[i],transfer:se[a],matrix:le[o],fullRange:s}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`);let r=W(e),i=W(e);r>0&&i>0&&(t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,r>i?t.info.squarePixelWidth=Math.round(t.info.width*r/i):t.info.squarePixelHeight=Math.round(t.info.height*i/r))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=W(e),r=W(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4),n(H(e)===3),Si(e),e.skip(2);let r=H(e),i=!!(r&128),a=!!(r&64),o=!!(r&32);if(i&&e.skip(2),a){let t=H(e);e.skip(t)}o&&e.skip(2),n(H(e)===4);let s=Si(e),c=e.filePos,l=H(e);if(l===64||l===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:l===103,objectType:null}):l===105||l===107?t.info.codec=`mp3`:l===221?t.info.codec=`vorbis`:l===169?t.info.codec=`dts`:A._warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),s>e.filePos-c){n(H(e)===5);let r=Si(e);if(t.info.codecDescription=V(e,r),t.info.codec===`aac`){let e=qt(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(U(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=H(e);t.info.pcmLittleEndian=!!(r&1),t.info.pcmSampleSize=H(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(1);let r=H(e),i=U(e),a=W(e),o=mu(e),s=H(e),c;c=s===0?/* @__PURE__ */ new Uint8Array:V(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),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=e.filePos;for(;e.filePos<a;){let n=H(e),r=pu(e);if((n&127)===Qn.STREAMINFO){e.skip(10);let n=W(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let i=e.filePos;e.filePos=r;let o=V(e,i-r),s=new Uint8Array(4+o.byteLength);new DataView(s.buffer).setUint32(0,1716281667,!1),s.set(o,4),t.info.codecDescription=s}break;case`dac3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let r=new j(V(e,3)),i=r.readBits(2);r.skipBits(8);let a=r.readBits(3),o=r.readBits(1);i<3&&(t.info.sampleRate=nn[i]),t.info.numberOfChannels=tr[a]+o}break;case`dec3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let i=V(e,r.contentSize),a=cr(i);if(!a){A._warn(`Invalid dec3 box contents, ignoring.`);break}let o=lr(a);o!==null&&(t.info.sampleRate=o),t.info.numberOfChannels=ur(a)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let i=V(e,Math.min(r.contentSize,20)),a=Cr(i);if(!a){A._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=a.sampleRate,a.numberOfChannels!==null&&(t.info.numberOfChannels=a.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=0,i=0;for(let a=0;a<n;a++){let n=W(e),a=W(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=W(e),r=0;for(let i=0;i<n;i++){let n=W(e),i=_u(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=W(e),r=W(e);if(n===0)for(let n=0;n<r;n++){let n=W(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=H(e),r=W(e),i=new j(V(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=W(e);for(let r=0;r<n;r++){let n=W(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=W(e);for(let r=0;r<n;r++){let n=W(e)-1,r=W(e),i=W(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=W(e);for(let r=0;r<n;r++){let n=W(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e);for(let r=0;r<n;r++){let n=bu(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mehd`:{let t=H(e);e.skip(3);let n=t===1?bu(e):W(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=W(e),n=W(e),r=W(e),i=W(e),a=W(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=H(e);e.skip(3);let n=W(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=W(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[H,U,pu,W],l=c[a],u=c[o],d=c[s],f=W(e);for(let n=0;n<f;n++){let n=t===1?bu(e):W(e),i=t===1?bu(e):W(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:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(n(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.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 t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[h(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration;let{currentFragmentState:i}=this.currentTrack;n(i),i.startTimestamp!==null&&(Wi(e,i.startTimestamp),e.startTimestampIsFinal=!0),i.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=i.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=_i(V(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{n(this.currentFragment),e.skip(1);let t=pu(e),r=!!(t&1),i=!!(t&2),a=!!(t&8),o=!!(t&16),s=!!(t&32),c=!!(t&65536),l=!!(t&131072),u=W(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=bu(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(d.currentFragmentState.sampleDescriptionIndex=W(e)),a&&(d.currentFragmentState.defaultSampleDuration=W(e)),o&&(d.currentFragmentState.defaultSampleSize=W(e)),s&&(d.currentFragmentState.defaultSampleFlags=W(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;n(t.currentFragmentState);let r=H(e);e.skip(3);let i=r===0?W(e):bu(e);t.currentFragmentState.startTimestamp=i}break;case`trun`:{let t=this.currentTrack;if(!t)break;n(this.currentFragment),n(t.currentFragmentState),e.skip(1);let r=pu(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=W(e),d=null;i&&(d=_u(e));let f=null;a&&(f=W(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=W(e):(n(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=W(e):(n(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=W(e):(n(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=_u(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),pu(e)&1){let n=G(e,4),r=W(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=H(e),r=W(e),i=null;n===0&&r>0&&(i=V(e,r));let a=Ji(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);if(pu(e)&1){let n=G(e,4),r=W(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=W(e);if(r===0)break;r>1&&A._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?W(e):Number(bu(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Ji(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;n(this.currentFragment);let r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);let i=!!(pu(e)&2),a=W(e),o=t.encryptionInfo.defaultPerSampleIvSize;n(o!==null);for(let n=0;n<Math.min(a,r.samples.length);n++){let a=/* @__PURE__ */ new Uint8Array(16);o>0?a.set(V(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(i){let t=U(e);s=[];for(let n=0;n<t;n++){let t=U(e),n=W(e);s.push({clearLen:t,protectedLen:n})}}let c=r.samples[n];c.encryption={iv:a,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(i,r.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]??=Ci(n):this.metadataTags.raw[e.name]??=V(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=w.decode(V(n,e.contentSize)):this.metadataTags.title??=Ci(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=Ci(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=Ci(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=Ci(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=Ci(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=Ci(n));break;case`©day`:if(!this.currentTrack){let e=new Date(Ci(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=Ci(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=Ci(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=W(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=W(e);for(let n=0;n<t;n++){let t=W(e);e.skip(4);let r=w.decode(V(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(i,r.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=wi(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`tmpo`:if(i instanceof Uint8Array&&i.length>=2){let e=C(i).getInt16(0,!1);e>0&&(this.metadataTags.beatsPerMinute??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof zt?(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=C(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=C(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=a,!0}},Li=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ 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 this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(n(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 Fe(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Bi(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!qi(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,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=Vi(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!qi(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=Ce(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,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ui(e,r);return this.fetchPacketForSampleIndex(n,t)}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 t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return n(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Hi(n,e);if(!r)return null;let i;if(t.metadataOnly)i=hi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(k(t)&&(t=await t),!t)return null;if(i=V(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await Yi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=Xi(this.internalTrack.encryptionInfo),t&&(i=await Zi(this.internalTrack,t,i,null))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new I(i,r.isKeyFrame?`key`:`delta`,a,o,e,r.sampleSize);return this.packetToSampleIndex.set(s,e),s}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];n(i);let a;if(r.metadataOnly)a=hi;else{let t=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(k(t)&&(t=await t),!t)return null;if(a=V(t,i.byteSize),this.internalTrack.encryptionInfo){let t=i.encryption??Xi(this.internalTrack.encryptionInfo);t&&(a=await Zi(this.internalTrack,t,a,e))}}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new I(a,i.isKeyFrame?`key`:`delta`,o,s,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,r,i,a){let o=this.internalTrack.demuxer,s=null,c=null,l=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,a);n!==-1&&(c=e,l=n)}let u=E(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),d=u===-1?null:this.internalTrack.fragmentLookupTable[u],f=E(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(k(e)&&(e=await e),!e)break;let n=h,r=yi(e);if(!r)break;if(r.name===`moof`){s=await o.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(s);if(r)return this.fetchPacketInFragment(s,e,a);e!==-1&&(c=s,l=e)}h=n+r.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let e=this.internalTrack.fragmentLookupTable[u-1];n(!e||e.timestamp<d.timestamp);let r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,i,a)}return c?this.fetchPacketInFragment(c,l,a):null}},Ri=class extends Li{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}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===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&_n(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&On(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!Hn(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Vn(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!Gn(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Wn(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&Kn(e.data)}if(!ue(this.internalTrack.info.colorSpace)){let e=zr(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:Rr(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};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}},zi=class extends Li{constructor(e){super(e),this.decoderConfigPromise=null}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&br(e.data)}return{codec:Vr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};const Bi=(e,t)=>{if(e.presentationTimestamps){let n=E(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=E(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)}},Vi=(e,t)=>{if(!e.keySampleIndices)return Bi(e,t);if(e.presentationTimestamps){let n=E(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(ye(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=Bi(e,t),r=E(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Hi=(e,t)=>{let r=E(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let a=i.startDecodeTimestamp+(t-i.startIndex)*i.delta,o=E(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[o];s&&t-s.startIndex<s.count&&(a+=s.offset);let c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=E(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[l];n(u);let d=u.startChunkIndex+Math.floor((t-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*(t-p),m+=c*u.samplesPerChunk;else for(let n=p;n<p+u.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(h+=r),m+=r}let g=i.delta;if(e.presentationTimestamps){let r=e.presentationTimestampIndexMap[t];n(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||ye(e.keySampleIndices,t,e=>e)!==-1}},Ui=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=E(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Wi=(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},Gi=e=>[bi(e),bi(e),xi(e),bi(e),bi(e),xi(e),bi(e),bi(e),xi(e)],Ki=(e,t)=>{let n=e.info;if(n.type!==`video`)return;let{num:r,den:i}=t;r>0&&i>0&&r!==i&&(r>i?(n.squarePixelWidth=Math.round(n.width*r/i),n.squarePixelHeight=n.height):(n.squarePixelWidth=n.width,n.squarePixelHeight=Math.round(n.height*i/r)))},qi=e=>e.sampleSizes.length===0,Ji=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},Yi=async(e,t,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{n(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)i+=r.sampleSizes[e]}let a=e.requestSlice(r.offset,i);if(k(a)&&(a=await a),!a)throw Error(`Failed to read auxiliary encryption info.`);let o=t.defaultPerSampleIvSize;n(o!==null);let s=[];for(let e=0;e<r.sampleCount;e++){let n=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],i=/* @__PURE__ */ new Uint8Array(16);o>0?i.set(V(a,o),0):i.set(t.defaultConstantIv,0);let c=null;if(n>o){let e=U(a);c=[];for(let t=0;t<e;t++){let e=U(a),t=W(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},Xi=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Zi=async(e,t,r,i)=>{n(e.encryptionInfo);let a=e.encryptionInfo;n(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++)vi(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&&he.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:_e(n)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return a.scheme===`cenc`||a.scheme===`cens`?Qi(s,a,t,r):$i(s,a,t,r)},Qi=async(e,t,r,i)=>{let a=/* @__PURE__ */ 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);n(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let c=ea(r.subsamples,t.defaultCryptByteBlock,t.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},$i=(e,t,r,i)=>{let a=new Pi;a.init({key:e,iv:r.iv});let o=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(n(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=ea(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},ea=(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};
|
|
128
|
+
var Li=class e extends mi{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=o,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */ 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 gi({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 e=0,t=!1,r=!1;for(;;){let n=this.reader.requestSliceRange(e,8,16);if(k(n)&&(n=await n),!n)break;let i=e,a=yi(n);if(!a)break;if(a.name===`ftyp`||a.name===`styp`){let e=G(n,4);this.isQuickTime=e===`qt `}else if(a.name===`moov`){let e=this.reader.requestSlice(n.filePos,a.contentSize);if(k(e)&&(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)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+a.totalSize,r=!0;break}else if(a.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.`);await this.copyMetadataFromInitInput(this.input._initInput),t=!1,r=!0;break}e=i+a.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){n(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);k(e)&&(e=await e),n(e);let t=W(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(k(e)&&(e=await e),e){let t=yi(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);k(n)&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}async copyMetadataFromInitInput(t){let r=await t._getDemuxer();if(r.constructor!==e)throw Error(`Init input must match the input's format.`);await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let e of r.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,matrix:e.matrix,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,maxBitrate:e.maxBitrate,avgBitrate:e.avgBitrate,info:e.info};e.trackBacking&&(n(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new zi(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Bi(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;n(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&P.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){n(e.info?.type===`audio`);let r=Gr(e.info.codec),i=[],a=[];for(let n=0;n<t.sampleToChunk.length;n++){let o=t.sampleToChunk[n],s=t.sampleToChunk[n+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let n=0;n<c;n++){let s=o.startSampleIndex+n*o.samplesPerChunk,c=s+o.samplesPerChunk,l=E(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=E(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,g=h(i);g&&g.delta===m?g.count++:i.push({startIndex:o.startChunkIndex+n,startDecodeTimestamp:p,count:1,delta:m});let _=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;a.push(_)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=i,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);k(t)&&(t=await t),n(t);let r=yi(t);n(r?.name===`moof`);let i=this.reader.requestSlice(e,r.totalSize);k(i)&&(i=await i),n(i),this.traverseBox(i);let a=this.lastReadFragment;n(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)Gi(e,r.timestamp);else{let t=E(n,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Gi(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=E(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 Xi(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=yi(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,r=yi(e);if(!r)return!1;let i=e.filePos,a=t+r.totalSize;switch(r.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mvhd`:{let t=H(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=W(e),this.movieDurationInTimescale=xu(e)):(e.skip(8),this.movieTimescale=W(e),this.movieDurationInTimescale=W(e)),e.skip(16),this.movieMatrix=Ki(e)}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...Ut,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:o,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(i,r.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new zi(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new Bi(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=H(e),r=!!(mu(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=W(e),e.skip(4),t.durationInMovieTimescale=W(e);else if(n===1)e.skip(16),t.id=W(e),e.skip(4),t.durationInMovieTimescale=xu(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=Ki(e);t.matrix=p(i,this.movieMatrix)}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=H(e);e.skip(3);let r=!1,i=0,a=W(e);for(let o=0;o<a;o++){let a=n===1?xu(e):W(e),o=n===1?Su(e):vu(e),s=bi(e);if(r){A._warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){A._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=H(e);e.skip(3),n===0?(e.skip(8),t.timescale=W(e),t.durationInMediaTimescale=W(e)):n===1&&(e.skip(16),t.timescale=W(e),t.durationInMediaTimescale=xu(e));let r=U(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;Ue(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=G(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...fe},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let n=this.currentTrack;if(!n)break;n.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,r.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=H(e);e.skip(3);let r=W(e);for(let i=0;i<r;i++){let r=e.filePos,i=yi(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=U(e),t.info.height=U(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`:Mr.includes(a)?(t.info.codec=`prores`,t.info.proresFormat=a):n===null?A._warn(`Unknown encrypted video codec due to missing frma box.`):A._warn(`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=U(e);e.skip(6);let s=U(e),c=U(e);e.skip(4);let l=W(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*W(e),e.skip(8)):o===2&&(e.skip(4),l=Tu(e),s=W(e),e.skip(4),c=W(e),u=W(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=Ur;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(Nr.includes(d))t.info.codec=`dts`,t.info.dtsFormat=d;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(A._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`:(A._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`:(A._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`:(A._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`:(A._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(A._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&&A._warn(`Unsupported PCM format.`)}else d===null?A._warn(`Unknown encrypted audio codec due to missing frma box.`):A._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=G(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=G(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:A._warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);e.skip(3),e.skip(1);let r=H(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=H(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=H(e),t.encryptionInfo.defaultKid=ge(V(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=H(e),r=/* @__PURE__ */ new Uint8Array(16);r.set(V(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t||(n(t.info),r.contentSize===0))break;t.info.codecDescription=V(e,r.contentSize);let i=yn(t.info.codecDescription)?.sequenceParameterSets[0],a=i&&xn(i);a&&qi(t,a.pixelAspectRatio)}break;case`hvcC`:{let t=this.currentTrack;if(!t||(n(t.info),r.contentSize===0))break;t.info.codecDescription=V(e,r.contentSize);let i=Ln(t.info.codecDescription)?.arrays.find(e=>e.nalUnitType===M.SPS_NUT)?.nalUnits[0],a=i&&Dn(i);a&&qi(t,a.pixelAspectRatio)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(4);let r=H(e),i=H(e),a=H(e),o=a>>4,s=a>>1&7,c=a&1,l=H(e),u=H(e),d=H(e);t.info.vp9CodecInfo={profile:r,level:i,bitDepth:o,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(1);let i=H(e),a=i>>5,o=i&31,s=H(e),c=s>>7,l=s>>6&1,u=s>>5&1,d=s>>4&1,f=s>>3&1,p=s>>2&1,m=s&3,h=a===2&&l?u?12:10:l?10:8;e.skip(1);let g=V(e,r.contentSize-4),_=Wn(g);t.info.av1CodecInfo={profile:a,level:o,tier:c,bitDepth:h,monochrome:d,chromaSubsamplingX:f,chromaSubsamplingY:p,chromaSamplePosition:m,videoFullRangeFlag:_?.videoFullRangeFlag??0,colourPrimaries:_?.colourPrimaries??2,transferCharacteristics:_?.transferCharacteristics??2,matrixCoefficients:_?.matrixCoefficients??2}}break;case`colr`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`);let r=G(e,4);if(r!==`nclx`&&r!==`nclc`)break;let i=U(e),a=U(e),o=U(e),s;r===`nclx`&&(s=!!(H(e)&128)),t.info.colorSpace={primaries:ae[i],transfer:se[a],matrix:le[o],fullRange:s}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`);let r=W(e),i=W(e);r>0&&i>0&&(t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,r>i?t.info.squarePixelWidth=Math.round(t.info.width*r/i):t.info.squarePixelHeight=Math.round(t.info.height*i/r))}break;case`btrt`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=W(e),r=W(e);t.maxBitrate=n>0?n:null,t.avgBitrate=r>0?r:null}break;case`wave`:this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t||t.info?.type!==`audio`)break;e.skip(4);let{objectTypeIndication:n,decoderSpecificInfo:r}=Ci(e);if(n===64||n===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:n===103,objectType:null}):n===105||n===107?t.info.codec=`mp3`:n===221?t.info.codec=`vorbis`:n===169?t.info.codec=`dts`:A._warn(`Unsupported audio codec (objectTypeIndication ${n}) - discarding track.`),r&&(t.info.codecDescription=r,t.info.codec===`aac`)){let e=qt(t.info.codecDescription);e.outputNumberOfChannels!==null&&(t.info.numberOfChannels=e.outputNumberOfChannels),e.outputSampleRate!==null&&(t.info.sampleRate=e.outputSampleRate)}}break;case`enda`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(U(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=H(e);t.info.pcmLittleEndian=!!(r&1),t.info.pcmSampleSize=H(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(1);let r=H(e),i=U(e),a=W(e),o=hu(e),s=H(e),c;c=s===0?/* @__PURE__ */ new Uint8Array:V(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),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=e.filePos;for(;e.filePos<a;){let n=H(e),r=mu(e);if((n&127)===Qn.STREAMINFO){e.skip(10);let n=W(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let i=e.filePos;e.filePos=r;let o=V(e,i-r),s=new Uint8Array(4+o.byteLength);new DataView(s.buffer).setUint32(0,1716281667,!1),s.set(o,4),t.info.codecDescription=s}break;case`dac3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let r=new j(V(e,3)),i=r.readBits(2);r.skipBits(8);let a=r.readBits(3),o=r.readBits(1);i<3&&(t.info.sampleRate=nn[i]),t.info.numberOfChannels=tr[a]+o}break;case`dec3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let i=V(e,r.contentSize),a=cr(i);if(!a){A._warn(`Invalid dec3 box contents, ignoring.`);break}let o=lr(a);o!==null&&(t.info.sampleRate=o),t.info.numberOfChannels=ur(a)}break;case`ddts`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let i=V(e,Math.min(r.contentSize,20)),a=Cr(i);if(!a){A._warn(`Invalid ddts box contents, ignoring.`);break}t.info.sampleRate=a.sampleRate,a.numberOfChannels!==null&&(t.info.numberOfChannels=a.numberOfChannels)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e),r=0,i=0;for(let a=0;a<n;a++){let n=W(e),a=W(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=W(e),r=0;for(let i=0;i<n;i++){let n=W(e),i=vu(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=W(e),r=W(e);if(n===0)for(let n=0;n<r;n++){let n=W(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=H(e),r=W(e),i=new j(V(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=W(e);for(let r=0;r<n;r++){let n=W(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=W(e);for(let r=0;r<n;r++){let n=W(e)-1,r=W(e),i=W(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=W(e);for(let r=0;r<n;r++){let n=W(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=W(e);for(let r=0;r<n;r++){let n=xu(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,r.contentSize));break;case`mehd`:{let t=H(e);e.skip(3);let n=t===1?xu(e):W(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=W(e),n=W(e),r=W(e),i=W(e),a=W(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=H(e);e.skip(3);let n=W(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=W(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[H,U,mu,W],l=c[a],u=c[o],d=c[s],f=W(e);for(let n=0;n<f;n++){let n=t===1?xu(e):W(e),i=t===1?xu(e):W(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:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */ new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(n(this.currentFragment),this.readContiguousBoxes(e.slice(i,r.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 t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[h(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration;let{currentFragmentState:i}=this.currentTrack;n(i),i.startTimestamp!==null&&(Gi(e,i.startTimestamp),e.startTimestampIsFinal=!0),i.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=i.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=_i(V(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{n(this.currentFragment),e.skip(1);let t=mu(e),r=!!(t&1),i=!!(t&2),a=!!(t&8),o=!!(t&16),s=!!(t&32),c=!!(t&65536),l=!!(t&131072),u=W(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=xu(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(d.currentFragmentState.sampleDescriptionIndex=W(e)),a&&(d.currentFragmentState.defaultSampleDuration=W(e)),o&&(d.currentFragmentState.defaultSampleSize=W(e)),s&&(d.currentFragmentState.defaultSampleFlags=W(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;n(t.currentFragmentState);let r=H(e);e.skip(3);let i=r===0?W(e):xu(e);t.currentFragmentState.startTimestamp=i}break;case`trun`:{let t=this.currentTrack;if(!t)break;n(this.currentFragment),n(t.currentFragmentState),e.skip(1);let r=mu(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=W(e),d=null;i&&(d=vu(e));let f=null;a&&(f=W(e));let p;this.currentFragment.trackData.has(t.id)?(p=this.currentFragment.trackData.get(t.id),d!==null&&(p.currentOffset=t.currentFragmentState.baseDataOffset+d)):(p={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,p));for(let r=0;r<u;r++){let i;o?i=W(e):(n(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=W(e):(n(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=W(e):(n(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=vu(e));let m=!(u&65536);p.samples.push({presentationTimestamp:p.currentTimestamp+d,duration:i,byteOffset:p.currentOffset,byteSize:a,isKeyFrame:m,encryption:null}),p.currentOffset+=a,p.currentTimestamp+=i}this.currentFragment.implicitBaseDataOffset=p.currentOffset}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),mu(e)&1){let n=G(e,4),r=W(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=H(e),r=W(e),i=null;n===0&&r>0&&(i=V(e,r));let a=Yi(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=H(e);if(mu(e)&1){let n=G(e,4),r=W(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=W(e);if(r===0)break;r>1&&A._warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?W(e):Number(xu(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=Yi(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;n(this.currentFragment);let r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);let i=!!(mu(e)&2),a=W(e),o=t.encryptionInfo.defaultPerSampleIvSize;n(o!==null);for(let n=0;n<Math.min(a,r.samples.length);n++){let a=/* @__PURE__ */ new Uint8Array(16);o>0?a.set(V(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(i){let t=U(e);s=[];for(let n=0;n<t;n++){let t=U(e),n=W(e);s.push({clearLen:t,protectedLen:n})}}let c=r.samples[n];c.encryption={iv:a,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(i,r.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]??=wi(n):this.metadataTags.raw[e.name]??=V(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=w.decode(V(n,e.contentSize)):this.metadataTags.title??=wi(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=wi(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=wi(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=wi(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=wi(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=wi(n));break;case`©day`:if(!this.currentTrack){let e=new Date(wi(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=wi(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=wi(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=W(e)!==0;this.currentMetadataKeys=/* @__PURE__ */ new Map,t?this.readContiguousBoxes(e.slice(i,r.contentSize)):this.readContiguousBoxes(e.slice(i+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=W(e);for(let n=0;n<t;n++){let t=W(e);e.skip(4);let r=w.decode(V(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(i,r.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=Ti(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`tmpo`:if(i instanceof Uint8Array&&i.length>=2){let e=C(i).getInt16(0,!1);e>0&&(this.metadataTags.beatsPerMinute??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof zt?(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=C(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=C(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=a,!0}},Ri=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */ new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */ 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 this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(n(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 Fe(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Vi(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Ji(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,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=Hi(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Ji(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=Ce(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,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Wi(e,r);return this.fetchPacketForSampleIndex(n,t)}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 t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return n(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Ui(n,e);if(!r)return null;let i;if(t.metadataOnly)i=hi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(k(t)&&(t=await t),!t)return null;if(i=V(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){let n=await Xi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<n.length&&(t=n[e])}t??=Zi(this.internalTrack.encryptionInfo),t&&(i=await Qi(this.internalTrack,t,i,null))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new I(i,r.isKeyFrame?`key`:`delta`,a,o,e,r.sampleSize);return this.packetToSampleIndex.set(s,e),s}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];n(i);let a;if(r.metadataOnly)a=hi;else{let t=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(k(t)&&(t=await t),!t)return null;if(a=V(t,i.byteSize),this.internalTrack.encryptionInfo){let t=i.encryption??Zi(this.internalTrack.encryptionInfo);t&&(a=await Qi(this.internalTrack,t,a,e))}}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new I(a,i.isKeyFrame?`key`:`delta`,o,s,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,r,i,a){let o=this.internalTrack.demuxer,s=null,c=null,l=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,a);n!==-1&&(c=e,l=n)}let u=E(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),d=u===-1?null:this.internalTrack.fragmentLookupTable[u],f=E(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(k(e)&&(e=await e),!e)break;let n=h,r=yi(e);if(!r)break;if(r.name===`moof`){s=await o.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(s);if(r)return this.fetchPacketInFragment(s,e,a);e!==-1&&(c=s,l=e)}h=n+r.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let e=this.internalTrack.fragmentLookupTable[u-1];n(!e||e.timestamp<d.timestamp);let r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,i,a)}return c?this.fetchPacketInFragment(c,l,a):null}},zi=class extends Ri{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}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===`avc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&_n(e.data)}else if(this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription){let e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&On(e.data)}else if(this.internalTrack.info.codec===`vp9`&&(!this.internalTrack.info.vp9CodecInfo||!Hn(this.internalTrack.info.vp9CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Vn(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else if(this.internalTrack.info.codec===`av1`&&(!this.internalTrack.info.av1CodecInfo||!Gn(this.internalTrack.info.av1CodecInfo))){let e=await this.getFirstPacket({}),t=e&&Wn(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else if(this.internalTrack.info.codec===`prores`&&!this.internalTrack.info.proresCodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&Kn(e.data)}if(!ue(this.internalTrack.info.colorSpace)){let e=zr(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let e={codec:Rr(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};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}},Bi=class extends Ri{constructor(e){super(e),this.decoderConfigPromise=null}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&br(e.data)}return{codec:Vr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};const Vi=(e,t)=>{if(e.presentationTimestamps){let n=E(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=E(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)}},Hi=(e,t)=>{if(!e.keySampleIndices)return Vi(e,t);if(e.presentationTimestamps){let n=E(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(ye(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=Vi(e,t),r=E(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Ui=(e,t)=>{let r=E(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let a=i.startDecodeTimestamp+(t-i.startIndex)*i.delta,o=E(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[o];s&&t-s.startIndex<s.count&&(a+=s.offset);let c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=E(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[l];n(u);let d=u.startChunkIndex+Math.floor((t-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*(t-p),m+=c*u.samplesPerChunk;else for(let n=p;n<p+u.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(h+=r),m+=r}let g=i.delta;if(e.presentationTimestamps){let r=e.presentationTimestampIndexMap[t];n(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||ye(e.keySampleIndices,t,e=>e)!==-1}},Wi=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=E(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Gi=(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},Ki=e=>[bi(e),bi(e),xi(e),bi(e),bi(e),xi(e),bi(e),bi(e),xi(e)],qi=(e,t)=>{let n=e.info;if(n.type!==`video`)return;let{num:r,den:i}=t;r>0&&i>0&&r!==i&&(r>i?(n.squarePixelWidth=Math.round(n.width*r/i),n.squarePixelHeight=n.height):(n.squarePixelWidth=n.width,n.squarePixelHeight=Math.round(n.height*i/r)))},Ji=e=>e.sampleSizes.length===0,Yi=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},Xi=async(e,t,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{n(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)i+=r.sampleSizes[e]}let a=e.requestSlice(r.offset,i);if(k(a)&&(a=await a),!a)throw Error(`Failed to read auxiliary encryption info.`);let o=t.defaultPerSampleIvSize;n(o!==null);let s=[];for(let e=0;e<r.sampleCount;e++){let n=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],i=/* @__PURE__ */ new Uint8Array(16);o>0?i.set(V(a,o),0):i.set(t.defaultConstantIv,0);let c=null;if(n>o){let e=U(a);c=[];for(let t=0;t<e;t++){let e=U(a),t=W(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},Zi=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Qi=async(e,t,r,i)=>{n(e.encryptionInfo);let a=e.encryptionInfo;n(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++)vi(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&&he.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:_e(n)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return a.scheme===`cenc`||a.scheme===`cens`?$i(s,a,t,r):ea(s,a,t,r)},$i=async(e,t,r,i)=>{let a=/* @__PURE__ */ 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);n(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let c=ta(r.subsamples,t.defaultCryptByteBlock,t.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},ea=(e,t,r,i)=>{let a=new Fi;a.init({key:e,iv:r.iv});let o=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(n(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=ta(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},ta=(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};
|
|
129
129
|
/*!
|
|
130
130
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
131
131
|
*
|
|
@@ -133,7 +133,7 @@ var Ii=class e extends mi{constructor(e){super(e),this.moovSlice=null,this.curre
|
|
|
133
133
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
134
134
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
135
135
|
*/
|
|
136
|
-
var ta=class{constructor(e){this.value=e}},na=class{constructor(e){this.value=e}},ra=class{constructor(e){this.value=e}},ia=class{constructor(e){this.value=e}},L;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseYaw=30323]=`ProjectionPoseYaw`,e[e.ProjectionPosePitch=30324]=`ProjectionPosePitch`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(L||={});const aa=[L.EBML,L.Segment],oa=[L.SeekHead,L.Info,L.Cluster,L.Tracks,L.Cues,L.Attachments,L.Chapters,L.Tags],sa=[...aa,...oa],ca=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,la=e=>e<1n<<8n?1:e<1n<<16n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,ua=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-(2**34)&&e<2**34?5:6,da=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<(1<<21)-1)return 3;if(e<(1<<28)-1)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw Error(`EBML varint size not supported `+e)};var fa=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap,this.dataOffsets=/* @__PURE__ */ new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=ca(e)){let n=0;switch(t){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw Error(`Bad unsigned int size `+t)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,t=la(e)){let n=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(n++,Number(e>>BigInt(r*8)&255n));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,t=ua(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=da(e)){let n=0;switch(t){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw Error(`Bad EBML varint size `+t)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split(``).map(e=>e.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),e.size!==-1){let e=this.writer.getPos()-r,i=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,n),this.writer.seek(i)}}else if(typeof e.data==`number`){let t=e.size??ca(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data==`bigint`){let t=e.size??la(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data==`string`)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ta)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof na)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof ra){let t=e.size??ua(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof ia){let t=T.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Ee(e.data)}}};const pa=e=>{if(e.remainingLength<1)return null;let t=H(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},ma=e=>{if(e.remainingLength<1)return null;let t=H(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+=H(e);return i},R=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=H(e);return n},ha=(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(H(e));return n},ga=e=>{let t=pa(e);return t===null||e.remainingLength<t?null:R(e,t)},_a=e=>{if(e.remainingLength<1)return null;if(H(e)===255)return;e.skip(-1);let t=ma(e);if(t===null)return null;if(t!==72057594037927940)return t},va=e=>{n(e.remainingLength>=2);let t=ga(e);if(t===null)return null;let r=_a(e);return r===null?null:{id:t,size:r}},ya=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},ba=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return w.decode(n.subarray(0,r))},xa=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?Cu(e):wu(e)},Sa=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(k(t)&&(t=await t),!t)break;let n=va(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Ta(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},Ca=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(k(t)&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=ga(t);if(e!==null&&a.has(e))return o;o++}}return null},wa={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`,dts:`A_DTS`,"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 Ta(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}
|
|
136
|
+
var na=class{constructor(e){this.value=e}},ra=class{constructor(e){this.value=e}},ia=class{constructor(e){this.value=e}},aa=class{constructor(e){this.value=e}},L;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseYaw=30323]=`ProjectionPoseYaw`,e[e.ProjectionPosePitch=30324]=`ProjectionPosePitch`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(L||={});const oa=[L.EBML,L.Segment],sa=[L.SeekHead,L.Info,L.Cluster,L.Tracks,L.Cues,L.Attachments,L.Chapters,L.Tags],ca=[...oa,...sa],la=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,ua=e=>e<1n<<8n?1:e<1n<<16n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,da=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-(2**34)&&e<2**34?5:6,fa=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<(1<<21)-1)return 3;if(e<(1<<28)-1)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw Error(`EBML varint size not supported `+e)};var pa=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap,this.dataOffsets=/* @__PURE__ */ new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=la(e)){let n=0;switch(t){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw Error(`Bad unsigned int size `+t)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,t=ua(e)){let n=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(n++,Number(e>>BigInt(r*8)&255n));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,t=da(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=fa(e)){let n=0;switch(t){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw Error(`Bad EBML varint size `+t)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split(``).map(e=>e.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),e.size!==-1){let e=this.writer.getPos()-r,i=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,n),this.writer.seek(i)}}else if(typeof e.data==`number`){let t=e.size??la(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data==`bigint`){let t=e.size??ua(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data==`string`)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof na)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof ra)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof ia){let t=e.size??da(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof aa){let t=T.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Ee(e.data)}}};const ma=e=>{if(e.remainingLength<1)return null;let t=H(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},ha=e=>{if(e.remainingLength<1)return null;let t=H(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+=H(e);return i},R=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=H(e);return n},ga=(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(H(e));return n},_a=e=>{let t=ma(e);return t===null||e.remainingLength<t?null:R(e,t)},va=e=>{if(e.remainingLength<1)return null;if(H(e)===255)return;e.skip(-1);let t=ha(e);if(t===null)return null;if(t!==72057594037927940)return t},ya=e=>{n(e.remainingLength>=2);let t=_a(e);if(t===null)return null;let r=va(e);return r===null?null:{id:t,size:r}},ba=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},xa=(e,t)=>{let n=V(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return w.decode(n.subarray(0,r))},Sa=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?wu(e):Tu(e)},Ca=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(k(t)&&(t=await t),!t)break;let n=ya(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Ea(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},wa=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(k(t)&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=_a(t);if(e!==null&&a.has(e))return o;o++}}return null},Ta={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`,dts:`A_DTS`,"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 Ea(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}
|
|
137
137
|
/*!
|
|
138
138
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
139
139
|
*
|
|
@@ -141,7 +141,7 @@ var ta=class{constructor(e){this.value=e}},na=class{constructor(e){this.value=e}
|
|
|
141
141
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
142
142
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
143
143
|
*/
|
|
144
|
-
const
|
|
144
|
+
const Da=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};
|
|
145
145
|
/*!
|
|
146
146
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
147
147
|
*
|
|
@@ -149,7 +149,7 @@ const Ea=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.i
|
|
|
149
149
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
150
150
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
151
151
|
*/
|
|
152
|
-
var Da;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(Da||={});var Oa;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(Oa||={});var ka;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(ka||={});const Aa=[{id:L.SeekHead,flag:`seekHeadSeen`},{id:L.Info,flag:`infoSeen`},{id:L.Tracks,flag:`tracksSeen`},{id:L.Cues,flag:`cuesSeen`}],ja=10*2**20;var Ma=class extends mi{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 Ea({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(k(t)&&(t=await t),!t)break;let n=va(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===L.EBML){Ta(i);let e=this.reader.requestSlice(a,i);if(k(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===L.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===L.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await Sa(this.reader,a,sa,this.reader.fileSize)).pos-a);let e=h(this.segments);e&&(e.elementEndPos=a+i)}Ta(i),e=a+i}})()}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,r=/* @__PURE__ */ new Set;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let t=this.reader.requestSliceRange(n,2,16);if(k(t)&&(t=await t),!t)break;let i=n,a=va(t);if(!a||!oa.includes(a.id)&&a.id!==L.Void){let e=await Ca(this.reader,i,oa,Math.min(this.currentSegment.elementEndPos??1/0,i+ja));if(e){n=e;continue}break}let{id:o,size:s}=a,c=t.filePos,l=Aa.findIndex(e=>e.id===o);if(l!==-1){let t=Aa[l].flag;this.currentSegment[t]=!0,o===L.SeekHead&&r.add(i-e),Ta(s);let n=this.reader.requestSlice(c,s);k(n)&&(n=await n),n&&this.readContiguousElements(n)}else if(o===L.Tags||o===L.Attachments){o===L.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ta(s);let e=this.reader.requestSlice(c,s);k(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(o===L.Cluster){this.currentSegment.clusterSeekStartPos=i;break}if(s===void 0)break;n=c+s}if(this.reader.fileSize!==null)for(;;){let t=this.currentSegment.seekEntries.find(e=>e.id===L.SeekHead&&!r.has(e.segmentPosition));if(!t)break;r.add(t.segmentPosition);let n=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(k(n)&&(n=await n),!n)continue;let i=va(n);if(!i||i.id!==L.SeekHead)continue;let{size:a}=i;Ta(a);let o=this.reader.requestSlice(n.filePos,a);k(o)&&(o=await o),o&&this.readContiguousElements(o)}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=Aa.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(k(r)&&(r=await r),!r)continue;let i=va(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Ta(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);k(s)&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=i.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 a=null,o=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>o&&(o=e.cuePoints.length,a=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);k(r)&&(r=await r),n(r);let i=e,a=va(r);n(a);let o=a.id;n(o===L.Cluster);let s=a.size,c=r.filePos;s===void 0&&(s=(await Sa(this.reader,c,sa,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,s);k(l)&&(l=await l);let u={segment:t,elementStartPos:i,elementEndPos:c+s,dataStartPos:c,timestamp:-1,trackData:/* @__PURE__ */ new Map};this.currentCluster=u,l&&(u.elementEndPos=this.readContiguousElements(l,sa));for(let[,e]of u.trackData){let t=e.track;n(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){let n=e.blocks[t];n.timestamp+=u.timestamp,r||=n.lacing!==Da.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===Da.None&&(i.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let a=e.blocks[e.presentationTimestamps[0].blockIndex],o=e.blocks[h(e.presentationTimestamps).blockIndex];e.startTimestamp=a.timestamp,e.endTimestamp=o.timestamp+o.duration;let s=E(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(s===-1||t.clusterPositionCache[s].elementStartPos!==i)&&t.clusterPositionCache.splice(s+1,0,{elementStartPos:u.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=u,u}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,t){for(let r=0;r<e.length;r++){let i=e[r];if(i.lacing===Da.None)continue;i.decoded||=(i.data=this.decodeBlockData(t,i.data),!0);let a=uu.tempFromBytes(i.data),o=[],s=H(a)+1;switch(i.lacing){case Da.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){let n=H(a);if(t+=n,n<255){o.push(t),e+=t;break}}}o.push(a.length-(a.bufferPos+e))}break;case Da.FixedSize:{let e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)o.push(t)}break;case Da.Ebml:{let e=ma(a);n(e!==null);let t=e;o.push(t);let r=t;for(let e=1;e<s-1;e++){let e=a.bufferPos,i=ma(a);n(i!==null);let s=i-((1<<(a.bufferPos-e)*7-1)-1);t+=s,o.push(t),r+=t}o.push(a.length-(a.bufferPos+r))}break;default:n(!1)}n(o.length===s),e.splice(r,1);let c=i.duration||s*(t.defaultDuration??0);for(let t=0;t<s;t++){let n=o[t],l=V(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:Da.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if((t.id!==L.Tags||e.tagsSeen)&&(t.id!==L.Attachments||e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(k(r)&&(r=await r),!r)continue;let i=va(r);if(!i||i.id!==t.id)continue;let{size:a}=i;Ta(a),n(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,a);k(o)&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,t.id===L.Tags?e.tagsSeen=!0:t.id===L.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let i=va(e);if(!i||t&&t.includes(i.id))return!1;let{id:o,size:s}=i,c=e.filePos;switch(Ta(s),o){case L.DocType:this.isWebM=ya(e,s)===`webm`;break;case L.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(c,s)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case L.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=R(e,s)}break;case L.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=R(e,s)}break;case L.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=R(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case L.Duration:if(!this.currentSegment)break;this.currentSegment.duration=xa(e,s);break;case L.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ut,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(c,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==Oa.Block||e.data.algorithm!==ka.HeaderStripping)&&(A._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===wa.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wa.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===wa.vp8)this.currentTrack.info.codec=`vp8`;else if(t===wa.vp9)this.currentTrack.info.codec=`vp9`;else if(t===wa.av1)this.currentTrack.info.codec=`av1`;else if(t===wa.prores){let e=this.currentTrack.codecPrivate?w.decode(this.currentTrack.codecPrivate):``;Mr.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new Pa(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===wa.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===wa.mp3?this.currentTrack.info.codec=`mp3`:t===wa.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ur):t===wa.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===wa.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===wa.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===wa.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===wa.dts?(this.currentTrack.info.codec=`dts`,this.currentTrack.codecId===`A_DTS/EXPRESS`?this.currentTrack.info.dtsFormat=`dtse`:this.currentTrack.codecId===`A_DTS/LOSSLESS`&&(this.currentTrack.info.dtsFormat=`dtsl`)):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 Fa(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case L.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=R(e,s);break;case L.TrackType:{if(!this.currentTrack)break;let t=R(e,s);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...fe},alphaMode:!1,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case L.FlagEnabled:if(!this.currentTrack)break;R(e,s)||(this.currentTrack=null);break;case L.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!R(e,s);break;case L.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!R(e,s);break;case L.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!R(e,s);break;case L.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!R(e,s);break;case L.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!R(e,s);break;case L.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!R(e,s);break;case L.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ya(e,s);break;case L.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,s);break;case L.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=R(e,s);break;case L.Name:if(!this.currentTrack)break;this.currentTrack.name=ba(e,s);break;case L.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ya(e,s),Ue(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case L.LanguageBCP47:{if(!this.currentTrack)break;let t=ya(e,s).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case L.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=R(e,s);break;case L.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=R(e,s);break;case L.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=R(e,s);break;case L.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=R(e,s);break;case L.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=R(e,s);break;case L.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=R(e,s)===1;break;case L.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=le[t];this.currentTrack.info.colorSpace.matrix=n}break;case L.Range:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s);this.currentTrack.info.colorSpace.fullRange=t===1||t===2?t===2:void 0}break;case L.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=se[t];this.currentTrack.info.colorSpace.transfer=n}break;case L.Primaries:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=ae[t];this.currentTrack.info.colorSpace.primaries=n}break;case L.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.ProjectionPoseYaw:{if(this.currentTrack?.info?.type!==`video`)break;let t=xa(e,s);try{let e=a(t);this.currentTrack.info.horizontalScale=Math.round(Math.cos(e*r))}catch{}}break;case L.ProjectionPosePitch:{if(this.currentTrack?.info?.type!==`video`)break;let t=xa(e,s);try{let e=a(t);this.currentTrack.info.verticalScale=Math.round(Math.cos(e*r))}catch{}}break;case L.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-xa(e,s);try{this.currentTrack.info.rotation=a(t)}catch{}}break;case L.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(c,s));break;case L.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=xa(e,s);break;case L.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=R(e,s);break;case L.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=R(e,s);break;case L.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(c,s)),this.currentCueTime=null;break;case L.CueTime:this.currentCueTime=R(e,s);break;case L.CueTrackPositions:{if(this.currentCueTime===null)break;n(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(c,s)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case L.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=R(e,s)}break;case L.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+R(e,s)}break;case L.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=R(e,s);break;case L.SimpleBlock:{if(!this.currentCluster)break;let t=ma(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=mu(e),i=H(e),a=i>>1&3,o=!!(i&128);n.track.info?.type===`audio`&&n.track.info.codec&&(o=!0);let l=V(e,s-(e.filePos-c)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:o,data:l,lacing:a,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case L.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(c,s)),this.currentBlock=null;break;case L.Block:{if(!this.currentCluster)break;let t=ma(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=mu(e),i=H(e)>>1&3,a=V(e,s-(e.filePos-c)),o=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:a,lacing:i,decoded:!o,postProcessed:!1,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case L.BlockAdditions:this.readContiguousElements(e.slice(c,s));break;case L.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(c,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case L.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,s);break;case L.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=R(e,s);break;case L.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=R(e,s);break;case L.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case L.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(c,s));break;case L.Targets:this.readContiguousElements(e.slice(c,s));break;case L.TargetTypeValue:R(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case L.TagTrackUID:case L.TagEditionUID:case L.TagChapterUID:case L.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case L.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(c,s));break;case L.TagName:this.currentSimpleTagName=ba(e,s);break;case L.TagString:{if(!this.currentSimpleTagName)break;let t=ba(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case L.TagBinary:{if(!this.currentSimpleTagName)break;let t=V(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case L.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(c,s));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Bt(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case L.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ha(e,s);break;case L.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ba(e,s);break;case L.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ya(e,s);break;case L.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,s);break;case L.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ba(e,s);break;case L.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(c,s)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case L.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Oa.Block,data:null},this.readContiguousElements(e.slice(c,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case L.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=R(e,s);break;case L.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=R(e,s);break;case L.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:ka.Zlib,settings:null},this.readContiguousElements(e.slice(c,s));break;case L.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=R(e,s);break;case L.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=V(e,s);break;case L.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=c+s,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let r=t;for(let t of e.decodingInstructions)if(n(t.data),t.data.type===`decompress`)switch(t.data.algorithm){case ka.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,n=new Uint8Array(e.length+r.length);n.set(e,0),n.set(r,e.length),r=n}}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`bpm`:{let e=Number.parseInt(t,10);Number.isInteger(e)&&e>0&&(n.beatsPerMinute??=e)}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)}}}getDurationFromMetadata(e){return e.duration<=0?null:e.duration/e.timestampFactor}},Na=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=/* @__PURE__ */ 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(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}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 Fe(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=E(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=Ce(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,t){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 t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return n(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];if(n(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);C(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?hi:i.data,o=i.timestamp/this.internalTrack.segment.timestampFactor,s=i.duration/this.internalTrack.segment.timestampFactor,c={};i.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?hi:i.mainAdditional,c.alphaByteLength=i.mainAdditional.byteLength);let l=new I(a,i.isKeyFrame?`key`:`delta`,o,s,e.dataStartPos+t,i.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,i,a){let{demuxer:o,segment:s}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,a);n!==-1&&(l=e,u=n)}let d=E(this.internalTrack.cuePoints,r,e=>e.time),f=d===-1?null:this.internalTrack.cuePoints[d],p=E(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(k(e)&&(e=await e),!e)break;let r=g,d=va(e);if(!d||!oa.includes(d.id)&&d.id!==L.Void){let e=await Ca(o.reader,r,oa,Math.min(s.elementEndPos??1/0,r+ja));if(e){g=e;continue}break}let f=d.id,p=d.size,m=e.filePos;if(f===L.Cluster){c=await o.readCluster(r,s),p=c.elementEndPos-m;let{blockIndex:e,correctBlockFound:n}=t(c);if(n)return this.fetchPacketInCluster(c,e,a);e!==-1&&(l=c,u=e)}p===void 0&&(n(f!==L.Cluster),p=(await Sa(o.reader,m,sa,s.elementEndPos)).pos-m);let h=m+p;if(s.elementEndPos===null){let e=o.reader.requestSliceRange(h,2,16);if(k(e)&&(e=await e),!e)break;if(ga(e)===L.Segment){s.elementEndPos=h;break}}g=h}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let e=this.internalTrack.cuePoints[d-1];n(!e||e.time<f.time);let r=e?.time??-1/0;return this.performClusterLookup(null,t,r,i,a)}return l?this.fetchPacketInCluster(l,u,a):null}},Pa=class extends Na{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){let e=this.internalTrack.info,t=p(f(e.horizontalScale,e.verticalScale),u(e.rotation));return s(t,e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}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===`prores`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let t={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?_n(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?On(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?Vn(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?Wn(e.data):null,proresCodecInfo:this.internalTrack.info.codec===`prores`&&e?Kn(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!ue(this.internalTrack.info.colorSpace)){let e=zr(t);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let n={codec:Rr(t),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},Fa=class extends Na{constructor(e){super(e),this.decoderConfigPromise=null}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&br(e.data)}return{codec:Vr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};
|
|
152
|
+
var Oa;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(Oa||={});var ka;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(ka||={});var Aa;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(Aa||={});const ja=[{id:L.SeekHead,flag:`seekHeadSeen`},{id:L.Info,flag:`infoSeen`},{id:L.Tracks,flag:`tracksSeen`},{id:L.Cues,flag:`cuesSeen`}],Ma=10*2**20;var Na=class extends mi{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 Da({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(k(t)&&(t=await t),!t)break;let n=ya(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===L.EBML){Ea(i);let e=this.reader.requestSlice(a,i);if(k(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===L.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===L.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await Ca(this.reader,a,ca,this.reader.fileSize)).pos-a);let e=h(this.segments);e&&(e.elementEndPos=a+i)}Ea(i),e=a+i}})()}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,r=/* @__PURE__ */ new Set;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let t=this.reader.requestSliceRange(n,2,16);if(k(t)&&(t=await t),!t)break;let i=n,a=ya(t);if(!a||!sa.includes(a.id)&&a.id!==L.Void){let e=await wa(this.reader,i,sa,Math.min(this.currentSegment.elementEndPos??1/0,i+Ma));if(e){n=e;continue}break}let{id:o,size:s}=a,c=t.filePos,l=ja.findIndex(e=>e.id===o);if(l!==-1){let t=ja[l].flag;this.currentSegment[t]=!0,o===L.SeekHead&&r.add(i-e),Ea(s);let n=this.reader.requestSlice(c,s);k(n)&&(n=await n),n&&this.readContiguousElements(n)}else if(o===L.Tags||o===L.Attachments){o===L.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ea(s);let e=this.reader.requestSlice(c,s);k(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(o===L.Cluster){this.currentSegment.clusterSeekStartPos=i;break}if(s===void 0)break;n=c+s}if(this.reader.fileSize!==null)for(;;){let t=this.currentSegment.seekEntries.find(e=>e.id===L.SeekHead&&!r.has(e.segmentPosition));if(!t)break;r.add(t.segmentPosition);let n=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(k(n)&&(n=await n),!n)continue;let i=ya(n);if(!i||i.id!==L.SeekHead)continue;let{size:a}=i;Ea(a);let o=this.reader.requestSlice(n.filePos,a);k(o)&&(o=await o),o&&this.readContiguousElements(o)}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=ja.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(k(r)&&(r=await r),!r)continue;let i=ya(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Ea(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);k(s)&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=i.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 a=null,o=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>o&&(o=e.cuePoints.length,a=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);k(r)&&(r=await r),n(r);let i=e,a=ya(r);n(a);let o=a.id;n(o===L.Cluster);let s=a.size,c=r.filePos;s===void 0&&(s=(await Ca(this.reader,c,ca,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,s);k(l)&&(l=await l);let u={segment:t,elementStartPos:i,elementEndPos:c+s,dataStartPos:c,timestamp:-1,trackData:/* @__PURE__ */ new Map};this.currentCluster=u,l&&(u.elementEndPos=this.readContiguousElements(l,ca));for(let[,e]of u.trackData){let t=e.track;n(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){let n=e.blocks[t];n.timestamp+=u.timestamp,r||=n.lacing!==Oa.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===Oa.None&&(i.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let a=e.blocks[e.presentationTimestamps[0].blockIndex],o=e.blocks[h(e.presentationTimestamps).blockIndex];e.startTimestamp=a.timestamp,e.endTimestamp=o.timestamp+o.duration;let s=E(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(s===-1||t.clusterPositionCache[s].elementStartPos!==i)&&t.clusterPositionCache.splice(s+1,0,{elementStartPos:u.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=u,u}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,t){for(let r=0;r<e.length;r++){let i=e[r];if(i.lacing===Oa.None)continue;i.decoded||=(i.data=this.decodeBlockData(t,i.data),!0);let a=du.tempFromBytes(i.data),o=[],s=H(a)+1;switch(i.lacing){case Oa.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){let n=H(a);if(t+=n,n<255){o.push(t),e+=t;break}}}o.push(a.length-(a.bufferPos+e))}break;case Oa.FixedSize:{let e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)o.push(t)}break;case Oa.Ebml:{let e=ha(a);n(e!==null);let t=e;o.push(t);let r=t;for(let e=1;e<s-1;e++){let e=a.bufferPos,i=ha(a);n(i!==null);let s=i-((1<<(a.bufferPos-e)*7-1)-1);t+=s,o.push(t),r+=t}o.push(a.length-(a.bufferPos+r))}break;default:n(!1)}n(o.length===s),e.splice(r,1);let c=i.duration||s*(t.defaultDuration??0);for(let t=0;t<s;t++){let n=o[t],l=V(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:Oa.None,decoded:!0,postProcessed:!1,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if((t.id!==L.Tags||e.tagsSeen)&&(t.id!==L.Attachments||e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(k(r)&&(r=await r),!r)continue;let i=ya(r);if(!i||i.id!==t.id)continue;let{size:a}=i;Ea(a),n(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,a);k(o)&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,t.id===L.Tags?e.tagsSeen=!0:t.id===L.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let i=ya(e);if(!i||t&&t.includes(i.id))return!1;let{id:o,size:s}=i,c=e.filePos;switch(Ea(s),o){case L.DocType:this.isWebM=ba(e,s)===`webm`;break;case L.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(c,s)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case L.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=R(e,s)}break;case L.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=R(e,s)}break;case L.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=R(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case L.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Sa(e,s);break;case L.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ut,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(c,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==ka.Block||e.data.algorithm!==Aa.HeaderStripping)&&(A._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===Ta.avc)this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Ta.hevc)this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Ta.vp8)this.currentTrack.info.codec=`vp8`;else if(t===Ta.vp9)this.currentTrack.info.codec=`vp9`;else if(t===Ta.av1)this.currentTrack.info.codec=`av1`;else if(t===Ta.prores){let e=this.currentTrack.codecPrivate?w.decode(this.currentTrack.codecPrivate):``;Mr.includes(e)&&(this.currentTrack.info.codec=`prores`,this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new Fa(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===Ta.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===Ta.mp3?this.currentTrack.info.codec=`mp3`:t===Ta.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ur):t===Ta.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ta.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ta.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ta.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ta.dts?(this.currentTrack.info.codec=`dts`,this.currentTrack.codecId===`A_DTS/EXPRESS`?this.currentTrack.info.dtsFormat=`dtse`:this.currentTrack.codecId===`A_DTS/LOSSLESS`&&(this.currentTrack.info.dtsFormat=`dtsl`)):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 Ia(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case L.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=R(e,s);break;case L.TrackType:{if(!this.currentTrack)break;let t=R(e,s);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...fe},alphaMode:!1,proresFormat:null}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case L.FlagEnabled:if(!this.currentTrack)break;R(e,s)||(this.currentTrack=null);break;case L.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!R(e,s);break;case L.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!R(e,s);break;case L.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!R(e,s);break;case L.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!R(e,s);break;case L.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!R(e,s);break;case L.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!R(e,s);break;case L.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ba(e,s);break;case L.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,s);break;case L.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=R(e,s);break;case L.Name:if(!this.currentTrack)break;this.currentTrack.name=xa(e,s);break;case L.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ba(e,s),Ue(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case L.LanguageBCP47:{if(!this.currentTrack)break;let t=ba(e,s).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case L.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=R(e,s);break;case L.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=R(e,s);break;case L.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=R(e,s);break;case L.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=R(e,s);break;case L.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=R(e,s);break;case L.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=R(e,s)===1;break;case L.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=le[t];this.currentTrack.info.colorSpace.matrix=n}break;case L.Range:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s);this.currentTrack.info.colorSpace.fullRange=t===1||t===2?t===2:void 0}break;case L.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=se[t];this.currentTrack.info.colorSpace.transfer=n}break;case L.Primaries:{if(this.currentTrack?.info?.type!==`video`)break;let t=R(e,s),n=ae[t];this.currentTrack.info.colorSpace.primaries=n}break;case L.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(c,s));break;case L.ProjectionPoseYaw:{if(this.currentTrack?.info?.type!==`video`)break;let t=Sa(e,s);try{let e=a(t);this.currentTrack.info.horizontalScale=Math.round(Math.cos(e*r))}catch{}}break;case L.ProjectionPosePitch:{if(this.currentTrack?.info?.type!==`video`)break;let t=Sa(e,s);try{let e=a(t);this.currentTrack.info.verticalScale=Math.round(Math.cos(e*r))}catch{}}break;case L.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-Sa(e,s);try{this.currentTrack.info.rotation=a(t)}catch{}}break;case L.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(c,s));break;case L.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=Sa(e,s);break;case L.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=R(e,s);break;case L.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=R(e,s);break;case L.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(c,s)),this.currentCueTime=null;break;case L.CueTime:this.currentCueTime=R(e,s);break;case L.CueTrackPositions:{if(this.currentCueTime===null)break;n(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(c,s)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case L.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=R(e,s)}break;case L.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+R(e,s)}break;case L.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=R(e,s);break;case L.SimpleBlock:{if(!this.currentCluster)break;let t=ha(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=hu(e),i=H(e),a=i>>1&3,o=!!(i&128);n.track.info?.type===`audio`&&n.track.info.codec&&(o=!0);let l=V(e,s-(e.filePos-c)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:o,data:l,lacing:a,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case L.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(c,s)),this.currentBlock=null;break;case L.Block:{if(!this.currentCluster)break;let t=ha(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=hu(e),i=H(e)>>1&3,a=V(e,s-(e.filePos-c)),o=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:a,lacing:i,decoded:!o,postProcessed:!1,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case L.BlockAdditions:this.readContiguousElements(e.slice(c,s));break;case L.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(c,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case L.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,s);break;case L.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=R(e,s);break;case L.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=R(e,s);break;case L.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case L.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(c,s));break;case L.Targets:this.readContiguousElements(e.slice(c,s));break;case L.TargetTypeValue:R(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case L.TagTrackUID:case L.TagEditionUID:case L.TagChapterUID:case L.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case L.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(c,s));break;case L.TagName:this.currentSimpleTagName=xa(e,s);break;case L.TagString:{if(!this.currentSimpleTagName)break;let t=xa(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case L.TagBinary:{if(!this.currentSimpleTagName)break;let t=V(e,s);this.processTagValue(this.currentSimpleTagName,t)}break;case L.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(c,s));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Bt(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case L.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ga(e,s);break;case L.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=xa(e,s);break;case L.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ba(e,s);break;case L.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,s);break;case L.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=xa(e,s);break;case L.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(c,s)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case L.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ka.Block,data:null},this.readContiguousElements(e.slice(c,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case L.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=R(e,s);break;case L.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=R(e,s);break;case L.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:Aa.Zlib,settings:null},this.readContiguousElements(e.slice(c,s));break;case L.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=R(e,s);break;case L.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=V(e,s);break;case L.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=c+s,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let r=t;for(let t of e.decodingInstructions)if(n(t.data),t.data.type===`decompress`)switch(t.data.algorithm){case Aa.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,n=new Uint8Array(e.length+r.length);n.set(e,0),n.set(r,e.length),r=n}}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`bpm`:{let e=Number.parseInt(t,10);Number.isInteger(e)&&e>0&&(n.beatsPerMinute??=e)}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)}}}getDurationFromMetadata(e){return e.duration<=0?null:e.duration/e.timestampFactor}},Pa=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=/* @__PURE__ */ 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(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}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 Fe(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=E(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=Ce(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,t){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 t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return n(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];if(n(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);C(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?hi:i.data,o=i.timestamp/this.internalTrack.segment.timestampFactor,s=i.duration/this.internalTrack.segment.timestampFactor,c={};i.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?hi:i.mainAdditional,c.alphaByteLength=i.mainAdditional.byteLength);let l=new I(a,i.isKeyFrame?`key`:`delta`,o,s,e.dataStartPos+t,i.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,i,a){let{demuxer:o,segment:s}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,a);n!==-1&&(l=e,u=n)}let d=E(this.internalTrack.cuePoints,r,e=>e.time),f=d===-1?null:this.internalTrack.cuePoints[d],p=E(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(k(e)&&(e=await e),!e)break;let r=g,d=ya(e);if(!d||!sa.includes(d.id)&&d.id!==L.Void){let e=await wa(o.reader,r,sa,Math.min(s.elementEndPos??1/0,r+Ma));if(e){g=e;continue}break}let f=d.id,p=d.size,m=e.filePos;if(f===L.Cluster){c=await o.readCluster(r,s),p=c.elementEndPos-m;let{blockIndex:e,correctBlockFound:n}=t(c);if(n)return this.fetchPacketInCluster(c,e,a);e!==-1&&(l=c,u=e)}p===void 0&&(n(f!==L.Cluster),p=(await Ca(o.reader,m,ca,s.elementEndPos)).pos-m);let h=m+p;if(s.elementEndPos===null){let e=o.reader.requestSliceRange(h,2,16);if(k(e)&&(e=await e),!e)break;if(_a(e)===L.Segment){s.elementEndPos=h;break}}g=h}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let e=this.internalTrack.cuePoints[d-1];n(!e||e.time<f.time);let r=e?.time??-1/0;return this.performClusterLookup(null,t,r,i,a)}return l?this.fetchPacketInCluster(l,u,a):null}},Fa=class extends Pa{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){let e=this.internalTrack.info,t=p(f(e.horizontalScale,e.verticalScale),u(e.rotation));return s(t,e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}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===`prores`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let t={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?_n(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?On(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?Vn(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?Wn(e.data):null,proresCodecInfo:this.internalTrack.info.codec===`prores`&&e?Kn(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!ue(this.internalTrack.info.colorSpace)){let e=zr(t);this.internalTrack.info.colorSpace.primaries??=e.primaries,this.internalTrack.info.colorSpace.transfer??=e.transfer,this.internalTrack.info.colorSpace.matrix??=e.matrix,this.internalTrack.info.colorSpace.fullRange??=e.fullRange}let n={codec:Rr(t),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}},Ia=class extends Pa{constructor(e){super(e),this.decoderConfigPromise=null}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.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`dts`&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&br(e.data)}return{codec:Vr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};
|
|
153
153
|
/*!
|
|
154
154
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
155
155
|
*
|
|
@@ -157,7 +157,7 @@ var Da;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`Fixe
|
|
|
157
157
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
158
158
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
159
159
|
*/
|
|
160
|
-
const
|
|
160
|
+
const La=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(k(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=W(o),i=e.fileSize===null?null:e.fileSize-a,s=li(n,i);if(s.header&&(!r||s.header.sampleRate===r.sampleRate&&s.header.mpegVersionId===r.mpegVersionId&&s.header.layer===r.layer&&pi(s.header.channel)===pi(r.channel)))return{header:s.header,startPos:a};o.filePos=t+s.bytesAdvanced,a=o.filePos}}return null};
|
|
161
161
|
/*!
|
|
162
162
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
163
163
|
*
|
|
@@ -165,7 +165,7 @@ const Ia=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===nu
|
|
|
165
165
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
166
166
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
167
167
|
*/
|
|
168
|
-
var
|
|
168
|
+
var Ra=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new me,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&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.trackBackings=[new za(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(k(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Mu(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await La(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=ci(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(k(r)&&(r=await r),r){let i=W(r);if(i===1483304551||i===1231971951){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+n+4,12);if(k(t)&&(t=await t),t){let e=V(t,12),n=C(e),r=n.getUint32(0,!1);this.xingData={frameCount:r&fi.FrameCount?n.getUint32(4,!1):null,fileSize:r&fi.FileSize?n.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,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(k(n)&&(n=await n),!n)break;let r=Mu(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(k(i)&&(i=await i),!i)break;Nu(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);k(e)&&(e=await e),n(e),G(e,3)===`TAG`&&Au(e,this.metadataTags)}return this.metadataTags}finally{e()}}},za=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return n(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(n(e.firstFrameHeader!==null),n(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=si(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 n(this.demuxer.firstFrameHeader),pi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Ut}}async getDecoderConfig(){return n(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:pi(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=hi;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(k(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new I(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=ye(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=E(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)}};
|
|
169
169
|
/*!
|
|
170
170
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
171
171
|
*
|
|
@@ -173,7 +173,7 @@ var La=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.f
|
|
|
173
173
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
174
174
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
175
175
|
*/
|
|
176
|
-
const
|
|
176
|
+
const Ba=/* @__PURE__ */ 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;Ba[e]=t>>>0&4294967295}const Va=e=>{let t=C(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^Ba[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},Ha=(e,t,r)=>{let i=0,a=null;if(e.length>0){if(t.codec===`vorbis`){n(t.vorbisInfo);let o=t.vorbisInfo.modeBlockflags.length,s=(1<<Be(o-1))-1<<1,c=(e[0]&s)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let l=r,u=t.vorbisInfo.modeBlockflags[c];if(a=t.vorbisInfo.blocksizes[u],u===1){let n=(s|1)+1,r=e[0]&n?1:0;l=t.vorbisInfo.blocksizes[r]}i=l===null?0:l+a>>2}else t.codec===`opus`&&(i=Yn(e).durationInSamples)}return{durationInSamples:i,vorbisBlockSize:a}},Ua=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Wa=65307,Ga=e=>{
|
|
177
177
|
/*!
|
|
178
178
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
179
179
|
*
|
|
@@ -181,7 +181,7 @@ const za=/* @__PURE__ */ new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24
|
|
|
181
181
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
182
182
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
183
183
|
*/
|
|
184
|
-
let t=e.filePos;if(
|
|
184
|
+
let t=e.filePos;if(_u(e)!==1399285583)return null;e.skip(1);let n=H(e),r=Cu(e),i=_u(e),a=_u(e),o=_u(e),s=H(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=H(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}},Ka=(e,t)=>{for(;e.filePos<t-3;){let t=_u(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};
|
|
185
185
|
/*!
|
|
186
186
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
187
187
|
*
|
|
@@ -189,7 +189,7 @@ let t=e.filePos;if(gu(e)!==1399285583)return null;e.skip(1);let n=H(e),r=Su(e),i
|
|
|
189
189
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
190
190
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
191
191
|
*/
|
|
192
|
-
var Ka=class extends mi{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(k(t)&&(t=await t),!t)break;let n=Wa(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 qa(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 s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=C(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:Xn(i.data).modeBlockflags},$n(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=qn(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Ur,t.codecInfo.opusInfo={preSkip:i.preSkip},$n(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(t<e.lacingValues.length);let r=0;for(let n=0;n<t;n++)r+=e.lacingValues[n];let i=e,a=r,o=t,s=[];outer:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);k(t)&&(t=await t),n(t);let c=V(t,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(k(t)&&(t=await t),!t)return null;let n=Wa(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(k(n)&&(n=await n),!n)return null;let r=Wa(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return Ha({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},qa=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=/* @__PURE__ */ new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new me,this.firstTimestampInSamplesPromise=null,this.internalSampleRate=e.codecInfo.codec===`opus`?Ur:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return n(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 n(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{...Ut,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let r=Va(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),{vorbisBlockSize:i}=r,{durationInSamples:a}=r;if(e.endPage.headerType&4&&e.endSegmentIndex===e.endPage.lacingValues.length-1){let n=this.granulePositionToTimestampInSamples(e.endPage.granulePosition);a=O(n-t.timestampInSamples,0,a)}let o=Math.max(t.timestampInSamples,0),s=Math.max(t.timestampInSamples+a,0),c=new I(n.metadataOnly?hi:e.data,`key`,o/this.internalSampleRate,(s-o)/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(c,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),c}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let e=this.granulePositionToTimestampInSamples(0);n(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return e;let r=null,i=0,a=null;for(;t;){let e=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);if(!e||(r??=e.endPage,e.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:n,vorbisBlockSize:o}=Va(e.data,this.bitstream.codecInfo,a);i+=n,a=o,t=await this.demuxer.findNextPacketStart(e)}return r?e+Math.max(r.granulePosition-i,0):e})()}async getFirstPacket(e){n(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=await this.getFirstTimestampInSamples(),i=await this.demuxer.readPacket(t.startPage,t.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,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=Fe(e*this.internalSampleRate),i=await this.getFirstTimestampInSamples();if(r===Math.max(i,0))return this.getFirstPacket(t);if(r<Math.max(i,0))return null;n(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let o=a.startPage,s=this.demuxer.reader.fileSize,c=[o];outer:for(;o.headerStartPos+o.totalSize<s;){let e=o.headerStartPos,t=Math.floor((e+s)/2),i=t;for(;;){let e=Math.min(i+Ua,s-27),a=this.demuxer.reader.requestSlice(i,e-i);if(k(a)&&(a=await a),n(a),!Ga(a,e)){if(s<=t+27)break outer;s=t+27;continue outer}let l=this.demuxer.reader.requestSliceRange(a.filePos,27,282);k(l)&&(l=await l),n(l);let u=Wa(l);n(u);let d=!1;if(u.serialNumber===this.bitstream.serialNumber)d=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);k(e)&&(e=await e),n(e);let t=V(e,u.totalSize);d=Ba(t)===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?s=u.headerStartPos:(o=u,c.push(u));continue outer}}let l=a.startPage;for(let e of c){if(e.granulePosition===o.granulePosition)break;(!l||e.headerStartPos>l.headerStartPos)&&(l=e)}let u=l,d=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==o.granulePosition;){let e=u.headerStartPos+u.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);k(t)&&(t=await t),n(t);let r=Wa(t);n(r),u=r,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}n(u.granulePosition!==-1);let f=null,p,m,h=u,g=0;if(u.headerStartPos===a.startPage.headerStartPos)p=i,m=!0,f=0;else{p=0,m=!1;for(let e=u.lacingValues.length-1;e>=0;e--)if(u.lacingValues[e]<255){f=e+1;break}if(f===null)throw Error(`Invalid page with granule position: no packets end on this page.`);g=f-1;let e={data:hi,endPage:h,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(e)){let e=Ya(d,u,f);n(e);let t=Ja(d,e.page,e.segmentIndex);t&&(u=t.page,f=t.segmentIndex)}else for(;;){let e=Ya(d,u,f);if(!e)break;let t=Ja(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,f=t.segmentIndex,e.page.headerStartPos!==h.headerStartPos){h=e.page,g=e.segmentIndex;break}}}let _=null,v=null;for(;u!==null;){n(f!==null);let e=await this.demuxer.readPacket(u,f);if(!e)break;if(!(u.headerStartPos===a.startPage.headerStartPos&&f<a.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p,vorbisLastBlocksize:v?.vorbisBlockSize??null},t);n(i);let a=this.encodedPacketToMetadata.get(i);if(n(a),!m&&e.endPage.headerStartPos===h.headerStartPos&&e.endSegmentIndex===g?(p=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p-a.durationInSamples,vorbisLastBlocksize:v?.vorbisBlockSize??null},t),n(i),a=this.encodedPacketToMetadata.get(i),n(a)):p+=a.durationInSamples,_=i,v=a,m&&(Math.max(p,0)>r||Math.max(a.timestampInSamples,0)===r))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;u=i.startPage,f=i.startSegmentIndex}return _}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let r=Fe(e*this.internalSampleRate);e=r/this.internalSampleRate;let i=E(this.sequentialScanCache,r,e=>e.timestampInSamples),a;if(i!==-1){let e=this.sequentialScanCache[i];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else if(a=await this.getFirstPacket(t),a&&a.timestamp>e)return null;let o=0;for(;a&&a.timestamp<e;){let r=await this.getNextPacket(a,t);if(!r||r.timestamp>e)break;if(a=r,o++,o===100){o=0;let e=this.encodedPacketToMetadata.get(a);n(e),this.sequentialScanCache.length>0&&n(h(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};const Ja=(e,t,r)=>{let i=t,a=r;outer:for(;;){for(a--;a>=0;a--)if(i.lacingValues[a]<255){a++;break outer}if(n(a===-1),!(i.headerType&1)){a=0;break}let t=Se(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,a=i.lacingValues.length}if(n(a!==-1),a===i.lacingValues.length){let t=e[e.indexOf(i)+1];n(t),i=t,a=0}return{page:i,segmentIndex:a}},Ya=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=Se(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};
|
|
192
|
+
var qa=class extends mi{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(k(t)&&(t=await t),!t)break;let n=Ga(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 Ja(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 s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=C(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:Xn(i.data).modeBlockflags},$n(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=qn(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Ur,t.codecInfo.opusInfo={preSkip:i.preSkip},$n(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(t<e.lacingValues.length);let r=0;for(let n=0;n<t;n++)r+=e.lacingValues[n];let i=e,a=r,o=t,s=[];outer:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);k(t)&&(t=await t),n(t);let c=V(t,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(k(t)&&(t=await t),!t)return null;let n=Ga(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(k(n)&&(n=await n),!n)return null;let r=Ga(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return Ua({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ja=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=/* @__PURE__ */ new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new me,this.firstTimestampInSamplesPromise=null,this.internalSampleRate=e.codecInfo.codec===`opus`?Ur:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return n(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 n(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{...Ut,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let r=Ha(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),{vorbisBlockSize:i}=r,{durationInSamples:a}=r;if(e.endPage.headerType&4&&e.endSegmentIndex===e.endPage.lacingValues.length-1){let n=this.granulePositionToTimestampInSamples(e.endPage.granulePosition);a=O(n-t.timestampInSamples,0,a)}let o=Math.max(t.timestampInSamples,0),s=Math.max(t.timestampInSamples+a,0),c=new I(n.metadataOnly?hi:e.data,`key`,o/this.internalSampleRate,(s-o)/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(c,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),c}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let e=this.granulePositionToTimestampInSamples(0);n(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return e;let r=null,i=0,a=null;for(;t;){let e=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);if(!e||(r??=e.endPage,e.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:n,vorbisBlockSize:o}=Ha(e.data,this.bitstream.codecInfo,a);i+=n,a=o,t=await this.demuxer.findNextPacketStart(e)}return r?e+Math.max(r.granulePosition-i,0):e})()}async getFirstPacket(e){n(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=await this.getFirstTimestampInSamples(),i=await this.demuxer.readPacket(t.startPage,t.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,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=Fe(e*this.internalSampleRate),i=await this.getFirstTimestampInSamples();if(r===Math.max(i,0))return this.getFirstPacket(t);if(r<Math.max(i,0))return null;n(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let o=a.startPage,s=this.demuxer.reader.fileSize,c=[o];outer:for(;o.headerStartPos+o.totalSize<s;){let e=o.headerStartPos,t=Math.floor((e+s)/2),i=t;for(;;){let e=Math.min(i+Wa,s-27),a=this.demuxer.reader.requestSlice(i,e-i);if(k(a)&&(a=await a),n(a),!Ka(a,e)){if(s<=t+27)break outer;s=t+27;continue outer}let l=this.demuxer.reader.requestSliceRange(a.filePos,27,282);k(l)&&(l=await l),n(l);let u=Ga(l);n(u);let d=!1;if(u.serialNumber===this.bitstream.serialNumber)d=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);k(e)&&(e=await e),n(e);let t=V(e,u.totalSize);d=Va(t)===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?s=u.headerStartPos:(o=u,c.push(u));continue outer}}let l=a.startPage;for(let e of c){if(e.granulePosition===o.granulePosition)break;(!l||e.headerStartPos>l.headerStartPos)&&(l=e)}let u=l,d=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==o.granulePosition;){let e=u.headerStartPos+u.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);k(t)&&(t=await t),n(t);let r=Ga(t);n(r),u=r,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}n(u.granulePosition!==-1);let f=null,p,m,h=u,g=0;if(u.headerStartPos===a.startPage.headerStartPos)p=i,m=!0,f=0;else{p=0,m=!1;for(let e=u.lacingValues.length-1;e>=0;e--)if(u.lacingValues[e]<255){f=e+1;break}if(f===null)throw Error(`Invalid page with granule position: no packets end on this page.`);g=f-1;let e={data:hi,endPage:h,endSegmentIndex:g};if(await this.demuxer.findNextPacketStart(e)){let e=Xa(d,u,f);n(e);let t=Ya(d,e.page,e.segmentIndex);t&&(u=t.page,f=t.segmentIndex)}else for(;;){let e=Xa(d,u,f);if(!e)break;let t=Ya(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,f=t.segmentIndex,e.page.headerStartPos!==h.headerStartPos){h=e.page,g=e.segmentIndex;break}}}let _=null,v=null;for(;u!==null;){n(f!==null);let e=await this.demuxer.readPacket(u,f);if(!e)break;if(!(u.headerStartPos===a.startPage.headerStartPos&&f<a.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p,vorbisLastBlocksize:v?.vorbisBlockSize??null},t);n(i);let a=this.encodedPacketToMetadata.get(i);if(n(a),!m&&e.endPage.headerStartPos===h.headerStartPos&&e.endSegmentIndex===g?(p=this.granulePositionToTimestampInSamples(u.granulePosition),m=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:p-a.durationInSamples,vorbisLastBlocksize:v?.vorbisBlockSize??null},t),n(i),a=this.encodedPacketToMetadata.get(i),n(a)):p+=a.durationInSamples,_=i,v=a,m&&(Math.max(p,0)>r||Math.max(a.timestampInSamples,0)===r))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;u=i.startPage,f=i.startSegmentIndex}return _}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let r=Fe(e*this.internalSampleRate);e=r/this.internalSampleRate;let i=E(this.sequentialScanCache,r,e=>e.timestampInSamples),a;if(i!==-1){let e=this.sequentialScanCache[i];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else if(a=await this.getFirstPacket(t),a&&a.timestamp>e)return null;let o=0;for(;a&&a.timestamp<e;){let r=await this.getNextPacket(a,t);if(!r||r.timestamp>e)break;if(a=r,o++,o===100){o=0;let e=this.encodedPacketToMetadata.get(a);n(e),this.sequentialScanCache.length>0&&n(h(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};const Ya=(e,t,r)=>{let i=t,a=r;outer:for(;;){for(a--;a>=0;a--)if(i.lacingValues[a]<255){a++;break outer}if(n(a===-1),!(i.headerType&1)){a=0;break}let t=Se(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,a=i.lacingValues.length}if(n(a!==-1),a===i.lacingValues.length){let t=e[e.indexOf(i)+1];n(t),i=t,a=0}return{page:i,segmentIndex:a}},Xa=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=Se(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};
|
|
193
193
|
/*!
|
|
194
194
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
195
195
|
*
|
|
@@ -197,7 +197,7 @@ var Ka=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.b
|
|
|
197
197
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
198
198
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
199
199
|
*/
|
|
200
|
-
var
|
|
200
|
+
var Za;(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`})(Za||={});var Qa=class extends mi{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);k(e)&&(e=await e),n(e);let t=G(e,4),r=t!==`RIFX`,i=t===`RF64`,a=gu(e,r),o=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if(G(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(k(e)&&(e=await e),!e)break;let t=G(e,4),n=gu(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(k(e)&&(e=await e),!e)break;let t=bu(e,r);c=bu(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 eo(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(k(r)&&(r=await r),!r)return;let i=pu(r,n),a=pu(r,n),o=gu(r,n);r.skip(4);let s=pu(r,n),c;if(c=t===14?8:pu(r,n),t>=18&&i!==357){let e=pu(r,n),a=t-18;if(Math.min(a,e)>=22&&i===Za.EXTENSIBLE){r.skip(6);let e=V(r,16);i=e[0]|e[1]<<8}}if((i===Za.MULAW||i===Za.ALAW)&&(c=8),i!==Za.PCM&&i!==Za.IEEE_FLOAT&&i!==Za.ALAW&&i!==Za.MULAW)throw Error(`Unsupported WAVE codec (format tag ${i}). Only integer/float PCM, A-law, and μ-law are supported.`);if(i===Za.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===Za.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(k(r)&&(r=await r),!r)return;let i=G(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=G(r,4),t=gu(r,n),i=V(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}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(k(n)&&(n=await n),!n)return;let r=Mu(n);if(r){let i=t-10;if(r.size=Math.min(r.size,i),r.size>0){let t=n.slice(e+10,r.size);Nu(t,r,this.metadataTags)}}}getCodec(){if(n(this.audioInfo),this.audioInfo.format===Za.MULAW)return`ulaw`;if(this.audioInfo.format===Za.ALAW)return`alaw`;if(this.audioInfo.format===Za.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===Za.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return`pcm-f32`;if(this.audioInfo.sampleSizeInBytes===8)return`pcm-f64`}n(!1)}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}};const $a=2048;var eo=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(n(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return n(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 n(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{...Ut}}async getPacketAtIndex(e,t){n(e>=0),n(this.demuxer.audioInfo);let r=e*$a*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let i=Math.min($a*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(k(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=hi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);k(e)&&(e=await e),n(e),a=V(e,i)}let o=e*$a/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 I(a,`key`,o,s,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){n(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/$a,(this.demuxer.dataSize-1)/($a*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let i=await this.getPacketAtIndex(r,t);if(i)return i;if(r===0)return null;n(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){let e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){n(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/$a);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}};
|
|
201
201
|
/*!
|
|
202
202
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
203
203
|
*
|
|
@@ -205,7 +205,7 @@ var Xa;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=
|
|
|
205
205
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
206
206
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
207
207
|
*/
|
|
208
|
-
const
|
|
208
|
+
const to=e=>{let t=e.filePos,n=new j(V(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}},no=1024
|
|
209
209
|
/*!
|
|
210
210
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
211
211
|
*
|
|
@@ -213,7 +213,7 @@ const eo=e=>{let t=e.filePos,n=new j(V(e,9));if(n.readBits(12)!==4095||(n.skipBi
|
|
|
213
213
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
214
214
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
215
215
|
*/
|
|
216
|
-
;var
|
|
216
|
+
;var ro=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new me,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();n(this.firstFrameHeader),this.trackBackings=[new io(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(k(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Mu(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(k(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=to(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let r=Gt[t.samplingFrequencyIndex];n(r!==void 0);let i=no/r,a={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=no,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(k(t)&&(t=await t),!t)break;let n=Mu(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(k(r)&&(r=await r),!r)break;Nu(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},io=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/no}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 n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){n(this.demuxer.firstFrameHeader);let e=Kt[this.demuxer.firstFrameHeader.channelConfiguration];return n(e!==void 0),e}getSampleRate(){n(this.demuxer.firstFrameHeader);let e=Gt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return n(e!==void 0),e}getDisposition(){return{...Ut}}async getDecoderConfig(){return n(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=hi;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(k(e)&&(e=await e),!e)return null;r=V(e,n.dataSize)}return new I(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=ye(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=E(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)}};
|
|
217
217
|
/*!
|
|
218
218
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
219
219
|
*
|
|
@@ -221,7 +221,7 @@ const eo=e=>{let t=e.filePos,n=new j(V(e,9));if(n.readBits(12)!==4095||(n.skipBi
|
|
|
221
221
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
222
222
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
223
223
|
*/
|
|
224
|
-
const
|
|
224
|
+
const ao=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,oo=(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}},so=e=>{let t=0,n=new j(V(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new j(V(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)},co=(e,t)=>{if(t===`uncommon-u16`)return U(e)+1;if(t===`uncommon-u8`)return H(e)+1;if(typeof t==`number`)return t;Ee(t),n(!1)},lo=(e,t)=>t===`uncommon-u16`?U(e):t===`uncommon-u16-10`?U(e)*10:t===`uncommon-u8`?H(e):typeof t==`number`?t:null,uo=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};
|
|
225
225
|
/*!
|
|
226
226
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
227
227
|
*
|
|
@@ -229,7 +229,7 @@ const io=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`
|
|
|
229
229
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
230
230
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
231
231
|
*/
|
|
232
|
-
var
|
|
232
|
+
var fo=class extends mi{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 me,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),n(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(k(t)&&(t=await t),!t){this.lastSampleLoaded=!0;return}let r=Mu(t);if(!r)break;let i=this.reader.requestSlice(t.filePos,r.size);k(i)&&(i=await i),n(i),Nu(i,r,this.metadataTags),e=t.filePos+r.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(k(t)&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);n(t);let r=H(t),i=mu(t),a=!!(r&128);switch(r&127){case Qn.STREAMINFO:{let t=this.reader.requestSlice(e,i);if(k(t)&&(t=await t),n(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let r=V(t,34),a=new j(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=/* @__PURE__ */ 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 po(this);break}case Qn.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,i);k(t)&&(t=await t),n(t),$n(V(t,i),this.metadataTags);break}case Qn.PICTURE:{let t=this.reader.requestSlice(e,i);k(t)&&(t=await t),n(t);let r=W(t),a=W(t),o=w.decode(V(t,a)),s=W(t),c=w.decode(V(t,s));t.skip(16);let l=W(t),u=V(t,l);this.metadataTags.images??=[],this.metadataTags.images.push({data:u,mimeType:o,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,description:c});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:t}){n(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:t});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(H(o)===255){let t=o.filePos;if(H(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:t}){let r=e.filePos,i=new j(V(e,4));if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){n(t);let e=i.readBits(1);this.blockingBit=e}else if(this.blockingBit===1){if(n(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(n(!t),i.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let a=ao(i.readBits(4));if(!a)return null;n(this.audioInfo);let o=oo(i.readBits(4),this.audioInfo.sampleRate);if(!o||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let s=so(e),c=co(e,a),l=lo(e,o);if(l===null||l!==this.audioInfo.sampleRate)return null;let u=e.filePos-r,d=H(e);return e.skip(-u),e.skip(-1),d===uo(V(e,u))?{num:s,blockSize:c,sampleRate:l}:null}async advanceReader(){await this.readMetadata(),n(this.lastLoadedPos!==null),n(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},po=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return n(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 n(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ut}}async getDecoderConfig(){return n(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(n(this.demuxer.audioInfo),e<0)return null;let r=await this.demuxer.readingMutex.acquire();try{for(;;){let n=E(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];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,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}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,t){let r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=hi;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(k(e)&&(e=await e),!e)return null;i=V(e,r.byteSize)}n(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,o=r.blockSize/this.demuxer.audioInfo.sampleRate;return new I(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)}};
|
|
233
233
|
/*!
|
|
234
234
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
235
235
|
*
|
|
@@ -237,7 +237,7 @@ var uo=class extends mi{constructor(e){super(e),this.loadedSamples=[],this.metad
|
|
|
237
237
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
238
238
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
239
239
|
*/
|
|
240
|
-
const
|
|
240
|
+
const mo=9e4,ho=2**33,go=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},_o=`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.`,vo=/* @__PURE__ */ new Set([133,134,162]),yo=/* @__PURE__ */ new Set
|
|
241
241
|
/*!
|
|
242
242
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
243
243
|
*
|
|
@@ -245,7 +245,7 @@ const po=9e4,mo=2**33,ho=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))
|
|
|
245
245
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
246
246
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
247
247
|
*/
|
|
248
|
-
;var yo=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);k(e)&&(e=await e),n(e);let t=V(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[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 t=await this.readSection(r,!0,!o);if(!t)break;let s=!1;if(!o&&t.pid!==0&&(t.payload[0]!==0||t.payload[1]!==0||t.payload[2]!==1)){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),s=e.readBits(8)===2}if(t.pid===0&&!a){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),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((t.pid===i||s)&&!o){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10),a=e.pos+8*i,s=!1;for(;e.pos<a;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===5&&n>=4){let t=e.readBits(32);s||=t===1212435798||t===1212436562}e.pos=r}for(e.pos=a;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,c=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===106)a=!0;else if(t===122||t===204)o=!0;else if(t===123)c=!0;else if(t===5&&n>=4){let t=e.readBits(32);c||=(t&4294967040)==1146376960}e.pos=r}let l=null,u=s&&_o.has(t)?130:t;switch(u){case 27:case 36:l={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:case 130:case 138:{let e;e=u===3||u===4?`mp3`:u===15?`aac`:u===129?`ac3`:u===135?`eac3`:`dts`,l={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?l={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:a?l={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:c&&(l={type:`audio`,codec:`dts`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:vo.has(t)||(A._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),vo.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}o=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);outer:if(e&&!e.initialized){let r=xo(this,t,!0);if(!r)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=t.randomAccessIndicator===1,this.input._initInput){let n=(await this.input._initInput._getDemuxer()).elementaryStreams.find(n=>n.pid===t.pid&&n.info.codec===e.info.codec);if(n){e.info=n.info,e.initialized=!0;break outer}}let i=new Eo(e,r);if(e.info.type===`video`){for(;;){let t=i;if(t.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=_n(i.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];n(t);let r=xn(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=e.info.height,a>0&&o>0&&(a>o?e.info.squarePixelWidth=Math.round(e.info.width*a/o):e.info.squarePixelHeight=Math.round(e.info.height*o/a)),e.info.colorSpace={primaries:ae[r.colourPrimaries],transfer:se[r.transferCharacteristics],matrix:le[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}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=On(i.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===M.SPS_NUT).nalUnits[0];n(t);let r=Dn(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=e.info.height,a>0&&o>0&&(a>o?e.info.squarePixelWidth=Math.round(e.info.width*a/o):e.info.squarePixelHeight=Math.round(e.info.height*o/a)),e.info.colorSpace={primaries:ae[r.colourPrimaries],transfer:se[r.transferCharacteristics],matrix:le[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:Rr({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=uu.tempFromBytes(i.suppliedPacket.data),n=eo(t);if(!n)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:n.objectType},e.info.numberOfChannels=Kt[n.channelConfiguration],e.info.sampleRate=Gt[n.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=W(uu.tempFromBytes(i.suppliedPacket.data)),n=li(t,i.suppliedPacket.data.byteLength);if(!n.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=pi(n.header.channel),e.info.sampleRate=n.header.sampleRate}else if(e.info.codec===`ac3`){let t=nr(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=tr[t.acmod]+t.lfeon,e.info.sampleRate=nn[t.fscod]}else if(e.info.codec===`eac3`){let t=sr(i.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=lr(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=ur(t),e.info.sampleRate=n}else if(e.info.codec===`dts`){let t=yr(i.suppliedPacket.data);if(!t)throw Error(`Invalid DTS audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?`dtsh`:`dtsc`)}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:Vr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),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.initialized&&(e.info.type===`video`?this.trackBackingEntries.push(new Co(e)):this.trackBackingEntries.push(new wo(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return ho(e)}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(ye(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=E(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(k(t)&&(t=await t),!t)return null;if(H(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=U(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=H(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(k(t)&&(t=await t),!t)return null;let n=V(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)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let t=60*po;this.timestampWrapInfo={reference:e-t,offset:e>=mo-t?-mo:mo}}let{reference:t,offset:n}=this.timestampWrapInfo;return n<0&&e>=t||n>0&&e<t?e+n:e}};const bo=(e,t,n)=>{if(t.payload.byteLength<3)return null;let r=new j(t.payload);if(r.readBits(24)!==1)return null;let i=r.readBits(8);if(r.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;r.skipBits(8);let a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=e.normalizeTimestamp(o);else if(n)throw Error(go);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},xo=(e,t,r)=>{n(t.endPos!==null);let i=bo(e,t,r);if(!i)return null;let a=new j(t.payload);a.skipBits(32);let o=a.readBits(16);a.skipBits(16);let s=a.readBits(8),c=a.pos+8*s;a.pos=c;let l=c/8;n(Number.isInteger(l));let u=t.payload.subarray(l,o>0?6+o:t.payload.byteLength);return{...i,data:u}};var So=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=/* @__PURE__ */ new WeakMap,this.packetSectionStarts=/* @__PURE__ */ new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,i=0;for(let a of t.trackBackingEntries)if(a.getType()===r&&i++,n(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{...Ut,primary:!1}}getTimeResolution(){return po}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 I(n.metadataOnly?hi:e.data,r,e.pts/po,Math.max(t/po,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;n(t);let r=xo(this.elementaryStream.demuxer,t,!0);n(r);let i=new Eo(this.elementaryStream,r),a=new Do(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,t){let r=this.packetBuffers.get(e);if(r){let n=await r.readNext();if(!n)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(n.packet,n.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,n.packet.sectionStartPos),i}let i=this.packetSectionStarts.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);let a=this.elementaryStream.demuxer,o=await a.readSection(i,!0);n(o);let s=xo(a,o,!0);n(s);let c=new Eo(this.elementaryStream,s);r=new Do(this,c);let l=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){let n=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(n,r),this.packetSectionStarts.set(n,e.packet.sectionStartPos),n}}}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,t,r){let i=Fe(e*po),a=this.elementaryStream.demuxer,{reader:o,seekChunkSize:s}=a,c=this.elementaryStream.pid,l=async(e,t,n)=>{let r=e;for(;r<t;){let e=await a.readPacketHeader(r);if(!e)return null;if(e.pid===c&&e.payloadUnitStartIndicator===1){let e=await a.readSection(r,n);if(!e)return null;let t=bo(a,e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=a.packetStride}return null},u=this.elementaryStream.firstSection;n(u);let d=bo(a,u,!0);if(n(d),i<d.pts)return null;let f,p=this.elementaryStream.referencePesPackets,m=E(p,i,e=>e.pts),g=m===-1?null:p[m];if(g&&i-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(o.fileSize!==null){let t=Math.ceil(o.fileSize/s);if(t>1){let n=0,r=t-1;for(e=n;n<=r;){let t=Math.floor((n+r)/2),o=Re(t*s,a.packetStride)+d.sectionStartPos,c=await l(o,o+s,!1);if(!c){r=t-1;continue}c.pesPacketHeader.pts<=i?(e=t,n=t+1):r=t-1}}}f=Re(e*s,a.packetStride)+d.sectionStartPos}let _=(await l(f,o.fileSize??1/0,!1))?.pesPacketHeader??null;_||=d;let v=this.getReorderSize(),y=async(e,t)=>{let o=await a.readSection(e,!0);n(o);let s=xo(a,o,!0);n(s);let c=new Eo(this.elementaryStream,s),l=new Do(this,c);for(;!((h(l.presentationOrderPackets)?.pts??-1/0)>=i||!await l.readNextPacket()););let u=Ce(l.presentationOrderPackets,t);if(u===-1)return null;let d=l.presentationOrderPackets[u],f=u===0?0:d.pts-l.presentationOrderPackets[u-1].pts;for(;l.decodeOrderPackets[0]!==d;)l.decodeOrderPackets.shift();l.lastDuration=f;let p=await l.readNext();n(p);let m=this.createEncodedPacket(p.packet,p.duration,r);return this.packetBuffers.set(m,l),this.packetSectionStarts.set(m,p.packet.sectionStartPos),m};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=_.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=bo(a,t,!1);if(e&&e.pts!==null){if(e.pts>i)break outer;_=e,To(this.elementaryStream,_);break}}}e+=a.packetStride}}outer:for(let e=0;e<v+1;e++){let e=_.sectionStartPos-a.packetStride;for(;e>=a.packetOffset;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=bo(a,t,!1);if(e&&e.pts!==null){_=e;break}}}e-=a.packetStride}}return y(_.sectionStartPos,e=>e.pts<=i)}{let e=f,t=null,r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let f=null,p=e<=d.sectionStartPos,m,h=null;if(p)m=d,h=u;else{let t=await l(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,h=t?.section??null}let g=!1,_=0;outer:for(;m&&!(t!==null&&m.sectionStartPos>=t);){if(m.pts<=i){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=m.randomAccessIndicator===1;else{n(h);let t=xo(a,h,!0);n(t);let r=new Eo(this.elementaryStream,t);await r.markNextPacket(),e=r.suppliedPacket?.randomAccessIndicator===1}e&&(f=m)}if(m.pts>i&&(g=!0),g&&(_++,_>v))break;let e=m.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,r);if(t){let e=bo(a,t,!1);if(e&&e.pts!==null){m=e,h=t,To(this.elementaryStream,m);break}}}e+=a.packetStride}}if(f){let e=f;if(_===0)outer:for(let t=0;t<v;t++){let t=e.sectionStartPos-a.packetStride;for(;t>=a.packetOffset;){let n=await a.readPacketHeader(t);if(!n)break outer;if(n.pid===c&&n.payloadUnitStartIndicator===1){let n=await a.readSection(t,r);if(n){let t=bo(a,n,!1);if(t&&t.pts!==null){e=t;break}}}t-=a.packetStride}}let t=await y(e.sectionStartPos,e=>e.pts<=i&&e.randomAccessIndicator===1);return n(t),t}if(p)return null;t=e,e=Math.max(Re(e-d.sectionStartPos-s,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Co=class extends So{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}getTransformationMatrix(){return[...o]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},wo=class extends So{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}};const To=(e,t)=>{let n=e.referencePesPackets,r=E(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 Eo=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 n(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=h(this.pesPackets).sectionEndPos;for(n(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=xo(this.demuxer,n,!1);if(r){e=r;break}}t+=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++}getPesPacketAt(e){n(e<=this.currentPos);let t=this.currentPesPacketIndex,r=this.currentPesPacketPos;for(;e<r;)t--,r-=this.pesPackets[t].data.byteLength;return this.pesPackets[t]}async markNextPacket(){n(!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,i=null,a=!1,o=null,s=0;for(;;){let e=this.ensureBuffered(n);if(k(e)&&(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;i??=g;let _=d+h,y=_+r;if(y+(t===`avc`?6:1)>u){this.seekTo(n);break}let b=l[_],x,S,C;if(t===`avc`)x=un(b),S=x===on.NON_IDR_SLICE||x===on.SLICE_DPA||x===on.IDR,C=x===on.SEI||x===on.SPS||x===on.PPS||x===on.AUD;else{if(x=En(b),((b&1)<<5|l[_+1]>>3)>0){d+=h;continue}S=x<=M.RASL_R||x>=M.BLA_W_LP&&x<=21,C=x>=M.VPS_NUT&&x<=37||x===M.PREFIX_SEI_NUT||x>=41&&x<=44||x>=48&&x<=55}let ee=!1;if(S){let e;if(t===`avc`){let t=l.subarray(y,y+6),n=v(new j(t));e=!a||n<=s,s=n}else e=l[y]>>7==1;e&&(a?ee=!0:(a=!0,o=this.getPesPacketAt(c+_).pts))}else C&&a&&(ee=!0);if(ee){let e=g-i;return this.seekTo(i),this.supplyPacket(e,0,o)}d+=h}if(e<n)break}if(i!==null&&this.endPos>i){let e=this.endPos-i;return this.seekTo(i),this.supplyPacket(e,0,o)}}else{let t=e.info.codec;for(;;){let r=this.ensureBuffered(128);k(r)&&(r=await r);let i=this.currentPos;for(;this.currentPos-i<r;){let r=this.readU8();if(t===`aac`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(9);if(k(n)&&(n=await n),n<9)return;let i=this.readBytes(9),a=eo(uu.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return k(n)&&(n=await n),this.supplyPacket(n,Math.round(to*po/e.info.sampleRate))}this.seekTo(t+1)}else if(t===`mp3`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(4);if(k(n)&&(n=await n),n<4)return;let i=this.readBytes(4),a=C(i).getUint32(0),o=li(a,null);if(o.header){this.seekTo(t);let n=this.ensureBuffered(o.header.totalSize);k(n)&&(n=await n);let r=o.header.audioSamplesInFrame*po/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}this.seekTo(t+1)}else if(t===`ac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(5);if(k(i)&&(i=await i),i<5)return;let a=this.readBytes(5);if(a[0]!==11||a[1]!==119){this.seekTo(t+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){this.seekTo(t+1);continue}let c=rr[3*s+o];n(c!==void 0),this.seekTo(t),i=this.ensureBuffered(c),k(i)&&(i=await i);let l=Math.round(1536*po/e.info.sampleRate);return this.supplyPacket(i,l)}else if(t===`eac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(5);if(k(n)&&(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=i[4]>>6==3?3:i[4]>>4&3,s=or[o];this.seekTo(t),n=this.ensureBuffered(a),k(n)&&(n=await n);let c=s*256,l=Math.round(c*po/e.info.sampleRate);return this.supplyPacket(n,l)}else if(t===`dts`){if(r!==127&&r!==100)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(18);if(k(n)&&(n=await n),n<18)return;let i=this.readBytes(18),a=xr(i),o=a?null:Sr(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,4096),n=this.ensureBuffered(e);k(n)&&(n=await n),o=Sr(this.readBytes(n))??o}let s=a?a.frameSize:o.frameSize;if(a){let e=Math.ceil(a.frameSize/4)*4;for(;;){this.seekTo(t);let n=e+10,r=this.ensureBuffered(n);if(k(r)&&(r=await r),r<n)break;this.seekTo(t+e);let i=Sr(this.readBytes(10));if(!i)break;e+=i.frameSize,s=e}}let c=a?.sampleCount??o.asset?.sampleCount;if(c===void 0){this.seekTo(t+1);continue}this.seekTo(t),n=this.ensureBuffered(s),k(n)&&(n=await n);let l=Math.round(c*po/e.info.sampleRate);return this.supplyPacket(n,l)}else throw Error(`Unhandled.`)}if(r<128)break}}}supplyPacket(e,t,r=null){let i=this.getCurrentPesPacket(),a;if(r!==null)a=r;else if(this.lastSuppliedPesPacket===i)n(this.nextPts!==null),a=this.nextPts;else{if(i.pts===null)throw Error(go);a=i.pts,To(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=a+t;let o=i.sectionStartPos,s=o+(this.currentPos-this.currentPesPacketPos),c=this.readBytes(e),l=i.randomAccessIndicator;if(l===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)l=1;else if(this.elementaryStream.info.decoderConfig){let e=Zn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,c)===`key`;l=Number(e)}}this.suppliedPacket={pts:a,data:c,sequenceNumber:s,sectionStartPos:o,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Do=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),n(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);n(t!==-1);let r;for(t===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[t+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(n(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}};
|
|
248
|
+
;var bo=class extends mi{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);k(e)&&(e=await e),n(e);let t=V(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[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 t=await this.readSection(r,!0,!o);if(!t)break;let s=!1;if(!o&&t.pid!==0&&(t.payload[0]!==0||t.payload[1]!==0||t.payload[2]!==1)){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),s=e.readBits(8)===2}if(t.pid===0&&!a){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),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((t.pid===i||s)&&!o){let e=new j(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10),a=e.pos+8*i,s=!1;for(;e.pos<a;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===5&&n>=4){let t=e.readBits(32);s||=t===1212435798||t===1212436562}e.pos=r}for(e.pos=a;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,c=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8),r=e.pos+8*n;if(t===106)a=!0;else if(t===122||t===204)o=!0;else if(t===123)c=!0;else if(t===5&&n>=4){let t=e.readBits(32);c||=(t&4294967040)==1146376960}e.pos=r}let l=null,u=s&&vo.has(t)?130:t;switch(u){case 27:case 36:l={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:case 130:case 138:{let e;e=u===3||u===4?`mp3`:u===15?`aac`:u===129?`ac3`:u===135?`eac3`:`dts`,l={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?l={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:a?l={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:c&&(l={type:`audio`,codec:`dts`,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:yo.has(t)||(A._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),yo.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}o=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);outer:if(e&&!e.initialized){let r=So(this,t,!0);if(!r)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=t.randomAccessIndicator===1,this.input._initInput){let n=(await this.input._initInput._getDemuxer()).elementaryStreams.find(n=>n.pid===t.pid&&n.info.codec===e.info.codec);if(n){e.info=n.info,e.initialized=!0;break outer}}let i=new Do(e,r);if(e.info.type===`video`){for(;;){let t=i;if(t.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=_n(i.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];n(t);let r=xn(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=e.info.height,a>0&&o>0&&(a>o?e.info.squarePixelWidth=Math.round(e.info.width*a/o):e.info.squarePixelHeight=Math.round(e.info.height*o/a)),e.info.colorSpace={primaries:ae[r.colourPrimaries],transfer:se[r.transferCharacteristics],matrix:le[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}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=On(i.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===M.SPS_NUT).nalUnits[0];n(t);let r=Dn(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=e.info.height,a>0&&o>0&&(a>o?e.info.squarePixelWidth=Math.round(e.info.width*a/o):e.info.squarePixelHeight=Math.round(e.info.height*o/a)),e.info.colorSpace={primaries:ae[r.colourPrimaries],transfer:se[r.transferCharacteristics],matrix:le[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:Rr({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=du.tempFromBytes(i.suppliedPacket.data),n=to(t);if(!n)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:n.objectType},e.info.numberOfChannels=Kt[n.channelConfiguration],e.info.sampleRate=Gt[n.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=W(du.tempFromBytes(i.suppliedPacket.data)),n=li(t,i.suppliedPacket.data.byteLength);if(!n.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=pi(n.header.channel),e.info.sampleRate=n.header.sampleRate}else if(e.info.codec===`ac3`){let t=nr(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=tr[t.acmod]+t.lfeon,e.info.sampleRate=nn[t.fscod]}else if(e.info.codec===`eac3`){let t=sr(i.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=lr(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=ur(t),e.info.sampleRate=n}else if(e.info.codec===`dts`){let t=yr(i.suppliedPacket.data);if(!t)throw Error(`Invalid DTS audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?`dtsh`:`dtsc`)}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:Vr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),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.initialized&&(e.info.type===`video`?this.trackBackingEntries.push(new wo(e)):this.trackBackingEntries.push(new To(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return go(e)}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(ye(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=E(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(k(t)&&(t=await t),!t)return null;if(H(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=U(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=H(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(k(t)&&(t=await t),!t)return null;let n=V(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)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let t=60*mo;this.timestampWrapInfo={reference:e-t,offset:e>=ho-t?-ho:ho}}let{reference:t,offset:n}=this.timestampWrapInfo;return n<0&&e>=t||n>0&&e<t?e+n:e}};const xo=(e,t,n)=>{if(t.payload.byteLength<3)return null;let r=new j(t.payload);if(r.readBits(24)!==1)return null;let i=r.readBits(8);if(r.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;r.skipBits(8);let a=r.readBits(2);r.skipBits(14);let o=null;if(a===2||a===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=e.normalizeTimestamp(o);else if(n)throw Error(_o);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},So=(e,t,r)=>{n(t.endPos!==null);let i=xo(e,t,r);if(!i)return null;let a=new j(t.payload);a.skipBits(32);let o=a.readBits(16);a.skipBits(16);let s=a.readBits(8),c=a.pos+8*s;a.pos=c;let l=c/8;n(Number.isInteger(l));let u=t.payload.subarray(l,o>0?6+o:t.payload.byteLength);return{...i,data:u}};var Co=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=/* @__PURE__ */ new WeakMap,this.packetSectionStarts=/* @__PURE__ */ new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,i=0;for(let a of t.trackBackingEntries)if(a.getType()===r&&i++,n(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{...Ut,primary:!1}}getTimeResolution(){return mo}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 I(n.metadataOnly?hi:e.data,r,e.pts/mo,Math.max(t/mo,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;n(t);let r=So(this.elementaryStream.demuxer,t,!0);n(r);let i=new Do(this.elementaryStream,r),a=new Oo(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,t){let r=this.packetBuffers.get(e);if(r){let n=await r.readNext();if(!n)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(n.packet,n.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,n.packet.sectionStartPos),i}let i=this.packetSectionStarts.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);let a=this.elementaryStream.demuxer,o=await a.readSection(i,!0);n(o);let s=So(a,o,!0);n(s);let c=new Do(this.elementaryStream,s);r=new Oo(this,c);let l=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){let n=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(n,r),this.packetSectionStarts.set(n,e.packet.sectionStartPos),n}}}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,t,r){let i=Fe(e*mo),a=this.elementaryStream.demuxer,{reader:o,seekChunkSize:s}=a,c=this.elementaryStream.pid,l=async(e,t,n)=>{let r=e;for(;r<t;){let e=await a.readPacketHeader(r);if(!e)return null;if(e.pid===c&&e.payloadUnitStartIndicator===1){let e=await a.readSection(r,n);if(!e)return null;let t=xo(a,e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=a.packetStride}return null},u=this.elementaryStream.firstSection;n(u);let d=xo(a,u,!0);if(n(d),i<d.pts)return null;let f,p=this.elementaryStream.referencePesPackets,m=E(p,i,e=>e.pts),g=m===-1?null:p[m];if(g&&i-g.pts<45e3)f=g.sectionStartPos;else{let e=0;if(o.fileSize!==null){let t=Math.ceil(o.fileSize/s);if(t>1){let n=0,r=t-1;for(e=n;n<=r;){let t=Math.floor((n+r)/2),o=Re(t*s,a.packetStride)+d.sectionStartPos,c=await l(o,o+s,!1);if(!c){r=t-1;continue}c.pesPacketHeader.pts<=i?(e=t,n=t+1):r=t-1}}}f=Re(e*s,a.packetStride)+d.sectionStartPos}let _=(await l(f,o.fileSize??1/0,!1))?.pesPacketHeader??null;_||=d;let v=this.getReorderSize(),y=async(e,t)=>{let o=await a.readSection(e,!0);n(o);let s=So(a,o,!0);n(s);let c=new Do(this.elementaryStream,s),l=new Oo(this,c);for(;!((h(l.presentationOrderPackets)?.pts??-1/0)>=i||!await l.readNextPacket()););let u=Ce(l.presentationOrderPackets,t);if(u===-1)return null;let d=l.presentationOrderPackets[u],f=u===0?0:d.pts-l.presentationOrderPackets[u-1].pts;for(;l.decodeOrderPackets[0]!==d;)l.decodeOrderPackets.shift();l.lastDuration=f;let p=await l.readNext();n(p);let m=this.createEncodedPacket(p.packet,p.duration,r);return this.packetBuffers.set(m,l),this.packetSectionStarts.set(m,p.packet.sectionStartPos),m};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=_.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=xo(a,t,!1);if(e&&e.pts!==null){if(e.pts>i)break outer;_=e,Eo(this.elementaryStream,_);break}}}e+=a.packetStride}}outer:for(let e=0;e<v+1;e++){let e=_.sectionStartPos-a.packetStride;for(;e>=a.packetOffset;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,!1);if(t){let e=xo(a,t,!1);if(e&&e.pts!==null){_=e;break}}}e-=a.packetStride}}return y(_.sectionStartPos,e=>e.pts<=i)}{let e=f,t=null,r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let f=null,p=e<=d.sectionStartPos,m,h=null;if(p)m=d,h=u;else{let t=await l(e,o.fileSize??1/0,r);m=t?.pesPacketHeader??null,h=t?.section??null}let g=!1,_=0;outer:for(;m&&!(t!==null&&m.sectionStartPos>=t);){if(m.pts<=i){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=m.randomAccessIndicator===1;else{n(h);let t=So(a,h,!0);n(t);let r=new Do(this.elementaryStream,t);await r.markNextPacket(),e=r.suppliedPacket?.randomAccessIndicator===1}e&&(f=m)}if(m.pts>i&&(g=!0),g&&(_++,_>v))break;let e=m.sectionStartPos+a.packetStride;for(;;){let t=await a.readPacketHeader(e);if(!t)break outer;if(t.pid===c&&t.payloadUnitStartIndicator===1){let t=await a.readSection(e,r);if(t){let e=xo(a,t,!1);if(e&&e.pts!==null){m=e,h=t,Eo(this.elementaryStream,m);break}}}e+=a.packetStride}}if(f){let e=f;if(_===0)outer:for(let t=0;t<v;t++){let t=e.sectionStartPos-a.packetStride;for(;t>=a.packetOffset;){let n=await a.readPacketHeader(t);if(!n)break outer;if(n.pid===c&&n.payloadUnitStartIndicator===1){let n=await a.readSection(t,r);if(n){let t=xo(a,n,!1);if(t&&t.pts!==null){e=t;break}}}t-=a.packetStride}}let t=await y(e.sectionStartPos,e=>e.pts<=i&&e.randomAccessIndicator===1);return n(t),t}if(p)return null;t=e,e=Math.max(Re(e-d.sectionStartPos-s,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},wo=class extends Co{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}getTransformationMatrix(){return[...o]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},To=class extends Co{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}};const Eo=(e,t)=>{let n=e.referencePesPackets,r=E(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 Do=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 n(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=h(this.pesPackets).sectionEndPos;for(n(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=So(this.demuxer,n,!1);if(r){e=r;break}}t+=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++}getPesPacketAt(e){n(e<=this.currentPos);let t=this.currentPesPacketIndex,r=this.currentPesPacketPos;for(;e<r;)t--,r-=this.pesPackets[t].data.byteLength;return this.pesPackets[t]}async markNextPacket(){n(!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,i=null,a=!1,o=null,s=0;for(;;){let e=this.ensureBuffered(n);if(k(e)&&(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;i??=g;let _=d+h,y=_+r;if(y+(t===`avc`?6:1)>u){this.seekTo(n);break}let b=l[_],x,S,C;if(t===`avc`)x=un(b),S=x===on.NON_IDR_SLICE||x===on.SLICE_DPA||x===on.IDR,C=x===on.SEI||x===on.SPS||x===on.PPS||x===on.AUD;else{if(x=En(b),((b&1)<<5|l[_+1]>>3)>0){d+=h;continue}S=x<=M.RASL_R||x>=M.BLA_W_LP&&x<=21,C=x>=M.VPS_NUT&&x<=37||x===M.PREFIX_SEI_NUT||x>=41&&x<=44||x>=48&&x<=55}let ee=!1;if(S){let e;if(t===`avc`){let t=l.subarray(y,y+6),n=v(new j(t));e=!a||n<=s,s=n}else e=l[y]>>7==1;e&&(a?ee=!0:(a=!0,o=this.getPesPacketAt(c+_).pts))}else C&&a&&(ee=!0);if(ee){let e=g-i;return this.seekTo(i),this.supplyPacket(e,0,o)}d+=h}if(e<n)break}if(i!==null&&this.endPos>i){let e=this.endPos-i;return this.seekTo(i),this.supplyPacket(e,0,o)}}else{let t=e.info.codec;for(;;){let r=this.ensureBuffered(128);k(r)&&(r=await r);let i=this.currentPos;for(;this.currentPos-i<r;){let r=this.readU8();if(t===`aac`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(9);if(k(n)&&(n=await n),n<9)return;let i=this.readBytes(9),a=to(du.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return k(n)&&(n=await n),this.supplyPacket(n,Math.round(no*mo/e.info.sampleRate))}this.seekTo(t+1)}else if(t===`mp3`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(4);if(k(n)&&(n=await n),n<4)return;let i=this.readBytes(4),a=C(i).getUint32(0),o=li(a,null);if(o.header){this.seekTo(t);let n=this.ensureBuffered(o.header.totalSize);k(n)&&(n=await n);let r=o.header.audioSamplesInFrame*mo/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}this.seekTo(t+1)}else if(t===`ac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(5);if(k(i)&&(i=await i),i<5)return;let a=this.readBytes(5);if(a[0]!==11||a[1]!==119){this.seekTo(t+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){this.seekTo(t+1);continue}let c=rr[3*s+o];n(c!==void 0),this.seekTo(t),i=this.ensureBuffered(c),k(i)&&(i=await i);let l=Math.round(1536*mo/e.info.sampleRate);return this.supplyPacket(i,l)}else if(t===`eac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(5);if(k(n)&&(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=i[4]>>6==3?3:i[4]>>4&3,s=or[o];this.seekTo(t),n=this.ensureBuffered(a),k(n)&&(n=await n);let c=s*256,l=Math.round(c*mo/e.info.sampleRate);return this.supplyPacket(n,l)}else if(t===`dts`){if(r!==127&&r!==100)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(18);if(k(n)&&(n=await n),n<18)return;let i=this.readBytes(18),a=xr(i),o=a?null:Sr(i);if(!a&&!o){this.seekTo(t+1);continue}if(o&&!o.asset){this.seekTo(t);let e=Math.min(o.frameSize,4096),n=this.ensureBuffered(e);k(n)&&(n=await n),o=Sr(this.readBytes(n))??o}let s=a?a.frameSize:o.frameSize;if(a){let e=Math.ceil(a.frameSize/4)*4;for(;;){this.seekTo(t);let n=e+10,r=this.ensureBuffered(n);if(k(r)&&(r=await r),r<n)break;this.seekTo(t+e);let i=Sr(this.readBytes(10));if(!i)break;e+=i.frameSize,s=e}}let c=a?.sampleCount??o.asset?.sampleCount;if(c===void 0){this.seekTo(t+1);continue}this.seekTo(t),n=this.ensureBuffered(s),k(n)&&(n=await n);let l=Math.round(c*mo/e.info.sampleRate);return this.supplyPacket(n,l)}else throw Error(`Unhandled.`)}if(r<128)break}}}supplyPacket(e,t,r=null){let i=this.getCurrentPesPacket(),a;if(r!==null)a=r;else if(this.lastSuppliedPesPacket===i)n(this.nextPts!==null),a=this.nextPts;else{if(i.pts===null)throw Error(_o);a=i.pts,Eo(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=a+t;let o=i.sectionStartPos,s=o+(this.currentPos-this.currentPesPacketPos),c=this.readBytes(e),l=i.randomAccessIndicator;if(l===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)l=1;else if(this.elementaryStream.info.decoderConfig){let e=Zn(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,c)===`key`;l=Number(e)}}this.suppliedPacket={pts:a,data:c,sequenceNumber:s,sectionStartPos:o,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Oo=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),n(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);n(t!==-1);let r;for(t===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[t+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(n(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}};
|
|
249
249
|
/*!
|
|
250
250
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
251
251
|
*
|
|
@@ -253,7 +253,7 @@ const po=9e4,mo=2**33,ho=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))
|
|
|
253
253
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
254
254
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
255
255
|
*/
|
|
256
|
-
const
|
|
256
|
+
const ko=`application/vnd.apple.mpegurl`,Ao=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`);var jo=class{constructor(e,t){this._attributes={};let n=``,r=``,i=!1,a=!1,o=!1,s=()=>{if(!n)return;let e=n.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,e)&&A._warn(`Duplicate AttributeName "${e}"; using last value`);let a=o||r.startsWith(`0x`)||r.startsWith(`0X`);this._attributes[e]=a&&t?t.substitute(r):r,n=``,r=``,i=!1,o=!1};for(let t=0;t<e.length;t++){let c=e[t];c===`"`?(i&&!a&&r.length===0&&(o=!0),a=!a):c===`=`&&!i&&!a?i=!0:c===`,`&&!a?s():i?r+=c:n+=c}if(a)throw Error(`Invalid M3U8 file; unterminated quoted-string AttributeValue.`);s()}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)}};const Mo=/^[A-Za-z0-9_-]+$/,No=/\{\$([A-Za-z0-9_-]+)\}/g;var Po=class{constructor(e,t){this.playlistPath=e,this.importedVariables=t,this.variables=/* @__PURE__ */ new Map}define(e){let t=new jo(e,this),n=t.get(`name`),r=t.get(`import`),i=t.get(`queryparam`);if([n,r,i].filter(e=>e!==null).length!==1)throw Error(`Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.`);if(n!==null){let e=t.get(`value`);if(e===null)throw Error(`Invalid #EXT-X-DEFINE tag; NAME requires VALUE.`);this.set(n,e)}else if(r!==null){let e=this.importedVariables?.get(r);if(e===void 0)throw Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${r}".`);this.set(r,e)}else if(i!==null){let e=_t(this.playlistPath,i);if(e===null)throw Error(`Invalid #EXT-X-DEFINE tag; query parameter "${i}" is missing.`);this.set(i,e)}}substitute(e){return e.replaceAll(No,(e,t)=>{let n=this.variables.get(t);if(n===void 0)throw Error(`Invalid M3U8 file; variable "${t}" is referenced before being defined.`);return n})}get(e){return this.variables.get(e)}set(e,t){if(!Mo.test(e))throw Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${e}".`);if(this.variables.has(e))throw Error(`Invalid #EXT-X-DEFINE tag; variable "${e}" is already defined.`);this.variables.set(e,t)}},Fo=class{constructor(e,t,n){
|
|
257
257
|
/*!
|
|
258
258
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
259
259
|
*
|
|
@@ -261,7 +261,7 @@ const Oo=`application/vnd.apple.mpegurl`,ko=e=>e.length===0||e.startsWith(`#`)&&
|
|
|
261
261
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
262
262
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
263
263
|
*/
|
|
264
|
-
this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=/* @__PURE__ */ new WeakMap,this.firstTimestampCache=/* @__PURE__ */ 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=vt(e,e=>e.getType()===`video`)+1;e.push(new
|
|
264
|
+
this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=/* @__PURE__ */ new WeakMap,this.firstTimestampCache=/* @__PURE__ */ 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=vt(e,e=>e.getType()===`video`)+1;e.push(new Lo(this,t,n))}else if(t.type===`audio`){let n=vt(e,e=>e.getType()===`audio`)+1;e.push(new Ro(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=vt(e,e=>e.getType()===`video`)+1;e.push(new Lo(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=vt(e,e=>e.getType()===`audio`)+1;e.push(new Ro(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}},Io=class{constructor(e,t,n){this.packetInfos=/* @__PURE__ */ new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=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=this.segmentedInput.firstSegment,t=null;for(;e&&(t=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,!t);)e=await this.segmentedInput.getNextSegment(e,{});if(!t)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=t,this.firstSegment=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(),n(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){n(e.sequenceNumber>=0),n(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(t,r.input),a=t.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:t,track:r,sourcePacket:e}),o}async getFirstPacket(e){await this.hydrate(),n(this.firstInputTrack),n(this.firstSegment);let t=this.firstInputTrack,r=this.firstSegment;for(;;){if(t){let n=await t._backing.getFirstPacket(e);if(n)return this.createAdjustedPacket(n,r,t)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;t=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return 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);if(!i){a=e;continue}return this.createAdjustedPacket(i,e,n)}}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}},Lo=class extends Io{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())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}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())}},Ro=class extends Io{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())}},zo=/* @__PURE__ */ e(t(),1)
|
|
265
265
|
/*!
|
|
266
266
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
267
267
|
*
|
|
@@ -269,7 +269,7 @@ this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.
|
|
|
269
269
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
270
270
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
271
271
|
*/
|
|
272
|
-
;mt();const zo=Ro===void 0?void 0:Ro,Bo=1/0;let Vo=null;typeof FinalizationRegistry<`u`&&(Vo=new FinalizationRegistry(e=>{e()}));var Ho=class extends Pt{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 cu;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Bo),e=this._getFileSize(),n(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new cu;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 cs(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Uo(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Uo=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;n(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Wo=class extends Ho{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 Ho||e instanceof Uo))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Ho?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return k(t)?t.then(n):n(t)}};const Go=(e,t)=>e.path===t.path;var Ko=class extends Wo{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,i){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof Ho?e.ref():e;return this._root=t,this._rootRequest=null,t};k(e)?this._rootRequest=e.then(t):(t(e),n(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,r,i))}return this._root.source._read(e,t,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()).catch(()=>{})}},qo=class extends Ho{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=S(e),this._view=C(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};const Jo=typeof FinalizationRegistry<`u`?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;var Yo=class extends Ho{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&&(!ht(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.`);if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);super(),this._readers=/* @__PURE__ */ new WeakMap,this._blob=e,this._options=t,this._orchestrator=new ss({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{let t=this._readers.get(e);t&&(this._readers.delete(e),Jo?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:os.fileSystem,handleUnhandledError:t.handleUnhandledError}),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){n(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&((`stream`in this._blob)&&!Ze()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),Jo?.register(e,t,e)):t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)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 t?.cancel().catch(()=>{})}_dispose(){this._orchestrator.dispose()}};const Xo=.5*2**20,Zo=((e,t,n)=>{if(t instanceof Error&&(t.message.includes(`Failed to fetch`)||t.message.includes(`Load failed`)||t.message.includes(`NetworkError when attempting to fetch resource`))&&typeof window<`u`){let e=null;try{typeof window<`u`&&window.location!==void 0&&(e=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if((typeof navigator>`u`||typeof navigator.onLine!=`boolean`||navigator.onLine)&&e!==null&&e!==window.location.origin)return A._warn(`Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option.`),null}return Math.min(2**(e-2),16)}),Qo=/* @__PURE__ */ new Set;var $o=class e extends Wo{constructor(t,n={}){if(typeof t!=`string`&&!(t instanceof URL)&&!(typeof Request<`u`&&t instanceof Request))throw TypeError(`url must be a string, URL or Request.`);if(!n||typeof n!=`object`)throw TypeError(`options must be an object.`);if(n.requestInit!==void 0&&(!n.requestInit||typeof n.requestInit!=`object`))throw TypeError(`options.requestInit, when provided, must be an object.`);if(n.getRetryDelay!==void 0&&typeof n.getRetryDelay!=`function`)throw TypeError(`options.getRetryDelay, when provided, must be a function.`);if(n.maxCacheSize!==void 0&&(!ht(n.maxCacheSize)||n.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(n.parallelism!==void 0&&(!Number.isInteger(n.parallelism)||n.parallelism<1))throw TypeError(`options.parallelism, when provided, must be a positive number.`);if(n.fetchFn!==void 0&&typeof n.fetchFn!=`function`)throw TypeError(`options.fetchFn, when provided, must be a function.`);if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);let r=t instanceof Request?t.url:t instanceof URL?t.href:t;super(r,t=>new e(t.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._abortControllers=/* @__PURE__ */ new Map,this._sequentialAbortController=null,this._url=t,this._options=n,this._getRetryDelay=n.getRetryDelay??Zo,this._requestInit={...n.requestInit};let i=null;if(n.requestInit?.headers){let e={...Ke(n.requestInit.headers)},t=Object.keys(e).find(e=>e.toLowerCase()===`range`);t!==void 0&&(i=e[t],delete e[t],this._requestInit.headers=e)}if(t instanceof Request){let e=t.headers.get(`Range`);if(e!==null){i??=e;let n=new Request(t);n.headers.delete(`Range`),this._url=n}}if(i!==null){let e=ts(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new ss({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??2,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>this._abortControllers.delete(e),prefetchProfile:os.network,handleUnhandledError:n.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length===null?void 0:this._length;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length===null?null:this._length:O(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._offset,a=this._sequentialBacking?this._sequentialBacking._read(i+e,i+t):this._orchestrator.read(i+e,i+t,Math.max(i+n,i),i+Math.min(r,this._length??1/0)),o=e=>e?(e.offset-=this._offset,e):null;return k(a)?a.then(o):o(a)}async _runWorker(e){for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let t=new AbortController;this._abortControllers.set(e,t);let n=await qe(this._options.fetchFn??fetch,this._url,Ge(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>t.signal.aborted);if(!n.ok)throw Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);outer:if(this._orchestrator.fileSize===null&&!n.headers.has(`Content-Encoding`)&&(n.status===206||n.type===`basic`)){let t=n.headers.get(`Content-Range`);if(t){let e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break outer}}let r=n.headers.get(`Content-Length`);if(r){let t=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(r))}}if(this._fileSizeDetermined=!0,!n.body)throw Error(`Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.`);if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){let e=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<`u`?window.location.href:void 0);e.origin!==`null`&&!(e.pathname.endsWith(`.m3u8`)||e.pathname.endsWith(`.m3u`))&&(Qo.has(e.origin)||(A._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),Qo.add(e.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,t);return}let r=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await r.read()}catch(e){if(t.signal.aborted)throw e;let n=this._getRetryDelay(1,e,this._url);if(n!==null){A._error(`Error while reading response stream. Attempting to resume.`,e),await Mt(1e3*n);break}throw e}if(e.aborted)continue;let{done:i,value:a}=n;if(i){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}}}_transitionToSequentialMode(e,t){this._sequentialAbortController=t;let r=e.getReader(),i=0,a=0,o=new as(new ReadableStream({pull:async e=>{for(;;){let t;try{t=await r.read()}catch(e){if(this._disposed)throw e;let t=this._getRetryDelay(1,e,this._url);if(t===null)throw e;A._error(`Error while reading response stream. Attempting to resume.`,e),await Mt(1e3*t),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let n=await qe(this._options.fetchFn??fetch,this._url,Ge(this._requestInit,{headers:{Range:`bytes=${i}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);if(!n.body)throw Error(`Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.`);r=n.body.getReader(),a=n.status===206?0:i;continue}if(t.done){e.close();return}let n=t.value;if(a>0){let e=Math.min(a,n.length);a-=e,n=n.subarray(e)}if(n.length!==0){i+=n.length,e.enqueue(n);return}}},cancel:()=>r.cancel().catch(()=>{})}),{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});o._endIndex=this._orchestrator.fileSize,o._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.`,o.on(`read`,({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=o;let s=/* @__PURE__ */ new Set;for(let e of this._orchestrator.workers){for(let t of e.pendingSlices)s.add(t);e.aborted=!0,e.pendingSlices.length=0}for(let e of this._orchestrator.queuedReads)for(let t of e.pendingSlices)s.add(t);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear();for(let e of s){let t=o._read(e.start,e.start+e.bytes.length);k(t)?t.then(t=>{t?(n(t.offset===e.start),e.resolve(t.bytes)):e.resolve(null)},t=>e.reject(t)):(n(t===null),e.resolve(null))}}_dispose(){this._orchestrator.dispose();for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}};const es=/^bytes=(\d+)-(\d*)$/,ts=e=>{let t=es.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]===``?null:Number(t[2]);return r!==null&&r<n?null:{offset:n,length:r===null?null:r-n+1}};var ns=class e extends Wo{constructor(t,r={}){if(typeof t!=`string`)throw TypeError(`filePath must be a string.`);if(!r||typeof r!=`object`)throw TypeError(`options must be an object.`);if(r.maxCacheSize!==void 0&&(!ht(r.maxCacheSize)||r.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(!zo.fs)throw Error(`FilePathSource is only available in server-side environments (Node.js, Bun, Deno).`);super(t,t=>new e(t.path,r)),this._fileHandle=null,this._customSource=new rs({getSize:async()=>{let e=await zo.fs.open(t,`r`);return this._fileHandle=e,Vo?.register(this,()=>{e.close()},this),(await e.stat()).size},read:async(e,t)=>{n(this._fileHandle);let r=new Uint8Array(t-e);return await this._fileHandle.read(r,0,t-e,e),r},maxCacheSize:r.maxCacheSize,prefetchProfile:`fileSystem`,handleUnhandledError:r.handleUnhandledError})}_read(e,t,n,r){return this._customSource._read(e,t,n,r)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Vo?.unregister(this))}},rs=class extends Ho{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(typeof e.getSize!=`function`)throw TypeError(`options.getSize must be a function.`);if(typeof e.read!=`function`)throw TypeError(`options.read must be a function.`);if(e.dispose!==void 0&&typeof e.dispose!=`function`)throw TypeError(`options.dispose, when provided, must be a function.`);if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(e.maxCacheSize!==void 0&&(!ht(e.maxCacheSize)||e.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(e.prefetchProfile&&![`none`,`fileSystem`,`network`].includes(e.prefetchProfile))throw TypeError(`options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.`);super(),this._readers=/* @__PURE__ */ new Set,this._options=e,this._orchestrator=new ss({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:os[e.prefetchProfile??`none`],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,n,r){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,n,r);let i=this._options.getSize();if(k(i))return i.then(i=>{if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)});if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let t=e.currentPos,n=e.targetPos,r=this._options.read(e.currentPos,n);if(k(r)&&(r=await r),e.aborted){r instanceof ReadableStream&&await r.cancel().catch(()=>{});break}if(r instanceof Uint8Array){if(r=S(r),r.length!==n-e.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${r.length}.`);this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else if(r instanceof ReadableStream){let i=r.getReader();this._readers.add(i);try{for(;e.currentPos<n&&!e.aborted;){let{done:r,value:a}=await i.read();if(r){if(e.currentPos<n)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-t} bytes, but got ${e.currentPos-t}`);break}if(!(a instanceof Uint8Array))throw TypeError(`ReadableStream returned by options.read must yield Uint8Array chunks.`);if(e.aborted)break;let o=S(a);this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}finally{this._readers.delete(i),i.releaseLock()}}else throw TypeError(`options.read must return or resolve to a Uint8Array or a ReadableStream.`)}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose();for(let e of this._readers)e.cancel().catch(()=>{});this._readers.clear(),this._options.dispose?.()}};const is=rs;var as=class extends Ho{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.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(t.maxCacheSize!==void 0&&(!ht(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._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20,this._handleUnhandledError=t.handleUnhandledError}_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=E(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:C(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=D();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:s,reject:c}),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 if(this._handleUnhandledError)this._handleUnhandledError(e);else throw e})),o}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}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:C(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:C(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(){for(let e of this._pendingSlices)e.reject(new cu);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel().catch(()=>{})}};const os={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(ct(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+Xo),{start:e,end:t}}};var ss=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,r,i){n(!this.disposed);let a=this.options.prefetchProfile(e,t,this.workers),o=Math.max(a.start,r),s=Math.min(a.end,this.fileSize??1/0,i);n(o<=e&&t<=s);let c=null,l=E(this.cache,e,e=>e.start),u=l===-1?null:this.cache[l];u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=E(this.cache,o,e=>e.start),f=c?null:new Uint8Array(t-e),p=0,m=o,h=[];if(d!==-1){for(let r=d;r<this.cache.length;r++){let i=this.cache[r];if(i.start>=s)break;if(i.end<=o)continue;let a=Math.max(o,i.start),c=Math.min(s,i.end);if(n(a<=c),m<a&&h.push({start:m,end:a}),m=c,f){let n=Math.max(e,i.start),r=Math.min(t,i.end);if(n<r){let t=n-e;f.set(i.bytes.subarray(n-i.start,r-i.start),t),t===p&&(p=r-e)}}i.age=this.nextAge++}m<s&&h.push({start:m,end:s})}else h.push({start:o,end:s});if(f&&p>=f.length&&(c={bytes:f,view:C(f),offset:e}),h.length===0)return n(c),c;let{promise:g,resolve:_,reject:v}=D(),y=[];for(let n of h){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?y.push(n):r<i&&y.push({start:r,end:i})}let b=f&&{start:e,bytes:f,holes:y,resolve:_,reject:v};outer:for(let e of h){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,b?[b]:[])){this.checkQueuedReadsAgainstWorker(t);continue outer}let t=e.end<s||this.fileSize!==null,n=this.createWorker(e.start,e.end,t);if(n)b&&(n.pendingSlices=[b]),this.runWorker(n);else{let n=E(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,b&&r.pendingSlices.push(b)):(n++,r={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:b?[b]:[],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 c?g.catch(e=>{if(!this.disposed){if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}}):(n(f),c=g.then(t=>t&&{bytes:t,view:C(t),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(ct(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,t,r){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let n=0;n<this.workers.length;n++){let r=this.workers[n];!r.running&&r.pendingSlices.length===0&&(!e||r.age<e.age)&&(t=n,e=r)}if(e)n(t!==null),n(e.pendingSlices.length===0),this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){n(!e.running),n(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){if(this.options.handleUnhandledError)this.options.handleUnhandledError(t);else 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)}})}supplyWorkerData(e,t){n(!e.aborted);let r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:C(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){let a=e.pendingSlices[n],o=Math.max(r,a.start),s=Math.min(i,a.start+a.bytes.length);o<s&&a.bytes.set(t.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(n,1),n--)}for(let t=0;t<this.workers.length;t++){let n=this.workers[t];e===n||n.running||ct(r,i,n.currentPos,n.targetPos)&&(this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(n),t--)}}supplyFileSize(e){n(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.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){let t=this.workers.indexOf(e);n(t!==-1),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),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=E(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=C(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=C(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){for(let t of e.pendingSlices)t.reject(new cu);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(let e of this.queuedReads)for(let t of e.pendingSlices)t.reject(new cu);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}},cs=class extends Ho{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:O(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 k(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},ls=function(e,t,n){
|
|
272
|
+
;mt();const Bo=zo===void 0?void 0:zo,Vo=1/0;let Ho=null;typeof FinalizationRegistry<`u`&&(Ho=new FinalizationRegistry(e=>{e()}));var Uo=class extends Pt{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 lu;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Vo),e=this._getFileSize(),n(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new lu;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 ls(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new Wo(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Wo=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;n(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Go=class extends Uo{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 Uo||e instanceof Wo))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Uo?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return k(t)?t.then(n):n(t)}};const Ko=(e,t)=>e.path===t.path;var qo=class extends Go{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,i){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof Uo?e.ref():e;return this._root=t,this._rootRequest=null,t};k(e)?this._rootRequest=e.then(t):(t(e),n(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,r,i))}return this._root.source._read(e,t,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()).catch(()=>{})}},Jo=class extends Uo{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=S(e),this._view=C(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}};const Yo=typeof FinalizationRegistry<`u`?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;var Xo=class extends Uo{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&&(!ht(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.`);if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);super(),this._readers=/* @__PURE__ */ new WeakMap,this._blob=e,this._options=t,this._orchestrator=new cs({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{let t=this._readers.get(e);t&&(this._readers.delete(e),Yo?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ss.fileSystem,handleUnhandledError:t.handleUnhandledError}),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){n(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&((`stream`in this._blob)&&!Ze()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),Yo?.register(e,t,e)):t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)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 t?.cancel().catch(()=>{})}_dispose(){this._orchestrator.dispose()}};const Zo=.5*2**20,Qo=((e,t,n)=>{if(t instanceof Error&&(t.message.includes(`Failed to fetch`)||t.message.includes(`Load failed`)||t.message.includes(`NetworkError when attempting to fetch resource`))&&typeof window<`u`){let e=null;try{typeof window<`u`&&window.location!==void 0&&(e=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if((typeof navigator>`u`||typeof navigator.onLine!=`boolean`||navigator.onLine)&&e!==null&&e!==window.location.origin)return A._warn(`Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option.`),null}return Math.min(2**(e-2),16)}),$o=/* @__PURE__ */ new Set;var es=class e extends Go{constructor(t,n={}){if(typeof t!=`string`&&!(t instanceof URL)&&!(typeof Request<`u`&&t instanceof Request))throw TypeError(`url must be a string, URL or Request.`);if(!n||typeof n!=`object`)throw TypeError(`options must be an object.`);if(n.requestInit!==void 0&&(!n.requestInit||typeof n.requestInit!=`object`))throw TypeError(`options.requestInit, when provided, must be an object.`);if(n.getRetryDelay!==void 0&&typeof n.getRetryDelay!=`function`)throw TypeError(`options.getRetryDelay, when provided, must be a function.`);if(n.maxCacheSize!==void 0&&(!ht(n.maxCacheSize)||n.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(n.parallelism!==void 0&&(!Number.isInteger(n.parallelism)||n.parallelism<1))throw TypeError(`options.parallelism, when provided, must be a positive number.`);if(n.fetchFn!==void 0&&typeof n.fetchFn!=`function`)throw TypeError(`options.fetchFn, when provided, must be a function.`);if(n.handleUnhandledError!==void 0&&typeof n.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);let r=t instanceof Request?t.url:t instanceof URL?t.href:t;super(r,t=>new e(t.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._abortControllers=/* @__PURE__ */ new Map,this._sequentialAbortController=null,this._url=t,this._options=n,this._getRetryDelay=n.getRetryDelay??Qo,this._requestInit={...n.requestInit};let i=null;if(n.requestInit?.headers){let e={...Ke(n.requestInit.headers)},t=Object.keys(e).find(e=>e.toLowerCase()===`range`);t!==void 0&&(i=e[t],delete e[t],this._requestInit.headers=e)}if(t instanceof Request){let e=t.headers.get(`Range`);if(e!==null){i??=e;let n=new Request(t);n.headers.delete(`Range`),this._url=n}}if(i!==null){let e=ns(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new cs({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??2,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>this._abortControllers.delete(e),prefetchProfile:ss.network,handleUnhandledError:n.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length===null?void 0:this._length;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length===null?null:this._length:O(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._offset,a=this._sequentialBacking?this._sequentialBacking._read(i+e,i+t):this._orchestrator.read(i+e,i+t,Math.max(i+n,i),i+Math.min(r,this._length??1/0)),o=e=>e?(e.offset-=this._offset,e):null;return k(a)?a.then(o):o(a)}async _runWorker(e){for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let t=new AbortController;this._abortControllers.set(e,t);let n=await qe(this._options.fetchFn??fetch,this._url,Ge(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>t.signal.aborted);if(!n.ok)throw Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);outer:if(this._orchestrator.fileSize===null&&!n.headers.has(`Content-Encoding`)&&(n.status===206||n.type===`basic`)){let t=n.headers.get(`Content-Range`);if(t){let e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break outer}}let r=n.headers.get(`Content-Length`);if(r){let t=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(r))}}if(this._fileSizeDetermined=!0,!n.body)throw Error(`Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.`);if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){let e=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<`u`?window.location.href:void 0);e.origin!==`null`&&!(e.pathname.endsWith(`.m3u8`)||e.pathname.endsWith(`.m3u`))&&($o.has(e.origin)||(A._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),$o.add(e.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,t);return}let r=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await r.read()}catch(e){if(t.signal.aborted)throw e;let n=this._getRetryDelay(1,e,this._url);if(n!==null){A._error(`Error while reading response stream. Attempting to resume.`,e),await Mt(1e3*n);break}throw e}if(e.aborted)continue;let{done:i,value:a}=n;if(i){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}}}_transitionToSequentialMode(e,t){this._sequentialAbortController=t;let r=e.getReader(),i=0,a=0,o=new os(new ReadableStream({pull:async e=>{for(;;){let t;try{t=await r.read()}catch(e){if(this._disposed)throw e;let t=this._getRetryDelay(1,e,this._url);if(t===null)throw e;A._error(`Error while reading response stream. Attempting to resume.`,e),await Mt(1e3*t),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let n=await qe(this._options.fetchFn??fetch,this._url,Ge(this._requestInit,{headers:{Range:`bytes=${i}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);if(!n.body)throw Error(`Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.`);r=n.body.getReader(),a=n.status===206?0:i;continue}if(t.done){e.close();return}let n=t.value;if(a>0){let e=Math.min(a,n.length);a-=e,n=n.subarray(e)}if(n.length!==0){i+=n.length,e.enqueue(n);return}}},cancel:()=>r.cancel().catch(()=>{})}),{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});o._endIndex=this._orchestrator.fileSize,o._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.`,o.on(`read`,({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=o;let s=/* @__PURE__ */ new Set;for(let e of this._orchestrator.workers){for(let t of e.pendingSlices)s.add(t);e.aborted=!0,e.pendingSlices.length=0}for(let e of this._orchestrator.queuedReads)for(let t of e.pendingSlices)s.add(t);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear();for(let e of s){let t=o._read(e.start,e.start+e.bytes.length);k(t)?t.then(t=>{t?(n(t.offset===e.start),e.resolve(t.bytes)):e.resolve(null)},t=>e.reject(t)):(n(t===null),e.resolve(null))}}_dispose(){this._orchestrator.dispose();for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}};const ts=/^bytes=(\d+)-(\d*)$/,ns=e=>{let t=ts.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]===``?null:Number(t[2]);return r!==null&&r<n?null:{offset:n,length:r===null?null:r-n+1}};var rs=class e extends Go{constructor(t,r={}){if(typeof t!=`string`)throw TypeError(`filePath must be a string.`);if(!r||typeof r!=`object`)throw TypeError(`options must be an object.`);if(r.maxCacheSize!==void 0&&(!ht(r.maxCacheSize)||r.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(!Bo.fs)throw Error(`FilePathSource is only available in server-side environments (Node.js, Bun, Deno).`);super(t,t=>new e(t.path,r)),this._fileHandle=null,this._customSource=new is({getSize:async()=>{let e=await Bo.fs.open(t,`r`);return this._fileHandle=e,Ho?.register(this,()=>{e.close()},this),(await e.stat()).size},read:async(e,t)=>{n(this._fileHandle);let r=new Uint8Array(t-e);return await this._fileHandle.read(r,0,t-e,e),r},maxCacheSize:r.maxCacheSize,prefetchProfile:`fileSystem`,handleUnhandledError:r.handleUnhandledError})}_read(e,t,n,r){return this._customSource._read(e,t,n,r)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Ho?.unregister(this))}},is=class extends Uo{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(typeof e.getSize!=`function`)throw TypeError(`options.getSize must be a function.`);if(typeof e.read!=`function`)throw TypeError(`options.read must be a function.`);if(e.dispose!==void 0&&typeof e.dispose!=`function`)throw TypeError(`options.dispose, when provided, must be a function.`);if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(e.maxCacheSize!==void 0&&(!ht(e.maxCacheSize)||e.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(e.prefetchProfile&&![`none`,`fileSystem`,`network`].includes(e.prefetchProfile))throw TypeError(`options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.`);super(),this._readers=/* @__PURE__ */ new Set,this._options=e,this._orchestrator=new cs({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:ss[e.prefetchProfile??`none`],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,n,r){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,n,r);let i=this._options.getSize();if(k(i))return i.then(i=>{if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)});if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let t=e.currentPos,n=e.targetPos,r=this._options.read(e.currentPos,n);if(k(r)&&(r=await r),e.aborted){r instanceof ReadableStream&&await r.cancel().catch(()=>{});break}if(r instanceof Uint8Array){if(r=S(r),r.length!==n-e.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${r.length}.`);this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else if(r instanceof ReadableStream){let i=r.getReader();this._readers.add(i);try{for(;e.currentPos<n&&!e.aborted;){let{done:r,value:a}=await i.read();if(r){if(e.currentPos<n)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-t} bytes, but got ${e.currentPos-t}`);break}if(!(a instanceof Uint8Array))throw TypeError(`ReadableStream returned by options.read must yield Uint8Array chunks.`);if(e.aborted)break;let o=S(a);this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}finally{this._readers.delete(i),i.releaseLock()}}else throw TypeError(`options.read must return or resolve to a Uint8Array or a ReadableStream.`)}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose();for(let e of this._readers)e.cancel().catch(()=>{});this._readers.clear(),this._options.dispose?.()}};const as=is;var os=class extends Uo{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.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!=`function`)throw TypeError(`options.handleUnhandledError, when provided, must be a function.`);if(t.maxCacheSize!==void 0&&(!ht(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._cacheMissErrorMessage=`Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20,this._handleUnhandledError=t.handleUnhandledError}_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=E(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:C(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=D();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:s,reject:c}),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 if(this._handleUnhandledError)this._handleUnhandledError(e);else throw e})),o}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}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:C(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:C(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(){for(let e of this._pendingSlices)e.reject(new lu);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel().catch(()=>{})}};const ss={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(ct(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+Zo),{start:e,end:t}}};var cs=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,r,i){n(!this.disposed);let a=this.options.prefetchProfile(e,t,this.workers),o=Math.max(a.start,r),s=Math.min(a.end,this.fileSize??1/0,i);n(o<=e&&t<=s);let c=null,l=E(this.cache,e,e=>e.start),u=l===-1?null:this.cache[l];u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=E(this.cache,o,e=>e.start),f=c?null:new Uint8Array(t-e),p=0,m=o,h=[];if(d!==-1){for(let r=d;r<this.cache.length;r++){let i=this.cache[r];if(i.start>=s)break;if(i.end<=o)continue;let a=Math.max(o,i.start),c=Math.min(s,i.end);if(n(a<=c),m<a&&h.push({start:m,end:a}),m=c,f){let n=Math.max(e,i.start),r=Math.min(t,i.end);if(n<r){let t=n-e;f.set(i.bytes.subarray(n-i.start,r-i.start),t),t===p&&(p=r-e)}}i.age=this.nextAge++}m<s&&h.push({start:m,end:s})}else h.push({start:o,end:s});if(f&&p>=f.length&&(c={bytes:f,view:C(f),offset:e}),h.length===0)return n(c),c;let{promise:g,resolve:_,reject:v}=D(),y=[];for(let n of h){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?y.push(n):r<i&&y.push({start:r,end:i})}let b=f&&{start:e,bytes:f,holes:y,resolve:_,reject:v};outer:for(let e of h){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,b?[b]:[])){this.checkQueuedReadsAgainstWorker(t);continue outer}let t=e.end<s||this.fileSize!==null,n=this.createWorker(e.start,e.end,t);if(n)b&&(n.pendingSlices=[b]),this.runWorker(n);else{let n=E(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,b&&r.pendingSlices.push(b)):(n++,r={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:b?[b]:[],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 c?g.catch(e=>{if(!this.disposed){if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}}):(n(f),c=g.then(t=>t&&{bytes:t,view:C(t),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(ct(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,t,r){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let n=0;n<this.workers.length;n++){let r=this.workers[n];!r.running&&r.pendingSlices.length===0&&(!e||r.age<e.age)&&(t=n,e=r)}if(e)n(t!==null),n(e.pendingSlices.length===0),this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){n(!e.running),n(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){if(this.options.handleUnhandledError)this.options.handleUnhandledError(t);else 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)}})}supplyWorkerData(e,t){n(!e.aborted);let r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:C(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){let a=e.pendingSlices[n],o=Math.max(r,a.start),s=Math.min(i,a.start+a.bytes.length);o<s&&a.bytes.set(t.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(n,1),n--)}for(let t=0;t<this.workers.length;t++){let n=this.workers[t];e===n||n.running||ct(r,i,n.currentPos,n.targetPos)&&(this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(n),t--)}}supplyFileSize(e){n(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.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){let t=this.workers.indexOf(e);n(t!==-1),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),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=E(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=C(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=C(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){for(let t of e.pendingSlices)t.reject(new lu);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(let e of this.queuedReads)for(let t of e.pendingSlices)t.reject(new lu);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}},ls=class extends Uo{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:O(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 k(i)?i.then(a):a(i)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},us=function(e,t,n){
|
|
273
273
|
/*!
|
|
274
274
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
275
275
|
*
|
|
@@ -277,7 +277,7 @@ this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.
|
|
|
277
277
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
278
278
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
279
279
|
*/
|
|
280
|
-
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},us=(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});const ds=/^0[xX][0-9a-fA-F]+$/,fs=/^data:.*;base64,/i;var ps=class extends Po{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 Mt(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 t={stack:[],error:void 0,hasError:!1};try{let r=ls(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=await new lu(r.source).requestEntireFile();n(i),e=Tu(i,i.length,{ignore:ko}),r.source instanceof Wo&&(this.rootPath=r.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{us(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,r=new No(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),i=!1,a=0,o=null,s=null,c=null,l=0,u=null,d=null,f=null,p=null,m=null,g=null,_=!1,v=h(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=>{l=e,v&&(n(v.sequenceNumber!==null),v.sequenceNumber<e&&(a=v.timestamp+v.duration,u=v.firstSegment,d=v.initSegment,m=v.lastProgramDateTimeSeconds,o=v.unixEpochTimestamp===null?null:v.unixEpochTimestamp+v.duration,v=null))};for(let n=0;n<e.length;n++){let x=e[n];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(s===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=c;if(e&&e.method===`AES-128`&&!e.iv){let t=/* @__PURE__ */ new Uint8Array(16),n=C(t);n.setUint32(8,Math.floor(l/2**32)),n.setUint32(12,l),e={...e,iv:t}}let t={path:gt(this.rootPath,r.substitute(x)),offset:p?.offset??0,length:p?.length??null},n={timestamp:a,unixEpochTimestamp:o,firstSegment:u,sequenceNumber:l,location:t,duration:s,encryption:e,initSegment:d,lastProgramDateTimeSeconds:m};u??=n,a+=s,o!==null&&(o+=s),this.segments.push(n)}s=null,p===null?f=null:p=null,b(l+1)}if(x.startsWith(`#EXTINF:`)){if(v){_=!0;continue}_||=(m===null&&l>0&&g!==null&&(a=l*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}'.`);s=r}else if(x.startsWith(`#EXT-X-DEFINE:`))r.define(x.slice(14));else if(x.startsWith(`#EXT-X-MAP:`)){let e=new Ao(x.slice(11),r),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),i=null;if(n!==null&&(i=y(n)),i&&i.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!v){let e={path:gt(this.rootPath,t),offset:i?.offset??0,length:i?.length??null};if(c?.method===`AES-128`&&!c.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);d={timestamp:a,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:m}}s=null,p===null?f=null:p=null}else if(x.startsWith(`#EXT-X-KEY:`)){let e=new Ao(x.slice(11),r),t=e.get(`method`);if(t===`NONE`)c=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(!ds.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),e=e.slice(-32),n=/* @__PURE__ */ new Uint8Array(16);for(let t=0;t<16;t++){let r=2*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.`);c={method:`AES-128`,keyUri:gt(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(fs.test(n)){let e=n.indexOf(`,`),t=dt(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=C(t).getUint32(0);r=_i(t.subarray(8,Math.min(e,t.length)))}}c={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(f===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=f}p=e,f=e.offset+e.length}else if(x.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(v)continue;let e=x.slice(25),n=Date.parse(e);if(!Number.isFinite(n))continue;let r=n/1e3;if(m===r)continue;if(m===null&&this.segments.length>0){let e=h(this.segments),n=r-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+n,t&&(e.timestamp=e.unixEpochTimestamp)}m=r,o=r,t&&(a=r)}else if(x===`#EXT-X-DISCONTINUITY`)u=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=E(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,t){let r=this.segments.indexOf(e);n(r!==-1);let i=r+1,a=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),t.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return n(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,r=this.inputCache.find(e=>e.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||t.encryption.method!==`SAMPLE-AES`&&t.encryption.method!==`SAMPLE-AES-CTR`||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let n=e.psshBoxes,{psshBox:r}=t.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!n.some(e=>vi(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},o=new ou({source:new Ko(t.location.path,async e=>{n(e.isRoot);let r={...e,isRoot:!1},i,a=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method===`SAMPLE-AES`||t.encryption.method===`SAMPLE-AES-CTR`){if(i=await this.input._getSourceCached(r),a){let e=i.source.slice(t.location.offset,t.location.length??void 0).ref();i.free(),i=e}}else if(t.encryption.method===`AES-128`){let e=t.encryption;n(e.iv);let o=await this.input._getSourceCached(r);if(a){let e=o.source.slice(t.location.offset,t.location.length??void 0).ref();o.free(),o=e}let s=new lu(o.source);i=new as(Fi(s,async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new lu(ls(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:V(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{us(t)}},()=>{o.free()})).ref()}else n(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof Ns)),initInput:i??void 0,formatOptions:a});if(o._onFormatDetermined=e=>{if((t.encryption?.method===`SAMPLE-AES`||t.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:t,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=yt(this.inputCache,e=>e.age);n(e!==-1),this.inputCache.splice(e,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},ms=class extends mi{constructor(e){
|
|
280
|
+
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},ds=(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});const fs=/^0[xX][0-9a-fA-F]+$/,ps=/^data:.*;base64,/i;var ms=class extends Fo{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 Mt(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 t={stack:[],error:void 0,hasError:!1};try{let r=us(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=await new uu(r.source).requestEntireFile();n(i),e=Eu(i,i.length,{ignore:Ao}),r.source instanceof Go&&(this.rootPath=r.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{ds(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,r=new Po(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),i=!1,a=0,o=null,s=null,c=null,l=0,u=null,d=null,f=null,p=null,m=null,g=null,_=!1,v=h(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=>{l=e,v&&(n(v.sequenceNumber!==null),v.sequenceNumber<e&&(a=v.timestamp+v.duration,u=v.firstSegment,d=v.initSegment,m=v.lastProgramDateTimeSeconds,o=v.unixEpochTimestamp===null?null:v.unixEpochTimestamp+v.duration,v=null))};for(let n=0;n<e.length;n++){let x=e[n];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(s===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=c;if(e&&e.method===`AES-128`&&!e.iv){let t=/* @__PURE__ */ new Uint8Array(16),n=C(t);n.setUint32(8,Math.floor(l/2**32)),n.setUint32(12,l),e={...e,iv:t}}let t={path:gt(this.rootPath,r.substitute(x)),offset:p?.offset??0,length:p?.length??null},n={timestamp:a,unixEpochTimestamp:o,firstSegment:u,sequenceNumber:l,location:t,duration:s,encryption:e,initSegment:d,lastProgramDateTimeSeconds:m};u??=n,a+=s,o!==null&&(o+=s),this.segments.push(n)}s=null,p===null?f=null:p=null,b(l+1)}if(x.startsWith(`#EXTINF:`)){if(v){_=!0;continue}_||=(m===null&&l>0&&g!==null&&(a=l*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}'.`);s=r}else if(x.startsWith(`#EXT-X-DEFINE:`))r.define(x.slice(14));else if(x.startsWith(`#EXT-X-MAP:`)){let e=new jo(x.slice(11),r),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),i=null;if(n!==null&&(i=y(n)),i&&i.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!v){let e={path:gt(this.rootPath,t),offset:i?.offset??0,length:i?.length??null};if(c?.method===`AES-128`&&!c.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);d={timestamp:a,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:c,initSegment:null,lastProgramDateTimeSeconds:m}}s=null,p===null?f=null:p=null}else if(x.startsWith(`#EXT-X-KEY:`)){let e=new jo(x.slice(11),r),t=e.get(`method`);if(t===`NONE`)c=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(!fs.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),e=e.slice(-32),n=/* @__PURE__ */ new Uint8Array(16);for(let t=0;t<16;t++){let r=2*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.`);c={method:`AES-128`,keyUri:gt(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(ps.test(n)){let e=n.indexOf(`,`),t=dt(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=C(t).getUint32(0);r=_i(t.subarray(8,Math.min(e,t.length)))}}c={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(f===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=f}p=e,f=e.offset+e.length}else if(x.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(v)continue;let e=x.slice(25),n=Date.parse(e);if(!Number.isFinite(n))continue;let r=n/1e3;if(m===r)continue;if(m===null&&this.segments.length>0){let e=h(this.segments),n=r-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+n,t&&(e.timestamp=e.unixEpochTimestamp)}m=r,o=r,t&&(a=r)}else if(x===`#EXT-X-DISCONTINUITY`)u=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=E(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,t){let r=this.segments.indexOf(e);n(r!==-1);let i=r+1,a=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),t.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return n(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,r=this.inputCache.find(e=>e.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||t.encryption.method!==`SAMPLE-AES`&&t.encryption.method!==`SAMPLE-AES-CTR`||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let n=e.psshBoxes,{psshBox:r}=t.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!n.some(e=>vi(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},o=new su({source:new qo(t.location.path,async e=>{n(e.isRoot);let r={...e,isRoot:!1},i,a=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method===`SAMPLE-AES`||t.encryption.method===`SAMPLE-AES-CTR`){if(i=await this.input._getSourceCached(r),a){let e=i.source.slice(t.location.offset,t.location.length??void 0).ref();i.free(),i=e}}else if(t.encryption.method===`AES-128`){let e=t.encryption;n(e.iv);let o=await this.input._getSourceCached(r);if(a){let e=o.source.slice(t.location.offset,t.location.length??void 0).ref();o.free(),o=e}let s=new uu(o.source);i=new os(Ii(s,async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new uu(us(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:V(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{ds(t)}},()=>{o.free()})).ref()}else n(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof Ps)),initInput:i??void 0,formatOptions:a});if(o._onFormatDetermined=e=>{if((t.encryption?.method===`SAMPLE-AES`||t.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:t,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=yt(this.inputCache,e=>e.age);n(e!==-1),this.inputCache.splice(e,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},hs=class extends mi{constructor(e){
|
|
281
281
|
/*!
|
|
282
282
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
283
283
|
*
|
|
@@ -285,7 +285,7 @@ if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object
|
|
|
285
285
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
286
286
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
287
287
|
*/
|
|
288
|
-
super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0,this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{n(this.input._rootSource instanceof Wo);let e=await this.input._reader.requestEntireFile();n(e);let t=Tu(e,e.length,{ignore:ko}),{rootPath:r}=this.input._rootSource,i=new No(r,null),a=[],o=[];for(let e=1;e<t.length;e++){let n=t[e];if(n.startsWith(`#EXT-X-DEFINE:`))i.define(n.slice(14));else if(n.startsWith(`#EXT-X-STREAM-INF:`)){let o=e,s=t[++e];if(s===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);s=i.substitute(s);let c=gt(r,s),l=new Ao(n.slice(18),i);if(l.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);a.push({fullPath:c,attributes:l,lineNumber:o,hasOnlyKeyPackets:!1})}else if(n.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let t=new Ao(n.slice(26),i),o=t.get(`uri`);if(o===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(t.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 s=gt(r,o);a.push({fullPath:s,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(n.startsWith(`#EXT-X-MEDIA:`)){let t=new Ao(n.slice(13),i);if(t.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(t.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let a=null,s=t.get(`uri`);s!==null&&(a=gt(r,s)),o.push({fullPath:a,attributes:t,lineNumber:e})}else if(n!==`#EXT-X-I-FRAMES-ONLY`&&n.startsWith(`#EXTINF:`)){let e=new ps(this,r,null,t);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}this.masterPlaylistVariables=i;let s=await Promise.all(a.map(async(e,t)=>{let i=[],a=e.attributes.get(`codecs`),s;if(a)s=a.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()})));s=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let c=e.attributes.get(`video`),l=e.attributes.get(`audio`),u=s.some(e=>N.includes(Kr(e))),d=s.some(e=>F.includes(Kr(e)));if(c!==null&&!u){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===c&&n.toLowerCase()===`video`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let i=gt(r,t),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);n(o!==null),s.push(o)}}if(l!==null&&!d){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===l&&n.toLowerCase()===`audio`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let i=gt(r,t),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);n(o!==null),s.push(o)}}s=[...new Set(s)];let f=null,p=null,m=e.attributes.getAsNumber(`bandwidth`);n(m!==null);let h=e.attributes.getAsNumber(`average-bandwidth`),g=e.attributes.get(`name`);for(let n of s){let r=Kr(n);if(r!==null){if(N.includes(r)){if(f!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);f=n;let r=e.attributes.get(`video`);if(r===null){let n=e.attributes.get(`resolution`),r=null,a=null;if(n){let e=n.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:f,pairingMask:1n<<BigInt(t),peakBitrate:m,averageBitrate:h,name:g,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:r,height:a}})}else for(let n of o){let a=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`video`)continue;let s=n.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:vs(n.attributes),autoselect:vs(n.attributes)||ys(n.attributes),languageCode:bs(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(t),peakBitrate:n.fullPath===null?m:null,averageBitrate:n.fullPath===null?h:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}else if(F.includes(r)){if(p!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);p=n;let r=e.attributes.get(`audio`);if(r===null){let n=e.attributes.get(`channels`),r=n===null?null:Number(n.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:m,averageBitrate:h,name:g,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:r!==null&&Number.isInteger(r)&&r>0?r:null}})}else for(let n of o){let a=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`audio`)continue;let s=n.attributes.get(`channels`)??e.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:vs(n.attributes),autoselect:vs(n.attributes)||ys(n.attributes),languageCode:bs(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:n.fullPath===null?m:null,averageBitrate:n.fullPath===null?h:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}return i})),c=[],l=e=>{let t=c.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=c.length+1,c.push(e))};for(let e of s)for(let t of e)l(t);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of c)e.info.type===`video`?this.trackBackings.push(new gs(e)):this.trackBackings.push(new _s(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),n(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 ps(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Oo}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},hs=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(r.length===1)t=r[0];else if(this instanceof gs){for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}else{n(this instanceof _s);for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...Ut,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(){n(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},gs=class extends hs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return Kr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},_s=class extends hs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return Kr(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()}};const vs=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}".`)},ys=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}".`)},bs=e=>e===null?`und`:e.split(`-`)[0]||`und`;
|
|
288
|
+
super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0,this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{n(this.input._rootSource instanceof Go);let e=await this.input._reader.requestEntireFile();n(e);let t=Eu(e,e.length,{ignore:Ao}),{rootPath:r}=this.input._rootSource,i=new Po(r,null),a=[],o=[];for(let e=1;e<t.length;e++){let n=t[e];if(n.startsWith(`#EXT-X-DEFINE:`))i.define(n.slice(14));else if(n.startsWith(`#EXT-X-STREAM-INF:`)){let o=e,s=t[++e];if(s===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);s=i.substitute(s);let c=gt(r,s),l=new jo(n.slice(18),i);if(l.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);a.push({fullPath:c,attributes:l,lineNumber:o,hasOnlyKeyPackets:!1})}else if(n.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let t=new jo(n.slice(26),i),o=t.get(`uri`);if(o===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(t.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 s=gt(r,o);a.push({fullPath:s,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(n.startsWith(`#EXT-X-MEDIA:`)){let t=new jo(n.slice(13),i);if(t.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(t.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let a=null,s=t.get(`uri`);s!==null&&(a=gt(r,s)),o.push({fullPath:a,attributes:t,lineNumber:e})}else if(n!==`#EXT-X-I-FRAMES-ONLY`&&n.startsWith(`#EXTINF:`)){let e=new ms(this,r,null,t);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}this.masterPlaylistVariables=i;let s=await Promise.all(a.map(async(e,t)=>{let i=[],a=e.attributes.get(`codecs`),s;if(a)s=a.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()})));s=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let c=e.attributes.get(`video`),l=e.attributes.get(`audio`),u=s.some(e=>N.includes(Kr(e))),d=s.some(e=>F.includes(Kr(e)));if(c!==null&&!u){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===c&&n.toLowerCase()===`video`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let i=gt(r,t),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);n(o!==null),s.push(o)}}if(l!==null&&!d){let e=o.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===l&&n.toLowerCase()===`audio`});outer:if(e){let t=e.attributes.get(`uri`);if(t===null)break outer;let i=gt(r,t),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);n(o!==null),s.push(o)}}s=[...new Set(s)];let f=null,p=null,m=e.attributes.getAsNumber(`bandwidth`);n(m!==null);let h=e.attributes.getAsNumber(`average-bandwidth`),g=e.attributes.get(`name`);for(let n of s){let r=Kr(n);if(r!==null){if(N.includes(r)){if(f!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);f=n;let r=e.attributes.get(`video`);if(r===null){let n=e.attributes.get(`resolution`),r=null,a=null;if(n){let e=n.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:f,pairingMask:1n<<BigInt(t),peakBitrate:m,averageBitrate:h,name:g,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:r,height:a}})}else for(let n of o){let a=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`video`)continue;let s=n.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:ys(n.attributes),autoselect:ys(n.attributes)||bs(n.attributes),languageCode:xs(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(t),peakBitrate:n.fullPath===null?m:null,averageBitrate:n.fullPath===null?h:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}else if(F.includes(r)){if(p!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);p=n;let r=e.attributes.get(`audio`);if(r===null){let n=e.attributes.get(`channels`),r=n===null?null:Number(n.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:m,averageBitrate:h,name:g,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:r!==null&&Number.isInteger(r)&&r>0?r:null}})}else for(let n of o){let a=n.attributes.get(`group-id`),o=n.attributes.get(`type`);if(a!==r||o.toLowerCase()!==`audio`)continue;let s=n.attributes.get(`channels`)??e.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:ys(n.attributes),autoselect:ys(n.attributes)||bs(n.attributes),languageCode:xs(n.attributes.get(`language`)),lineNumber:n.lineNumber,fullPath:n.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:n.fullPath===null?m:null,averageBitrate:n.fullPath===null?h:null,name:n.attributes.get(`name`),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}return i})),c=[],l=e=>{let t=c.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=c.length+1,c.push(e))};for(let e of s)for(let t of e)l(t);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of c)e.info.type===`video`?this.trackBackings.push(new _s(e)):this.trackBackings.push(new vs(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),n(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 ms(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ko}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},gs=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(r.length===1)t=r[0];else if(this instanceof _s){for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}else{n(this instanceof vs);for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...Ut,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(){n(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},_s=class extends gs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return Kr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},vs=class extends gs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return Kr(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()}};const ys=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}".`)},bs=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}".`)},xs=e=>e===null?`und`:e.split(`-`)[0]||`und`;
|
|
289
289
|
/*!
|
|
290
290
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
291
291
|
*
|
|
@@ -293,7 +293,7 @@ super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=n
|
|
|
293
293
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
294
294
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
295
295
|
*/
|
|
296
|
-
var
|
|
296
|
+
var Ss=class{constructor(){this._isIsobmff=!1}},Cs=class extends Ss{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(k(t)&&(t=await t),!t)return null;t.skip(4);let n=G(t,4);return n!==`ftyp`&&n!==`styp`?null:G(t,4)}_createDemuxer(e){return new Li(e)}},ws=class extends Cs{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=0;for(let t=0;t<10;t++){let t=e._reader.requestSlice(n,8);if(k(t)&&(t=await t),!t)return!1;let r=W(t),i=8;if(r===1){let t=e._reader.requestSlice(n+8,8);if(k(t)&&(t=await t),!t)return!1;r=xu(t),i=16}if(r<i)return!1;let a=G(t,4);if(a===`moof`||a===`sidx`)return!0;if(a===`emsg`||a===`prft`||a===`free`)n+=r;else return!1}return!1}get name(){return`MP4`}get mimeType(){return`video/mp4`}},Ts=class extends Cs{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Es=class extends Ss{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(k(n)&&(n=await n),!n)return!1;let r=ma(n);if(r===null||r<1||r>8||R(n,r)!==L.EBML)return!1;let i=va(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(k(a)&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=ya(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case L.EBMLVersion:if(R(a,r)!==1)return!1;break;case L.EBMLReadVersion:if(R(a,r)!==1)return!1;break;case L.DocType:if(ba(a,r)!==t)return!1;break;case L.DocTypeVersion:if(R(a,r)>4)return!1}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new Na(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},Ds=class extends Es{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},Os=class extends Ss{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(k(n)&&(n=await n),!n)break;let r=Mu(n);if(!r)break;t=n.filePos+r.size}let n=await La(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=ci(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(k(a)&&(a=await a),!a)return!1;let o=W(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await La(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 Ra(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},ks=class extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(k(t)&&(t=await t),!t)return!1;let n=G(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),G(t,4)===`WAVE`)}_createDemuxer(e){return new Qa(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},As=class extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return k(t)&&(t=await t),t?G(t,4)===`OggS`:!1}_createDemuxer(e){return new qa(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},js=class extends Ss{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(k(n)&&(n=await n),!n)break;let r=Mu(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSlice(t,4);return k(n)&&(n=await n),n?G(n,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new fo(e)}},Ms=class extends Ss{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(k(n)&&(n=await n),!n)break;let r=Mu(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(k(n)&&(n=await n),!n)return!1;let r=to(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),k(n)&&(n=await n),!n))return!1;let i=to(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new ro(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},Ns=class extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(k(t)&&(t=await t),!t)return!1;let n=V(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 bo(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Ps=class extends Ss{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(k(t)&&(t=await t),!t||G(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof Go))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 hs(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return ko}};const Fs=/* #__PURE__ */ new ws,Is=/* #__PURE__ */ new Ts,Ls=/* #__PURE__ */ new Es,Rs=/* #__PURE__ */ new Ds,zs=/* #__PURE__ */ new Os,Bs=/* #__PURE__ */ new ks,Vs=/* #__PURE__ */ new As,Hs=/* #__PURE__ */ new Ms,Us=/* #__PURE__ */ new js,Ws=/* #__PURE__ */ new Ns,Gs=/* #__PURE__ */ new Ps,Ks=[Gs,Fs,Is,Ls,Rs,Bs,Vs,Us,zs,Hs,Ws],qs=[Gs,Fs,Is,zs,Hs,Ws],Js=(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.`)}},Ys=/* @__PURE__ */ new Map,Xs=/* @__PURE__ */ new Map,Zs=(e,t)=>{
|
|
297
297
|
/*!
|
|
298
298
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
299
299
|
*
|
|
@@ -301,7 +301,7 @@ var xs=class{constructor(){this._isIsobmff=!1}},Ss=class extends xs{constructor(
|
|
|
301
301
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
302
302
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
303
303
|
*/
|
|
304
|
-
if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.codec!==void 0&&typeof t.codec!=`string`)throw TypeError(`options.codec, when provided, must be a string.`);if(t.codec!==void 0&&Kr(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw TypeError(`options.codedWidth, when provided, must be a positive integer.`);if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw TypeError(`options.codedHeight, when provided, must be a positive integer.`);if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw TypeError(`options.displayAspectWidth, when provided, must be a positive integer.`);if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw TypeError(`options.displayAspectHeight, when provided, must be a positive integer.`);if(t.description!==void 0&&!pe(t.description))throw TypeError(`options.description, when provided, must be a buffer source.`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!=`boolean`)throw TypeError(`options.optimizeForLatency, when provided, must be a boolean.`)},
|
|
304
|
+
if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.codec!==void 0&&typeof t.codec!=`string`)throw TypeError(`options.codec, when provided, must be a string.`);if(t.codec!==void 0&&Kr(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw TypeError(`options.codedWidth, when provided, must be a positive integer.`);if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw TypeError(`options.codedHeight, when provided, must be a positive integer.`);if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw TypeError(`options.displayAspectWidth, when provided, must be a positive integer.`);if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw TypeError(`options.displayAspectHeight, when provided, must be a positive integer.`);if(t.description!==void 0&&!pe(t.description))throw TypeError(`options.description, when provided, must be a buffer source.`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!=`boolean`)throw TypeError(`options.optimizeForLatency, when provided, must be a boolean.`)},Qs=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.codec!==void 0&&typeof t.codec!=`string`)throw TypeError(`options.codec, when provided, must be a string.`);if(t.codec!==void 0&&Kr(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw TypeError(`options.numberOfChannels, when provided, must be a positive integer.`);if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw TypeError(`options.sampleRate, when provided, must be a positive integer.`);if(t.description!==void 0&&!pe(t.description))throw TypeError(`options.description, when provided, must be a buffer source.`)},$s=e=>N.includes(e)?ec(e):F.includes(e)?tc(e):!1,ec=async(e,t={})=>{if(!N.includes(e))return!1;Zs(e,t);let n={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??Fr(e,1280,720,1e6,!1)};n.description??=void 0;let r=JSON.stringify(n),i=Ys.get(r);if(i)return i;let a=(async()=>xl.some(t=>t.supports(e,n))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(n)).supported===!0)();return Ys.set(r,a),a},tc=async(e,t={})=>{if(!F.includes(e))return!1;Qs(e,t);let n={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??Br(e,2,48e3)};if(n.description===void 0){let e=Hr(n);if(e===!1)return!1;n.description=e}let r=JSON.stringify(n),i=Xs.get(r);if(i)return i;let a=(async()=>Sl.some(t=>t.supports(e,n))||P.includes(e)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(n)).supported===!0)();return Xs.set(r,a),a},nc=async()=>{let[e,t]=await Promise.all([rc(),ic()]);return[...e,...t]},rc=async(e=N,t)=>{let n=await Promise.all(e.map(e=>ec(e,t)));return e.filter((e,t)=>n[t])},ic=async(e=F,t)=>{let n=await Promise.all(e.map(e=>tc(e,t)));return e.filter((e,t)=>n[t])};
|
|
305
305
|
/*!
|
|
306
306
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
307
307
|
*
|
|
@@ -309,7 +309,7 @@ if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.cod
|
|
|
309
309
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
310
310
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
311
311
|
*/
|
|
312
|
-
var ic=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},ac=(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});mt();let oc=-1/0,sc=-1/0,cc=null;typeof FinalizationRegistry<`u`&&(cc=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-oc>=1e3&&(A._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.`),oc=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-sc>=1e3&&(A._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.`),sc=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var lc=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}};const uc=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],dc=new Set(uc);var fc=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(We*this.timestamp)}get microsecondDuration(){return Math.trunc(We*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!dc.has(n.format))throw TypeError(`init.format must be one of: `+uc.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this.format=n.format,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0;let e=n.layout??Cc(n.format,n.codedWidth,n.codedHeight),r=n.colorSpace??null;r===null&&(r=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth),this._data=n._doNotCopy?S(t):S(t).slice(),this._layout=e,this.colorSpace=new vc(r)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.flip=n?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6;let{primaries:e,transfer:r,matrix:i,fullRange:a}=t.colorSpace;this.colorSpace=new vc({primaries:e!==null&&e in ie?e:null,transfer:r!==null&&r in oe?r:null,matrix:i!==null&&i in ce?i:null,fullRange:a})}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*We),duration:Math.trunc((n.duration??0)*We)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=n.visibleRect??{left:0,top:0,width:r,height:i},o=new OffscreenCanvas(a.width,a.height),s=o.getContext(`2d`,{alpha:$e(),willReadFrequently:!0});if(!s)throw Error(`OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.`);s.drawImage(t,-a.left,-a.top),this._data=o,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new vc({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof lc){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!uc.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=t.getColorSpace()}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=xt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),cc?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return n(this._data!==null),this._data instanceof lc?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):yc(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(n(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||=(cc?.unregister(this),this._data instanceof lc?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):yc(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(Sc(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return yc(this._data)?this._data.allocationSize(e):Tc(this,e).allocationSize}async copyTo(t,r={}){if(!pe(t))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(Sc(r),this._closed)throw Error(`VideoSample is closed.`);if((r.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(n(this._data!==null),yc(this._data))return this._data.copyTo(t,r);if(r.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(r.format)){if(this._data instanceof lc){let n={stack:[],error:void 0,hasError:!1};try{let i=ic(n,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},r.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(t,r)}catch(e){n.error=e,n.hasError=!0}finally{ac(n)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame(),n=await e.copyTo(t,r);return e.close(),n}}let i=Tc(this,r);n(this.format);let a=S(t);if(a.byteLength<i.allocationSize)throw TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);let o=wc(this.format),s;if(this._data instanceof lc){let e=this._data.getDataPlanes();if(k(e)&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);s=e}else if(this._data instanceof Uint8Array)n(this._layout),n(this._layout.length===o.length),s=this._layout.map((e,t)=>{let n=Math.ceil(this.codedHeight/o[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);n(e);let t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:S(t.data),stride:4*this.codedWidth}]}let c=[],l=o.length;for(let e=0;e<l;e++){let t=i.computedLayouts[e],n=s[e].stride,r=s[e].data,o=t.sourceTop*n;o+=t.sourceLeftBytes;let l=t.destinationOffset,u=t.sourceWidthBytes,d={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(o+u>r.byteLength)throw Error(`Source buffer OOB read.`);if(l+u>a.byteLength)throw Error(`Destination buffer OOB write.`);let e=r.subarray(o,o+u);a.set(e,l),o+=n,l+=t.destinationStride}c.push(d)}if(r.format!==void 0){let e=this.format.startsWith(`RGB`)!==r.format.startsWith(`RGB`),t=this.format.includes(`X`)&&r.format.includes(`A`);if(e||t)for(let n=0;n<i.allocationSize;n+=4){if(e){let e=a[n],t=a[n+2];a[n]=t,a[n+2]=e}t&&(a[n+3]=255)}}return c}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof lc){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(k(e))throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return yc(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(n(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._unmapSourceRegion(l,u,d,f,this.rotation,this.flip));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);t.crop!==void 0&&xc(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,a=t.flip??this.flip,[o,s]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&=bc(c,o,s);let l,u,d,f,{sx:p,sy:m,sWidth:h,sHeight:g}=this._unmapSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??o,t.crop?.height??s,i,a);if(t.fit===`fill`)l=0,u=0,d=n,f=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[o,s],a=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);d=e*a,f=i*a,l=(n-d)/2,u=(r-f)/2}e.save();let _=i%180==0?1:d/f;e.translate(n/2,r/2),a&&e.scale(-1,1),e.rotate(i*Math.PI/180),e.scale(1/_,_),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),p,m,h,g,l,u,d,f),e.restore()}_unmapSourceRegion(e,t,n,r,i,a){return a&&(e=(i%180==0?this.squarePixelWidth:this.squarePixelHeight)-e-n),i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}_drawWithFitAndMipmapping(e,t,n){let r=e.width,i=e.height,[a,o]=n.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=n.crop?n.crop.width:a,c=n.crop?n.crop.height:o,l=0;2*r<s&&2*i<c&&(l=Math.floor(Math.log2(Math.min(s/r,c/i))));let u=r*2**l,d=i*2**l,{canvas:f,context:p,isNew:m}=l>0?_c(u,d):{canvas:e,context:t,isNew:n.targetIsFresh};p.imageSmoothingQuality=`high`,n.fillBlack?(p.fillStyle=`black`,p.fillRect(0,0,u,d)):m||p.clearRect(0,0,u,d),this.drawWithFit(p,{fit:n.fit,rotation:n.rotation,flip:n.flip,crop:n.crop}),p.globalCompositeOperation=`copy`;for(let e=l;e>1;e--){let t=r*2**e,n=i*2**e;p.drawImage(f,0,0,t,n,0,0,t/2,n/2)}p.globalCompositeOperation=`source-over`,l>0&&(t.imageSmoothingQuality=`high`,t.globalCompositeOperation=`copy`,t.drawImage(f,0,0,2*r,2*i,0,0,r,i),t.globalCompositeOperation=`source-over`)}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof lc||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);if(t.crop!==void 0&&xc(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let{rotation:n,flip:r}=m(this.rotation,this.flip,t.rotate??0,t.flip??!1),[i,a]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=t.crop;o&&=bc(o,i,a);let s=o?o.width:i,c=o?o.height:a,l=s/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=s,d=c),u=Ie(u,t.roundDimensionsTo??1),d=Ie(d,t.roundDimensionsTo??1);let f={width:u,height:d,fit:t.fit??`fill`,rotation:n,flip:r,crop:o??{left:0,top:0,width:i,height:a},alpha:t.alpha??`keep`};for(let e of pc){let t=e(this,f);if(k(t)&&(t=await t),t!==null)return t}let{canvas:p,context:h,isNew:g}=_c(f.width,f.height);return this._drawWithFitAndMipmapping(p,h,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:g,fillBlack:f.alpha===`discard`}),new e(p,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setFlip(e){if(typeof e!=`boolean`)throw TypeError(`newFlip must be a boolean.`);this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}setEncodeOptions(e){if(!e||typeof e!=`object`)throw TypeError(`newEncodeOptions must be an object.`);this.encodeOptions=e}[Symbol.dispose](){this.close()}};const pc=[],mc=e=>{pc.includes(e)||pc.push(e)},hc=[];let gc=0;const _c=(e,t)=>{for(let n of hc)if(n.canvas.width===e&&n.canvas.height===t)return n.age=gc++,{canvas:n.canvas,context:n.context,isNew:!1};let n;if(typeof OffscreenCanvas<`u`)n=new OffscreenCanvas(e,t);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);n=document.createElement(`canvas`),n.width=e,n.height=t}let r=n.getContext(`2d`,{alpha:!0,willReadFrequently:!1});if(!r)throw Error(`The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.`);return hc.length>=3&&hc.splice(yt(hc,e=>e.age),1),hc.push({canvas:n,context:r,age:gc++}),{canvas:n,context:r,isNew:!0}};var vc=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(ie);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(oe);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(ce);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}};const yc=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,bc=(e,t,r)=>{let i=Math.min(e.left,t),a=Math.min(e.top,r),o=Math.min(e.width,t-i),s=Math.min(e.height,r-a);return n(o>=0),n(s>=0),{left:i,top:a,width:o,height:s}},xc=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},Sc=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},Cc=(e,t,n)=>{let r=wc(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},wc=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ee(e),n(!1)}},Tc=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=Ec(n,r,e.codedWidth,e.codedHeight,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return Oc(i,o,a)},Ec=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(t.width===0||t.height===0)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Dc(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},Dc=(e,t)=>{if(e===null)return!0;let n=wc(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},Oc=(e,t,n)=>{let r=wc(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},kc=/* @__PURE__ */ new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]);var Ac=class{constructor(){this._referenceCount=0}},jc=class e{get microsecondTimestamp(){return Math.trunc(We*this.timestamp)}get microsecondDuration(){return Math.trunc(We*this.duration)}constructor(e){if(this._closed=!1,Ic(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 Ac){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!kc.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(!kc.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/(Mc(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*Mc(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}cc?.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&&!kc.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=Mc(t),a=Nc(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(!pe(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&&!kc.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:r,frameCount:i,frameOffset:a}=t,{planeIndex:o}=t,s=this.format,c=r??this.format;if(!c)throw Error(`Destination format not determined`);let l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>=l)throw RangeError(`frameOffset out of range`);let f=i===void 0?l-d:i;if(f>l-d)throw RangeError(`frameCount out of range`);let p=Mc(c),m=Nc(c);if(m&&o>=u||!m&&o!==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 g=C(e),_=Fc(c);if(Ic(this._data)){if(Ze()&&u>2&&c!==s){Rc(this._data,g,s,c,u,o,d,f);return}try{this._data.copyTo(e,{planeIndex:o,frameOffset:d,frameCount:f,format:c});return}catch(e){if(c===`f32-planar`)throw e;s=`f32-planar`}}let v=Pc(s),y=Mc(s),b=Nc(s),x;if(this._data instanceof Ac){let e=e=>{let t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw TypeError(`getDataPlane() must return a Uint8Array.`);let n=l*y*(b?1:u);if(t.byteLength!==n)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${n} bytes, got ${t.byteLength} bytes.`);return t};if(b){if(m)x=e(o),o=0;else{x=new Uint8Array(l*y*u);for(let t=0;t<u;t++){let n=e(t);x.set(n,t*l*y)}}}else x=e(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(n(s===`f32-planar`),m)x=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:o})),this._data.copyTo(x,{format:`f32-planar`,planeIndex:o}),o=0;else{x=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:0})*u);for(let e=0;e<u;e++)this._data.copyTo(x.subarray(e*l*y,(e+1)*l*y),{format:`f32-planar`,planeIndex:e})}let S=C(x);for(let e=0;e<f;e++)if(m){let t=e*p,n;n=b?(o*l+(e+d))*y:((e+d)*u+o)*y,_(g,t,v(S,n))}else for(let t=0;t<u;t++){let n=(e*u+t)*p,r;r=b?(t*l+(e+d))*y:((e+d)*u+t)*y,_(g,n,v(S,r))}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(this._data instanceof Ac){let t=new e(this._data);return t.setTimestamp(this.timestamp),t}if(Ic(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}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(`startFrame must be a non-negative integer.`);if(!Number.isInteger(n)||n<0)throw TypeError(`endFrame must be a non-negative integer.`);if(t>this.numberOfFrames)throw RangeError(`startFrame out of range.`);if(n>this.numberOfFrames)throw RangeError(`endFrame out of range.`);if(n<t)throw RangeError(`endFrame must not be less than startFrame.`);if(this._closed)throw Error(`AudioSample is closed.`);let r=n-t,i=Mc(this.format),a;if(Nc(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||=(cc?.unregister(this),this._data instanceof Ac?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ic(this._data)?this._data.close():this._data=/* @__PURE__ */ new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);return this._data instanceof Ac?this._createAudioDataFromData():Ic(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(Nc(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})}{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}};const Mc=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`)}},Nc=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},Pc=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)}},Fc=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,O(Math.round(n*128)+128,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,O(Math.round(n*32768),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,O(Math.round(n*2147483648),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},Ic=e=>typeof AudioData<`u`&&e instanceof AudioData,Lc=e=>{switch(e){case`u8-planar`:return`u8`;case`s16-planar`:return`s16`;case`s32-planar`:return`s32`;case`f32-planar`:return`f32`;default:return e}},Rc=(e,t,n,r,i,a,o,s)=>{let c=Pc(n),l=Fc(r),u=Mc(n),d=Mc(r),f=Nc(n);if(Nc(r)){if(f){let r=new ArrayBuffer(s*u),i=C(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=C(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=C(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=C(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},zc=(e,t)=>{let n=e.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(n);return e.copyTo(r,{format:t,planeIndex:0}),new jc({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})},Bc=/* @__PURE__ */ new Map,Vc=/* @__PURE__ */ new Map,Hc=e=>{
|
|
312
|
+
var ac=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},oc=(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});mt();let sc=-1/0,cc=-1/0,lc=null;typeof FinalizationRegistry<`u`&&(lc=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-sc>=1e3&&(A._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.`),sc=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-cc>=1e3&&(A._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.`),cc=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var uc=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}};const dc=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],fc=new Set(dc);var pc=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(We*this.timestamp)}get microsecondDuration(){return Math.trunc(We*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!fc.has(n.format))throw TypeError(`init.format must be one of: `+dc.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this.format=n.format,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0;let e=n.layout??wc(n.format,n.codedWidth,n.codedHeight),r=n.colorSpace??null;r===null&&(r=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth),this._data=n._doNotCopy?S(t):S(t).slice(),this._layout=e,this.colorSpace=new yc(r)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.flip=n?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6;let{primaries:e,transfer:r,matrix:i,fullRange:a}=t.colorSpace;this.colorSpace=new yc({primaries:e!==null&&e in ie?e:null,transfer:r!==null&&r in oe?r:null,matrix:i!==null&&i in ce?i:null,fullRange:a})}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.visibleRect!==void 0&&St(n.visibleRect,`init.visibleRect`),typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*We),duration:Math.trunc((n.duration??0)*We)||void 0,visibleRect:n.visibleRect&&{x:n.visibleRect.left,y:n.visibleRect.top,width:n.visibleRect.width,height:n.visibleRect.height}}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=n.visibleRect??{left:0,top:0,width:r,height:i},o=new OffscreenCanvas(a.width,a.height),s=o.getContext(`2d`,{alpha:$e(),willReadFrequently:!0});if(!s)throw Error(`OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.`);s.drawImage(t,-a.left,-a.top),this._data=o,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new yc({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof uc){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n.flip!==void 0&&typeof n.flip!=`boolean`)throw TypeError(`init.flip, when provided, must be a boolean.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!dc.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=n.rotation??0,this.flip=n.flip??!1,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=t.getColorSpace()}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.encodeOptions=n?.encodeOptions??{},this.pixelAspectRatio=xt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),lc?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return n(this._data!==null),this._data instanceof uc?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):bc(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(n(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||=(lc?.unregister(this),this._data instanceof uc?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):bc(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(Cc(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return bc(this._data)?this._data.allocationSize(e):Ec(this,e).allocationSize}async copyTo(t,r={}){if(!pe(t))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(Cc(r),this._closed)throw Error(`VideoSample is closed.`);if((r.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(n(this._data!==null),bc(this._data))return this._data.copyTo(t,r);if(r.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(r.format)){if(this._data instanceof uc){let n={stack:[],error:void 0,hasError:!1};try{let i=ac(n,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},r.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(t,r)}catch(e){n.error=e,n.hasError=!0}finally{oc(n)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame(),n=await e.copyTo(t,r);return e.close(),n}}let i=Ec(this,r);n(this.format);let a=S(t);if(a.byteLength<i.allocationSize)throw TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);let o=Tc(this.format),s;if(this._data instanceof uc){let e=this._data.getDataPlanes();if(k(e)&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);s=e}else if(this._data instanceof Uint8Array)n(this._layout),n(this._layout.length===o.length),s=this._layout.map((e,t)=>{let n=Math.ceil(this.codedHeight/o[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);n(e);let t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:S(t.data),stride:4*this.codedWidth}]}let c=[],l=o.length;for(let e=0;e<l;e++){let t=i.computedLayouts[e],n=s[e].stride,r=s[e].data,o=t.sourceTop*n;o+=t.sourceLeftBytes;let l=t.destinationOffset,u=t.sourceWidthBytes,d={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(o+u>r.byteLength)throw Error(`Source buffer OOB read.`);if(l+u>a.byteLength)throw Error(`Destination buffer OOB write.`);let e=r.subarray(o,o+u);a.set(e,l),o+=n,l+=t.destinationStride}c.push(d)}if(r.format!==void 0){let e=this.format.startsWith(`RGB`)!==r.format.startsWith(`RGB`),t=this.format.includes(`X`)&&r.format.includes(`A`);if(e||t)for(let n=0;n<i.allocationSize;n+=4){if(e){let e=a[n],t=a[n+2];a[n]=t,a[n+2]=e}t&&(a[n+3]=255)}}return c}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof uc){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(k(e))throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return bc(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(n(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._unmapSourceRegion(l,u,d,f,this.rotation,this.flip));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);t.crop!==void 0&&Sc(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,a=t.flip??this.flip,[o,s]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=t.crop;c&&=xc(c,o,s);let l,u,d,f,{sx:p,sy:m,sWidth:h,sHeight:g}=this._unmapSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??o,t.crop?.height??s,i,a);if(t.fit===`fill`)l=0,u=0,d=n,f=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[o,s],a=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);d=e*a,f=i*a,l=(n-d)/2,u=(r-f)/2}e.save();let _=i%180==0?1:d/f;e.translate(n/2,r/2),a&&e.scale(-1,1),e.rotate(i*Math.PI/180),e.scale(1/_,_),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),p,m,h,g,l,u,d,f),e.restore()}_unmapSourceRegion(e,t,n,r,i,a){return a&&(e=(i%180==0?this.squarePixelWidth:this.squarePixelHeight)-e-n),i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}_drawWithFitAndMipmapping(e,t,n){let r=e.width,i=e.height,[a,o]=n.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=n.crop?n.crop.width:a,c=n.crop?n.crop.height:o,l=0;2*r<s&&2*i<c&&(l=Math.floor(Math.log2(Math.min(s/r,c/i))));let u=r*2**l,d=i*2**l,{canvas:f,context:p,isNew:m}=l>0?vc(u,d):{canvas:e,context:t,isNew:n.targetIsFresh};p.imageSmoothingQuality=`high`,n.fillBlack?(p.fillStyle=`black`,p.fillRect(0,0,u,d)):m||p.clearRect(0,0,u,d),this.drawWithFit(p,{fit:n.fit,rotation:n.rotation,flip:n.flip,crop:n.crop}),p.globalCompositeOperation=`copy`;for(let e=l;e>1;e--){let t=r*2**e,n=i*2**e;p.drawImage(f,0,0,t,n,0,0,t/2,n/2)}p.globalCompositeOperation=`source-over`,l>0&&(t.imageSmoothingQuality=`high`,t.globalCompositeOperation=`copy`,t.drawImage(f,0,0,2*r,2*i,0,0,r,i),t.globalCompositeOperation=`source-over`)}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof uc||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);if(t.crop!==void 0&&Sc(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let{rotation:n,flip:r}=m(this.rotation,this.flip,t.rotate??0,t.flip??!1),[i,a]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=t.crop;o&&=xc(o,i,a);let s=o?o.width:i,c=o?o.height:a,l=s/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=s,d=c),u=Ie(u,t.roundDimensionsTo??1),d=Ie(d,t.roundDimensionsTo??1);let f={width:u,height:d,fit:t.fit??`fill`,rotation:n,flip:r,crop:o??{left:0,top:0,width:i,height:a},alpha:t.alpha??`keep`};for(let e of mc){let t=e(this,f);if(k(t)&&(t=await t),t!==null)return t}let{canvas:p,context:h,isNew:g}=vc(f.width,f.height);return this._drawWithFitAndMipmapping(p,h,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:g,fillBlack:f.alpha===`discard`}),new e(p,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setFlip(e){if(typeof e!=`boolean`)throw TypeError(`newFlip must be a boolean.`);this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}setEncodeOptions(e){if(!e||typeof e!=`object`)throw TypeError(`newEncodeOptions must be an object.`);this.encodeOptions=e}[Symbol.dispose](){this.close()}};const mc=[],hc=e=>{mc.includes(e)||mc.push(e)},gc=[];let _c=0;const vc=(e,t)=>{for(let n of gc)if(n.canvas.width===e&&n.canvas.height===t)return n.age=_c++,{canvas:n.canvas,context:n.context,isNew:!1};let n;if(typeof OffscreenCanvas<`u`)n=new OffscreenCanvas(e,t);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);n=document.createElement(`canvas`),n.width=e,n.height=t}let r=n.getContext(`2d`,{alpha:!0,willReadFrequently:!1});if(!r)throw Error(`The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.`);return gc.length>=3&&gc.splice(yt(gc,e=>e.age),1),gc.push({canvas:n,context:r,age:_c++}),{canvas:n,context:r,isNew:!0}};var yc=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(ie);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(oe);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(ce);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}};const bc=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,xc=(e,t,r)=>{let i=Math.min(e.left,t),a=Math.min(e.top,r),o=Math.min(e.width,t-i),s=Math.min(e.height,r-a);return n(o>=0),n(s>=0),{left:i,top:a,width:o,height:s}},Sc=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},Cc=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},wc=(e,t,n)=>{let r=Tc(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},Tc=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ee(e),n(!1)}},Ec=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=Dc(n,r,e.codedWidth,e.codedHeight,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return kc(i,o,a)},Dc=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(t.width===0||t.height===0)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Oc(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},Oc=(e,t)=>{if(e===null)return!0;let n=Tc(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},kc=(e,t,n)=>{let r=Tc(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},Ac=/* @__PURE__ */ new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]);var jc=class{constructor(){this._referenceCount=0}},Mc=class e{get microsecondTimestamp(){return Math.trunc(We*this.timestamp)}get microsecondDuration(){return Math.trunc(We*this.duration)}constructor(e){if(this._closed=!1,Lc(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 jc){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Ac.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(!Ac.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/(Nc(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*Nc(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}lc?.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&&!Ac.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=Nc(t),a=Pc(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(!pe(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&&!Ac.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:r,frameCount:i,frameOffset:a}=t,{planeIndex:o}=t,s=this.format,c=r??this.format;if(!c)throw Error(`Destination format not determined`);let l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>=l)throw RangeError(`frameOffset out of range`);let f=i===void 0?l-d:i;if(f>l-d)throw RangeError(`frameCount out of range`);let p=Nc(c),m=Pc(c);if(m&&o>=u||!m&&o!==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 g=C(e),_=Ic(c);if(Lc(this._data)){if(Ze()&&u>2&&c!==s){zc(this._data,g,s,c,u,o,d,f);return}try{this._data.copyTo(e,{planeIndex:o,frameOffset:d,frameCount:f,format:c});return}catch(e){if(c===`f32-planar`)throw e;s=`f32-planar`}}let v=Fc(s),y=Nc(s),b=Pc(s),x;if(this._data instanceof jc){let e=e=>{let t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw TypeError(`getDataPlane() must return a Uint8Array.`);let n=l*y*(b?1:u);if(t.byteLength!==n)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${n} bytes, got ${t.byteLength} bytes.`);return t};if(b){if(m)x=e(o),o=0;else{x=new Uint8Array(l*y*u);for(let t=0;t<u;t++){let n=e(t);x.set(n,t*l*y)}}}else x=e(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(n(s===`f32-planar`),m)x=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:o})),this._data.copyTo(x,{format:`f32-planar`,planeIndex:o}),o=0;else{x=new Uint8Array(this._data.allocationSize({format:`f32-planar`,planeIndex:0})*u);for(let e=0;e<u;e++)this._data.copyTo(x.subarray(e*l*y,(e+1)*l*y),{format:`f32-planar`,planeIndex:e})}let S=C(x);for(let e=0;e<f;e++)if(m){let t=e*p,n;n=b?(o*l+(e+d))*y:((e+d)*u+o)*y,_(g,t,v(S,n))}else for(let t=0;t<u;t++){let n=(e*u+t)*p,r;r=b?(t*l+(e+d))*y:((e+d)*u+t)*y,_(g,n,v(S,r))}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(this._data instanceof jc){let t=new e(this._data);return t.setTimestamp(this.timestamp),t}if(Lc(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}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(`startFrame must be a non-negative integer.`);if(!Number.isInteger(n)||n<0)throw TypeError(`endFrame must be a non-negative integer.`);if(t>this.numberOfFrames)throw RangeError(`startFrame out of range.`);if(n>this.numberOfFrames)throw RangeError(`endFrame out of range.`);if(n<t)throw RangeError(`endFrame must not be less than startFrame.`);if(this._closed)throw Error(`AudioSample is closed.`);let r=n-t,i=Nc(this.format),a;if(Pc(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||=(lc?.unregister(this),this._data instanceof jc?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Lc(this._data)?this._data.close():this._data=/* @__PURE__ */ new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);return this._data instanceof jc?this._createAudioDataFromData():Lc(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(Pc(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})}{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}};const Nc=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`)}},Pc=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},Fc=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)}},Ic=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,O(Math.round(n*128)+128,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,O(Math.round(n*32768),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,O(Math.round(n*2147483648),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},Lc=e=>typeof AudioData<`u`&&e instanceof AudioData,Rc=e=>{switch(e){case`u8-planar`:return`u8`;case`s16-planar`:return`s16`;case`s32-planar`:return`s32`;case`f32-planar`:return`f32`;default:return e}},zc=(e,t,n,r,i,a,o,s)=>{let c=Fc(n),l=Ic(r),u=Nc(n),d=Nc(r),f=Pc(n);if(Pc(r)){if(f){let r=new ArrayBuffer(s*u),i=C(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=C(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=C(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=C(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},Bc=(e,t)=>{let n=e.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(n);return e.copyTo(r,{format:t,planeIndex:0}),new Mc({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})},Vc=/* @__PURE__ */ new Map,Hc=/* @__PURE__ */ new Map,Uc=e=>{
|
|
313
313
|
/*!
|
|
314
314
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
315
315
|
*
|
|
@@ -317,7 +317,7 @@ var ic=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)t
|
|
|
317
317
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
318
318
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
319
319
|
*/
|
|
320
|
-
if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!N.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${N.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.flip!==void 0&&typeof e.transform.flip!=`boolean`)throw TypeError(`config.transform.flip, when provided, must be a boolean.`);if(e.transform.crop!==void 0&&xc(e.transform.crop,`config.transform.`),e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`);if(e.transform.frameRate!==void 0&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError(`config.transform.frameRate, when provided, must be a finite positive number.`);if(e.transform.force!==void 0&&typeof e.transform.force!=`boolean`)throw TypeError(`config.transform.force, when provided, must be a boolean.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);Uc(e.codec,e)},Uc=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Kr(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},Wc=e=>{let t=e.bitrateMode,r=e.quality._toVideoRateControl(e.codec,e.width,e.height,t),i=(t,n,r)=>({codec:e.fullCodecString??Fr(e.codec,e.width,e.height,r,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:n,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...qr(e.codec)}),a=[];return r.quantizer!==null&&a.push({config:i(void 0,`quantizer`,r.bitrate),quantizer:r.quantizer}),r.bitrateMode!==`quantizer`&&a.push({config:i(r.bitrate,r.bitrateMode,r.bitrate),quantizer:null}),n(a.length>0),a},Gc=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!F.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${F.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(P.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.quality must be provided for compressed audio codecs.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);Kc(e.codec,e)},Kc=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Kr(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},qc=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??Br(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...Jr(e.codec)}};var z=class{constructor(e){if((typeof e==`number`||typeof e==`string`)&&(e={quality:e}),!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.bitrateMode!==void 0&&![`constant`,`variable`].includes(e.bitrateMode))throw TypeError(`options.bitrateMode, when provided, must be 'constant' or 'variable'.`);if(`quality`in e){if(typeof e.quality==`string`?!(e.quality in Jc):typeof e.quality!=`number`||Number.isNaN(e.quality))throw TypeError(`options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.`);if(e.preferBitrate!==void 0&&typeof e.preferBitrate!=`boolean`)throw TypeError(`options.preferBitrate, when provided, must be a boolean.`);if(`bitrate`in e||`quantizer`in e)throw TypeError(`options.quality cannot be combined with options.bitrate or options.quantizer.`);this._quality=typeof e.quality==`string`?Jc[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.bitrate, when provided, must be a positive integer.`);if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw TypeError(`options.quantizer, when provided, must be a non-negative integer.`);if(e.bitrate===void 0&&e.quantizer===void 0)throw TypeError(`At least one of options.bitrate or options.quantizer must be set.`);if(`preferBitrate`in e)throw TypeError(`options.preferBitrate can only be combined with options.quality.`);this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,r,i){let a=Yc[e],o=null,s=this._bitrateMode??i??`variable`;if(this._quantizer!==void 0){if(!a){if(this._bitrate===void 0)throw Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else if(this._quantizer<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${a.min} and ${a.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(s=`quantizer`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(n(this._quality!==void 0),o=O(Math.round(Ne(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let i=this._quality;i===void 0&&(n(o!==null&&a),i=O((o-a.worst)/(a.best-a.worst),0,1)),c=Zc(e,t,r,Xc(i))}return{quantizer:o,bitrate:c,bitrateMode:s}}_toVideoBitrate(e,t,r){return this._bitrate===void 0?(n(this._quality!==void 0),Zc(e,t,r,Xc(this._quality))):this._bitrate}_toAudioBitrate(e){if(P.includes(e)||e===`flac`)return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw Error(`This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.`);let t=Xc(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw Error(`Unhandled codec: ${e}`);let r=n*t;return e===`aac`?r=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e):e===`opus`||e===`vorbis`?r=Math.max(6e3,r):e===`mp3`&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)),Math.round(r/1e3)*1e3}};const Jc={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Yc={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(rt()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},Xc=e=>.3*Math.exp(2.5538*e),Zc=(e,t,n,r)=>{let i=t*n,a=3e6,o=a*(i/2073600)**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a}[e]*r;return Math.ceil(o/1e3)*1e3},Qc=(e,t)=>{if(e===`avc`)return{avc:{quantizer:t}};if(e===`hevc`)return{hevc:{quantizer:t}};if(e===`vp9`)return{vp9:{quantizer:t}};if(e===`av1`)return{av1:{quantizer:t}};n(!1)},$c=/* #__PURE__ */ new z(`very-low`),el=/* #__PURE__ */ new z(`low`),tl=/* #__PURE__ */ new z(`medium`),nl=/* #__PURE__ */ new z(`high`),rl=/* #__PURE__ */ new z(`very-high`),il=e=>{if(N.includes(e))return al(e);if(F.includes(e))return ol(e);if(Dr.includes(e))return cl(e);throw TypeError(`Unknown codec '${e}'.`)},al=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!N.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof z))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof z)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw TypeError(`frameRate, when provided, must be a finite positive number.`);Uc(e,s);let c=sl(i,a)??new z(`medium`),l;try{l=Wc({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let u=JSON.stringify(l),d=Bc.get(u);if(d)return d;let f=(async()=>{for(let{config:t}of l)if(Sl.some(n=>n.supports(e,t)))return!0;if(typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`))return!1;for(let{config:t,quantizer:i}of l){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!$e()||await new Promise(async a=>{try{let o=new VideoEncoder({output:()=>{},error:()=>a(!1)});o.configure(t);let s=new Uint8Array(n*r*4),c=new VideoFrame(s,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});o.encode(c,i===null?void 0:Qc(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return Bc.set(u,f),f},ol=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:a,...o}=t;if(!F.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(i!==void 0&&!(i instanceof z))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof z)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer.`);Kc(e,o);let s=sl(i,a)??new z(`medium`),c=qc({codec:e,numberOfChannels:n,sampleRate:r,quality:s,...o}),l=JSON.stringify(c),u=Vc.get(l);if(u)return u;let d=(async()=>{if(Cl.some(t=>t.supports(e,c))||P.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Vc.set(l,d),d},sl=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof z?t:new z({bitrate:t})},cl=async e=>!!Dr.includes(e),ll=async()=>{let[e,t,n]=await Promise.all([ul(),dl(),fl()]);return[...e,...t,...n]},ul=async(e=N,t)=>{let n=await Promise.all(e.map(e=>al(e,t)));return e.filter((e,t)=>n[t])},dl=async(e=F,t)=>{let n=await Promise.all(e.map(e=>ol(e,t)));return e.filter((e,t)=>n[t])},fl=async(e=Dr)=>{let t=await Promise.all(e.map(cl));return e.filter((e,n)=>t[n])},pl=async(e,t)=>{for(let n of e)if(await al(n,t))return n;return null},ml=async(e,t)=>{for(let n of e)if(await ol(n,t))return n;return null},hl=async e=>{for(let t of e)if(await cl(t))return t;return null};
|
|
320
|
+
if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!N.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${N.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.flip!==void 0&&typeof e.transform.flip!=`boolean`)throw TypeError(`config.transform.flip, when provided, must be a boolean.`);if(e.transform.crop!==void 0&&Sc(e.transform.crop,`config.transform.`),e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`);if(e.transform.frameRate!==void 0&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError(`config.transform.frameRate, when provided, must be a finite positive number.`);if(e.transform.force!==void 0&&typeof e.transform.force!=`boolean`)throw TypeError(`config.transform.force, when provided, must be a boolean.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);Wc(e.codec,e)},Wc=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Kr(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},Gc=e=>{let t=e.bitrateMode,r=e.quality._toVideoRateControl(e.codec,e.width,e.height,t),i=(t,n,r)=>({codec:e.fullCodecString??Fr(e.codec,e.width,e.height,r,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:n,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...qr(e.codec)}),a=[];return r.quantizer!==null&&a.push({config:i(void 0,`quantizer`,r.bitrate),quantizer:r.quantizer}),r.bitrateMode!==`quantizer`&&a.push({config:i(r.bitrate,r.bitrateMode,r.bitrate),quantizer:null}),n(a.length>0),a},Kc=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!F.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${F.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(P.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.quality must be provided for compressed audio codecs.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);qc(e.codec,e)},qc=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Kr(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},Jc=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??Br(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...Jr(e.codec)}};var z=class{constructor(e){if((typeof e==`number`||typeof e==`string`)&&(e={quality:e}),!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.bitrateMode!==void 0&&![`constant`,`variable`].includes(e.bitrateMode))throw TypeError(`options.bitrateMode, when provided, must be 'constant' or 'variable'.`);if(`quality`in e){if(typeof e.quality==`string`?!(e.quality in Yc):typeof e.quality!=`number`||Number.isNaN(e.quality))throw TypeError(`options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.`);if(e.preferBitrate!==void 0&&typeof e.preferBitrate!=`boolean`)throw TypeError(`options.preferBitrate, when provided, must be a boolean.`);if(`bitrate`in e||`quantizer`in e)throw TypeError(`options.quality cannot be combined with options.bitrate or options.quantizer.`);this._quality=typeof e.quality==`string`?Yc[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.bitrate, when provided, must be a positive integer.`);if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw TypeError(`options.quantizer, when provided, must be a non-negative integer.`);if(e.bitrate===void 0&&e.quantizer===void 0)throw TypeError(`At least one of options.bitrate or options.quantizer must be set.`);if(`preferBitrate`in e)throw TypeError(`options.preferBitrate can only be combined with options.quality.`);this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,r,i){let a=Xc[e],o=null,s=this._bitrateMode??i??`variable`;if(this._quantizer!==void 0){if(!a){if(this._bitrate===void 0)throw Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else if(this._quantizer<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${a.min} and ${a.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(s=`quantizer`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(n(this._quality!==void 0),o=O(Math.round(Ne(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let i=this._quality;i===void 0&&(n(o!==null&&a),i=O((o-a.worst)/(a.best-a.worst),0,1)),c=Qc(e,t,r,Zc(i))}return{quantizer:o,bitrate:c,bitrateMode:s}}_toVideoBitrate(e,t,r){return this._bitrate===void 0?(n(this._quality!==void 0),Qc(e,t,r,Zc(this._quality))):this._bitrate}_toAudioBitrate(e){if(P.includes(e)||e===`flac`)return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw Error(`This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.`);let t=Zc(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw Error(`Unhandled codec: ${e}`);let r=n*t;return e===`aac`?r=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e):e===`opus`||e===`vorbis`?r=Math.max(6e3,r):e===`mp3`&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)),Math.round(r/1e3)*1e3}};const Yc={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Xc={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(rt()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},Zc=e=>.3*Math.exp(2.5538*e),Qc=(e,t,n,r)=>{let i=t*n,a=3e6,o=a*(i/2073600)**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a}[e]*r;return Math.ceil(o/1e3)*1e3},$c=(e,t)=>{if(e===`avc`)return{avc:{quantizer:t}};if(e===`hevc`)return{hevc:{quantizer:t}};if(e===`vp9`)return{vp9:{quantizer:t}};if(e===`av1`)return{av1:{quantizer:t}};n(!1)},el=/* #__PURE__ */ new z(`very-low`),tl=/* #__PURE__ */ new z(`low`),nl=/* #__PURE__ */ new z(`medium`),rl=/* #__PURE__ */ new z(`high`),il=/* #__PURE__ */ new z(`very-high`),al=e=>{if(N.includes(e))return ol(e);if(F.includes(e))return sl(e);if(Dr.includes(e))return ll(e);throw TypeError(`Unknown codec '${e}'.`)},ol=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!N.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof z))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof z)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw TypeError(`frameRate, when provided, must be a finite positive number.`);Wc(e,s);let c=cl(i,a)??new z(`medium`),l;try{l=Gc({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let u=JSON.stringify(l),d=Vc.get(u);if(d)return d;let f=(async()=>{for(let{config:t}of l)if(Cl.some(n=>n.supports(e,t)))return!0;if(typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`))return!1;for(let{config:t,quantizer:i}of l){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!$e()||await new Promise(async a=>{try{let o=new VideoEncoder({output:()=>{},error:()=>a(!1)});o.configure(t);let s=new Uint8Array(n*r*4),c=new VideoFrame(s,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});o.encode(c,i===null?void 0:$c(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return Vc.set(u,f),f},sl=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:a,...o}=t;if(!F.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(i!==void 0&&!(i instanceof z))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof z)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer.`);qc(e,o);let s=cl(i,a)??new z(`medium`),c=Jc({codec:e,numberOfChannels:n,sampleRate:r,quality:s,...o}),l=JSON.stringify(c),u=Hc.get(l);if(u)return u;let d=(async()=>{if(wl.some(t=>t.supports(e,c))||P.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Hc.set(l,d),d},cl=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof z?t:new z({bitrate:t})},ll=async e=>!!Dr.includes(e),ul=async()=>{let[e,t,n]=await Promise.all([dl(),fl(),pl()]);return[...e,...t,...n]},dl=async(e=N,t)=>{let n=await Promise.all(e.map(e=>ol(e,t)));return e.filter((e,t)=>n[t])},fl=async(e=F,t)=>{let n=await Promise.all(e.map(e=>sl(e,t)));return e.filter((e,t)=>n[t])},pl=async(e=Dr)=>{let t=await Promise.all(e.map(ll));return e.filter((e,n)=>t[n])},ml=async(e,t)=>{for(let n of e)if(await ol(n,t))return n;return null},hl=async(e,t)=>{for(let n of e)if(await sl(n,t))return n;return null},gl=async e=>{for(let t of e)if(await ll(t))return t;return null};
|
|
321
321
|
/*!
|
|
322
322
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
323
323
|
*
|
|
@@ -325,7 +325,7 @@ if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);
|
|
|
325
325
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
326
326
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
327
327
|
*/
|
|
328
|
-
var
|
|
328
|
+
var _l=class{static supports(e,t){return!1}},vl=class{static supports(e,t){return!1}},yl=class{static supports(e,t){return!1}},bl=class{static supports(e,t){return!1}};const xl=[],Sl=[],Cl=[],wl=[],Tl=e=>{if(e.prototype instanceof _l){let t=e;if(xl.includes(t)){A._warn(`Video decoder already registered.`);return}xl.push(t),Ys.clear()}else if(e.prototype instanceof vl){let t=e;if(Sl.includes(t)){A._warn(`Audio decoder already registered.`);return}Sl.push(t),Xs.clear()}else throw TypeError(`Decoder must be a CustomVideoDecoder or CustomAudioDecoder.`)},El=e=>{if(e.prototype instanceof yl){let t=e;if(Cl.includes(t)){A._warn(`Video encoder already registered.`);return}Cl.push(t),Vc.clear()}else if(e.prototype instanceof bl){let t=e;if(wl.includes(t)){A._warn(`Audio encoder already registered.`);return}wl.push(t),Hc.clear()}else throw TypeError(`Encoder must be a CustomVideoEncoder or CustomAudioEncoder.`)},Dl=e=>{
|
|
329
329
|
/*!
|
|
330
330
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
331
331
|
*
|
|
@@ -333,7 +333,7 @@ var gl=class{static supports(e,t){return!1}},_l=class{static supports(e,t){retur
|
|
|
333
333
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
334
334
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
335
335
|
*/
|
|
336
|
-
let t=8191,n=e>>2,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},
|
|
336
|
+
let t=8191,n=e>>2,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},Ol=e=>{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)<<2},kl=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e>>3;for(o<0?o=-o-1:r=128,o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},Al=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)<<3},jl=e=>{
|
|
337
337
|
/*!
|
|
338
338
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
339
339
|
*
|
|
@@ -341,7 +341,7 @@ let t=8191,n=e>>2,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&
|
|
|
341
341
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
342
342
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
343
343
|
*/
|
|
344
|
-
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.`)},jl=e=>{if(!ht(e))throw TypeError(`timestamp must be a number.`)},Ml=(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 Nl=class{constructor(e){if(!(e instanceof ql))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(Al(e),this._track.input._disposed)throw new cu;return Ml(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Al(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(jl(e),Al(t),this._track.input._disposed)throw new cu;return Ml(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(Al(t),this._track.input._disposed)throw new cu;return Ml(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(jl(e),Al(t),this._track.input._disposed)throw new cu;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(Al(t),this._track.input._disposed)throw new cu;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getNextKeyPacket(r,t):r)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof I))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 I))throw TypeError(`endPacket must be an EncodedPacket.`);if(Al(n),this._track.input._disposed)throw new cu;let r=[],{promise:i,resolve:a}=D(),{promise:o,resolve:s}=D(),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}=D()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=D(),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 cu;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}}}},Pl=class{constructor(e,t){this.onSample=e,this.onError=t,this.onDequeue=null}},Fl=class{mediaSamplesInRange(e=-1/0,t=1/0,n){jl(e),jl(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=D(),{promise:c,resolve:l}=D(),u=!1,d=!1,f=!1,p=null,m=null,h=!1,g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=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}=D())},e=>{h||(m=e,h=!0,s())}),p.onDequeue=()=>l();let n=this._createPacketSink(),_=await n.getKeyPacket(e,g)??await n.getFirstKeyPacket(g),v=_,y=n.packets(_??void 0,void 0,g);for(await y.next();v&&!d&&!this._track.input._disposed;){if(r.length+p.getDecodeQueueSize()>=4){({promise:c,resolve:l}=D()),await c;continue}p.decode(v);let e=await y.next();if(e.done)break;v=e.value}await y.return(),!f&&!this._track.input._disposed&&await p.flush(),!i&&a&&(r.push(a),a=null),u=!0,s()})().catch(e=>{h||(m=e,h=!0,s())}).finally(()=>{p?.close()});let _=this._track,v=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(_.input._disposed)throw f=!0,d=!0,v(),new cu;else if(f)return{value:void 0,done:!0};else if(h)throw f=!0,d=!0,v(),m;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(),v(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Te(e);let r=we(e),i=[],a=[],{promise:o,resolve:s}=D(),{promise:c,resolve:l}=D(),u=!1,d=!1,f=null,p=null,m=!1,h=e=>{a.push(e),s(),{promise:o,resolve:s}=D()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=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++)h(n<t-1?e.clone():e);else e.close()},e=>{m||(p=e,m=!0,s())}),f.onDequeue=()=>l();let e=this._createPacketSink(),t=null,o=null,_=-1,v=async()=>{n(o),n(f);let t=o;for(f.decode(t);t.sequenceNumber<_;){for(;a.length+f.getDecodeQueueSize()>=4&&!d;)({promise:c,resolve:l}=D()),await c;if(d)break;let r=await e.getNextPacket(t,g);n(r),f.decode(r),t=r}_=-1},y=async()=>{n(f),await f.flush();for(let e=0;e<i.length;e++)h(null);i.length=0};for await(let n of r){if(jl(n),d||this._track.input._disposed)break;let r=await e.getPacket(n,g),a=r&&await e.getKeyPacket(n,g);if(!a){_!==-1&&(await v(),await y()),h(null),t=null;continue}t&&(a.sequenceNumber!==o.sequenceNumber||r.timestamp<t.timestamp)&&(await v(),await y()),i.push(r.timestamp),_=Math.max(r.sequenceNumber,_),t=r,o=a}!d&&!this._track.input._disposed&&(_!==-1&&await v(),await y()),u=!0,s()})().catch(e=>{m||(p=e,m=!0,s())}).finally(()=>{f?.close()});let _=this._track,v=()=>{for(let e of a)e?.close()};return{async next(){for(;;)if(_.input._disposed)throw d=!0,v(),new cu;else if(d)return{value:void 0,done:!0};else if(m)throw d=!0,v(),p;else if(a.length>0){let e=a.shift();return n(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(),v(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Il=class extends Pl{constructor(e,t,r,i,a,o,s){super(e,t),this.codec=r,this.decoderConfig=i,this.rotation=a,this.flip=o,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ye,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let c=bl.find(e=>e.supports(r,i));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof fc))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();n(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(tt()){if(r===`avc`&&this.decoderConfig.description){let e=yn(S(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=xn(e.sequenceParameterSets[0]);t&&(t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`}),t.maxDecFrameBuffering!==0&&t.bitstreamRestrictionFlag!==1&&(e.sequenceParameterSets[0]=Cn(t),this.decoderConfig={...this.decoderConfig,description:vn(e)}))}}ue(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??`bt709`,matrix:this.decoderConfig.colorSpace?.matrix??`bt709`,transfer:this.decoderConfig.colorSpace?.transfer??`bt709`,fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let t=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{if(n(this.decoder),Ze()||be(this.inputTimestamps,e.timestamp,e=>e),tt()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[],n=!1;for(let r of ln(e.data,this.decoderConfig)){let i=un(e.data[r.offset]);if(n||=i>=1&&i<=5,i===on.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}if(!this.decoderConfig.description)for(let e=0;e<t.length;e++){let n=t[e];if(un(n[0])!==on.SPS)continue;let r=xn(n);r&&r.maxDecFrameBuffering!==0&&r.bitstreamRestrictionFlag!==1&&(t[e]=Cn(r));break}e=new I(gn(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=zn(e.data,this.decoderConfig);t&&(e=new I(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||=new Rl,!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let t=this.colorQueue.shift();n(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();n(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`}})}let t=Zn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Tn(e,this.decoderConfig)){let n=En(e[t.offset]);if(n===M.RASL_N||n===M.RASL_R)return!0}return!1}sampleHandler(e){if(Ze()){if(this.sampleQueue.length>0&&e.timestamp>=h(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}be(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();n(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,t){let r=D();this.mergeAlphaPromises.push(r.promise);let i={sample:null};this.finalSamples.push(i);try{for(t?(n(this.merger),i.sample=new fc(await this.merger.merge(e,t))):i.sample=new fc(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){xe(this.finalSamples,i),this.onError(e)}finally{xe(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ze()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.state!==`closed`&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!==`closed`&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}};let Ll=null;var Rl=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!Ll){let e=new Blob([`(${zl.toString()})()`],{type:`application/javascript`});Ll=URL.createObjectURL(e)}let e=O(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(Ll);e.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame))}),e.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let n=this.nextRequestId++,r=D();this.pendingRequests.set(n,r);let i=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,i.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=/* @__PURE__ */ Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const zl=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,n);if(n===`NV12`)return await o(e,t);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,r,i,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:n===`RGBX`||n===`RGBA`?`RGBA`:`BGRA`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=n.includes(`P10`),o=n.includes(`P12`),c=a||o?2:1,l,u;n.startsWith(`I420`)?(l=Math.ceil(r/2),u=Math.ceil(i/2)):n.startsWith(`I422`)?(l=Math.ceil(r/2),u=i):(l=r,u=i);let d=r*i,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,r,i,c),y=p+2*m;_.set(v,y);let b={format:n.slice(0,4)+`A`+n.slice(4),codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();(!t||t.byteLength!==c)&&(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();(!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}{let a=e.subarray(0,n*r*i);if(t.colorSpace.fullRange===!1){let e=o.includes(`P12`)?12:o.includes(`P10`)?10:8,t=16<<e-8,s=235<<e-8,c=(1<<e)-1,l=i===2?new Uint16Array(a.buffer,0,n*r):a;for(let e=0;e<l.length;e++){let n=Math.round((l[e]-t)*c/(s-t));l[e]=Math.min(Math.max(n,0),c)}}return a}}},Bl=e=>{if(!e||typeof e!=`object`)throw TypeError(`decoderOptions must be an object.`);if(e.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!=`boolean`)throw TypeError(`decoderOptions.optimizeForLatency, when provided, must be a boolean.`)};var Vl=class extends Fl{constructor(e,t={}){if(!(e instanceof Yl))throw TypeError(`videoTrack must be an InputVideoTrack.`);Bl(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof VideoDecoder>`u`?it(`VideoDecoder`):`This video track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getRotation(),a=await this._track.getFlip(),o=await this._track.getDecoderConfig(),s=await this._track.getTimeResolution();return n(r&&o),o={...o,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Il(e,t,r,o,i,a,s)}_createPacketSink(){return new Nl(this._track)}async getSample(e,t={}){jl(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)}},Hl=class{constructor(e,t={}){if(this._rotation=0,this._flip=!1,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Yl))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);if(t.crop!==void 0&&xc(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);t.decoderOptions!==void 0&&Bl(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new Vl(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),r=e.flip??await t.getFlip(),i=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[o,s]=n%180==0?[i,a]:[a,i],c=e.crop;c&&=bc(c,o,s);let[l,u]=c?[c.width,c.height]:[o,s],d=l/u;e.width!==void 0&&e.height===void 0?(l=e.width,u=Math.round(l/d)):e.width===void 0&&e.height!==void 0?(u=e.height,l=Math.round(u*d)):e.width!==void 0&&e.height!==void 0&&(l=e.width,u=e.height),this._width=l,this._height=u,this._rotation=n,this._flip=r,this._crop=c})()}_videoSampleToWrappedCanvas(e){let t=this._width,r=this._height,i=this._canvasPool[this._nextCanvasIndex],a=!1;i||(typeof document<`u`?(i=document.createElement(`canvas`),i.width=t,i.height=r):i=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=i),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=i.getContext(`2d`,{alpha:this._alpha||$e()});n(o),e._drawWithFitAndMipmapping(i,o,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&$e()});let s={canvas:i,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e,t){jl(e),await this._ensureInit();let n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*Me(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Me(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},Ul=class extends Pl{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ye,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let i=t=>{let n=t.timestamp;this.expectedFirstTimestamp!==null&&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=xl.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 jc))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=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new jc(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(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--,this.onDequeue?.()})):(n(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.state!==`closed`&&this.decoder.close())}},Wl=class extends Pl{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,n(P.includes(r.codec)),this.codec=r.codec;let{dataType:i,sampleSize:a,littleEndian:o}=Gr(this.codec);switch(this.inputSampleSize=a,a){case 1:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-128:i===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):i===`ulaw`?this.readInputValue=(e,t)=>Dl(e.getUint8(t)):i===`alaw`?this.readInputValue=(e,t)=>kl(e.getUint8(t)):n(!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):n(!1);break;case 3:i===`unsigned`?this.readInputValue=(e,t)=>De(e,t,o)-2**23:i===`signed`?this.readInputValue=(e,t)=>Oe(e,t,o):n(!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):n(!1);break;case 8:i===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,o):n(!1);break;default:Ee(a),n(!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+128));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:Ee(a),n(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=C(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 s=this.currentTimestamp;this.currentTimestamp+=o;let c=new jc({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},Gl=class extends Fl{constructor(e){if(!(e instanceof Xl))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof AudioDecoder>`u`?it(`AudioDecoder`):`This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getDecoderConfig();return n(r&&i),P.includes(i.codec)?new Wl(e,t,i):new Ul(e,t,r,i)}_createPacketSink(){return new Nl(this._track)}async getSample(e,t={}){jl(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)}},Kl=class{constructor(e){if(!(e instanceof Xl))throw TypeError(`audioTrack must be an InputAudioTrack.`);this._audioSampleSink=new Gl(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){jl(e);let n=await this._audioSampleSink.getSample(e,t);return n&&this._audioSampleToWrappedArrayBuffer(n)}buffers(e,t,n){return Me(this._audioSampleSink.samples(e,t,n),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Me(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}},ql=class e{constructor(e,t){
|
|
344
|
+
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.`)},Ml=e=>{if(!ht(e))throw TypeError(`timestamp must be a number.`)},Nl=(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 Pl=class{constructor(e){if(!(e instanceof Jl))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(jl(e),this._track.input._disposed)throw new lu;return Nl(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){jl(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Ml(e),jl(t),this._track.input._disposed)throw new lu;return Nl(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(jl(t),this._track.input._disposed)throw new lu;return Nl(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ml(e),jl(t),this._track.input._disposed)throw new lu;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(jl(t),this._track.input._disposed)throw new lu;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getNextKeyPacket(r,t):r)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof I))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 I))throw TypeError(`endPacket must be an EncodedPacket.`);if(jl(n),this._track.input._disposed)throw new lu;let r=[],{promise:i,resolve:a}=D(),{promise:o,resolve:s}=D(),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}=D()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=D(),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 lu;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}}}},Fl=class{constructor(e,t){this.onSample=e,this.onError=t,this.onDequeue=null}},Il=class{mediaSamplesInRange(e=-1/0,t=1/0,n){Ml(e),Ml(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=D(),{promise:c,resolve:l}=D(),u=!1,d=!1,f=!1,p=null,m=null,h=!1,g={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=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}=D())},e=>{h||(m=e,h=!0,s())}),p.onDequeue=()=>l();let n=this._createPacketSink(),_=await n.getKeyPacket(e,g)??await n.getFirstKeyPacket(g),v=_,y=n.packets(_??void 0,void 0,g);for(await y.next();v&&!d&&!this._track.input._disposed;){if(r.length+p.getDecodeQueueSize()>=4){({promise:c,resolve:l}=D()),await c;continue}p.decode(v);let e=await y.next();if(e.done)break;v=e.value}await y.return(),!f&&!this._track.input._disposed&&await p.flush(),!i&&a&&(r.push(a),a=null),u=!0,s()})().catch(e=>{h||(m=e,h=!0,s())}).finally(()=>{p?.close()});let _=this._track,v=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(_.input._disposed)throw f=!0,d=!0,v(),new lu;else if(f)return{value:void 0,done:!0};else if(h)throw f=!0,d=!0,v(),m;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(),v(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Te(e);let r=we(e),i=[],a=[],{promise:o,resolve:s}=D(),{promise:c,resolve:l}=D(),u=!1,d=!1,f=null,p=null,m=!1,h=e=>{a.push(e),s(),{promise:o,resolve:s}=D()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=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++)h(n<t-1?e.clone():e);else e.close()},e=>{m||(p=e,m=!0,s())}),f.onDequeue=()=>l();let e=this._createPacketSink(),t=null,o=null,_=-1,v=async()=>{n(o),n(f);let t=o;for(f.decode(t);t.sequenceNumber<_;){for(;a.length+f.getDecodeQueueSize()>=4&&!d;)({promise:c,resolve:l}=D()),await c;if(d)break;let r=await e.getNextPacket(t,g);n(r),f.decode(r),t=r}_=-1},y=async()=>{n(f),await f.flush();for(let e=0;e<i.length;e++)h(null);i.length=0};for await(let n of r){if(Ml(n),d||this._track.input._disposed)break;let r=await e.getPacket(n,g),a=r&&await e.getKeyPacket(n,g);if(!a){_!==-1&&(await v(),await y()),h(null),t=null;continue}t&&(a.sequenceNumber!==o.sequenceNumber||r.timestamp<t.timestamp)&&(await v(),await y()),i.push(r.timestamp),_=Math.max(r.sequenceNumber,_),t=r,o=a}!d&&!this._track.input._disposed&&(_!==-1&&await v(),await y()),u=!0,s()})().catch(e=>{m||(p=e,m=!0,s())}).finally(()=>{f?.close()});let _=this._track,v=()=>{for(let e of a)e?.close()};return{async next(){for(;;)if(_.input._disposed)throw d=!0,v(),new lu;else if(d)return{value:void 0,done:!0};else if(m)throw d=!0,v(),p;else if(a.length>0){let e=a.shift();return n(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(),v(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Ll=class extends Fl{constructor(e,t,r,i,a,o,s){super(e,t),this.codec=r,this.decoderConfig=i,this.rotation=a,this.flip=o,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ye,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let c=xl.find(e=>e.supports(r,i));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof pc))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();n(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(tt()){if(r===`avc`&&this.decoderConfig.description){let e=yn(S(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=xn(e.sequenceParameterSets[0]);t&&(t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`}),t.maxDecFrameBuffering!==0&&t.bitstreamRestrictionFlag!==1&&(e.sequenceParameterSets[0]=Cn(t),this.decoderConfig={...this.decoderConfig,description:vn(e)}))}}ue(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??`bt709`,matrix:this.decoderConfig.colorSpace?.matrix??`bt709`,transfer:this.decoderConfig.colorSpace?.transfer??`bt709`,fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let t=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{if(n(this.decoder),Ze()||be(this.inputTimestamps,e.timestamp,e=>e),tt()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[],n=!1;for(let r of ln(e.data,this.decoderConfig)){let i=un(e.data[r.offset]);if(n||=i>=1&&i<=5,i===on.AUD){if(n)break;t.length=0}i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}if(!this.decoderConfig.description)for(let e=0;e<t.length;e++){let n=t[e];if(un(n[0])!==on.SPS)continue;let r=xn(n);r&&r.maxDecFrameBuffering!==0&&r.bitstreamRestrictionFlag!==1&&(t[e]=Cn(r));break}e=new I(gn(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=zn(e.data,this.decoderConfig);t&&(e=new I(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||=new zl,!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let t=this.colorQueue.shift();n(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();n(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`}})}let t=Zn(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Tn(e,this.decoderConfig)){let n=En(e[t.offset]);if(n===M.RASL_N||n===M.RASL_R)return!0}return!1}sampleHandler(e){if(Ze()){if(this.sampleQueue.length>0&&e.timestamp>=h(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}be(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();n(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,t){let r=D();this.mergeAlphaPromises.push(r.promise);let i={sample:null};this.finalSamples.push(i);try{for(t?(n(this.merger),i.sample=new pc(await this.merger.merge(e,t))):i.sample=new pc(e);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){xe(this.finalSamples,i),this.onError(e)}finally{xe(this.mergeAlphaPromises,r.promise),r.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ze()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.state!==`closed`&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!==`closed`&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}};let Rl=null;var zl=class{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!Rl){let e=new Blob([`(${Bl.toString()})()`],{type:`application/javascript`});Rl=URL.createObjectURL(e)}let e=O(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(Rl);e.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame))}),e.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let n=this.nextRequestId++,r=D();this.pendingRequests.set(n,r);let i=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,i.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=/* @__PURE__ */ Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const Bl=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,n);if(n===`NV12`)return await o(e,t);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,r,i,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:n===`RGBX`||n===`RGBA`?`RGBA`:`BGRA`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=n.includes(`P10`),o=n.includes(`P12`),c=a||o?2:1,l,u;n.startsWith(`I420`)?(l=Math.ceil(r/2),u=Math.ceil(i/2)):n.startsWith(`I422`)?(l=Math.ceil(r/2),u=i):(l=r,u=i);let d=r*i,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,r,i,c),y=p+2*m;_.set(v,y);let b={format:n.slice(0,4)+`A`+n.slice(4),codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n)=>{let r=e.visibleRect?.width??e.codedWidth,i=e.visibleRect?.height??e.codedHeight,a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();(!t||t.byteLength!==c)&&(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();(!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}{let a=e.subarray(0,n*r*i);if(t.colorSpace.fullRange===!1){let e=o.includes(`P12`)?12:o.includes(`P10`)?10:8,t=16<<e-8,s=235<<e-8,c=(1<<e)-1,l=i===2?new Uint16Array(a.buffer,0,n*r):a;for(let e=0;e<l.length;e++){let n=Math.round((l[e]-t)*c/(s-t));l[e]=Math.min(Math.max(n,0),c)}}return a}}},Vl=e=>{if(!e||typeof e!=`object`)throw TypeError(`decoderOptions must be an object.`);if(e.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!=`boolean`)throw TypeError(`decoderOptions.optimizeForLatency, when provided, must be a boolean.`)};var Hl=class extends Il{constructor(e,t={}){if(!(e instanceof Xl))throw TypeError(`videoTrack must be an InputVideoTrack.`);Vl(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof VideoDecoder>`u`?it(`VideoDecoder`):`This video track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getRotation(),a=await this._track.getFlip(),o=await this._track.getDecoderConfig(),s=await this._track.getTimeResolution();return n(r&&o),o={...o,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Ll(e,t,r,o,i,a,s)}_createPacketSink(){return new Pl(this._track)}async getSample(e,t={}){Ml(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)}},Ul=class{constructor(e,t={}){if(this._rotation=0,this._flip=!1,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Xl))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`options.flip, when provided, must be a boolean.`);if(t.crop!==void 0&&Sc(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);t.decoderOptions!==void 0&&Vl(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new Hl(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),r=e.flip??await t.getFlip(),i=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[o,s]=n%180==0?[i,a]:[a,i],c=e.crop;c&&=xc(c,o,s);let[l,u]=c?[c.width,c.height]:[o,s],d=l/u;e.width!==void 0&&e.height===void 0?(l=e.width,u=Math.round(l/d)):e.width===void 0&&e.height!==void 0?(u=e.height,l=Math.round(u*d)):e.width!==void 0&&e.height!==void 0&&(l=e.width,u=e.height),this._width=l,this._height=u,this._rotation=n,this._flip=r,this._crop=c})()}_videoSampleToWrappedCanvas(e){let t=this._width,r=this._height,i=this._canvasPool[this._nextCanvasIndex],a=!1;i||(typeof document<`u`?(i=document.createElement(`canvas`),i.width=t,i.height=r):i=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=i),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=i.getContext(`2d`,{alpha:this._alpha||$e()});n(o),e._drawWithFitAndMipmapping(i,o,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&$e()});let s={canvas:i,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e,t){Ml(e),await this._ensureInit();let n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*Me(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Me(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},Wl=class extends Fl{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ye,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let i=t=>{let n=t.timestamp;this.expectedFirstTimestamp!==null&&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=Sl.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 Mc))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=(/* @__PURE__ */ Error(`Decoding error`)).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new Mc(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.addEventListener(`dequeue`,()=>{this.onDequeue?.()}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(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--,this.onDequeue?.()})):(n(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.state!==`closed`&&this.decoder.close())}},Gl=class extends Fl{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,n(P.includes(r.codec)),this.codec=r.codec;let{dataType:i,sampleSize:a,littleEndian:o}=Gr(this.codec);switch(this.inputSampleSize=a,a){case 1:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-128:i===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):i===`ulaw`?this.readInputValue=(e,t)=>Ol(e.getUint8(t)):i===`alaw`?this.readInputValue=(e,t)=>Al(e.getUint8(t)):n(!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):n(!1);break;case 3:i===`unsigned`?this.readInputValue=(e,t)=>De(e,t,o)-2**23:i===`signed`?this.readInputValue=(e,t)=>Oe(e,t,o):n(!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):n(!1);break;case 8:i===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,o):n(!1);break;default:Ee(a),n(!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+128));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:Ee(a),n(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=C(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 s=this.currentTimestamp;this.currentTimestamp+=o;let c=new Mc({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},Kl=class extends Il{constructor(e){if(!(e instanceof Zl))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(typeof AudioDecoder>`u`?it(`AudioDecoder`):`This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getDecoderConfig();return n(r&&i),P.includes(i.codec)?new Gl(e,t,i):new Wl(e,t,r,i)}_createPacketSink(){return new Pl(this._track)}async getSample(e,t={}){Ml(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)}},ql=class{constructor(e){if(!(e instanceof Zl))throw TypeError(`audioTrack must be an InputAudioTrack.`);this._audioSampleSink=new Kl(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Ml(e);let n=await this._audioSampleSink.getSample(e,t);return n&&this._audioSampleToWrappedArrayBuffer(n)}buffers(e,t,n){return Me(this._audioSampleSink.samples(e,t,n),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Me(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}},Jl=class e{constructor(e,t){
|
|
345
345
|
/*!
|
|
346
346
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
347
347
|
*
|
|
@@ -349,7 +349,7 @@ if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.met
|
|
|
349
349
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
350
350
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
351
351
|
*/
|
|
352
|
-
this.input=e,this._backing=t}isVideoTrack(){return this instanceof Yl}isAudioTrack(){return this instanceof Xl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return B(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return B(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return B(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return B(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 B(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}),n=(t?.timestamp??0)+(t?.duration??0);return Le(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new Nl(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(tu({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(tu({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(tu({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(tu({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(tu({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Jl(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&&=Jl(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Jl(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}};const B=(e,t,n)=>{if(k(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Jl=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 k(r)?r.then(n):n(r)}:void 0};var Yl=class extends ql{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return B(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 B(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return B(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return c(await this._backing.getTransformationMatrix())}get rotation(){return c(B(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return l(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return B(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return B(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:B(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:B(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(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=B(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}let t=c(B(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return B(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=B(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}let t=c(B(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return B(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 t=await this._backing.getCodec();return n(t!==null),bl.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return A._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let r=await this.getDecoderConfig();return n(r),Zn(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!ht(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new Nl(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=ru(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let ee=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?au(ee):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:ee,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},Xl=class extends ql{constructor(e,t){super(e,t)}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return B(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return B(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return B(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 t=await this._backing.getCodec();return n(t!==null),xl.some(n=>n.supports(t,e))||P.includes(e.codec)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return A._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}};const Zl=e=>e??1/0,Ql=e=>-(e??-1/0),$l=e=>-e,eu=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 k(r)?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 k(r)?r.then(n):n(r)}:void 0}},tu=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return k(r)?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 k(r)||k(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),nu=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>k(e))){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=>k(e))?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)},ru=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=iu(p,m,n),r=iu(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},iu=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return xt({num:n,den:r})}return null},au=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};
|
|
352
|
+
this.input=e,this._backing=t}isVideoTrack(){return this instanceof Xl}isAudioTrack(){return this instanceof Zl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return B(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return B(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return B(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return B(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 B(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}),n=(t?.timestamp??0)+(t?.duration??0);return Le(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new Pl(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(nu({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(nu({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(nu({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(nu({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(nu({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Yl(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&&=Yl(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Yl(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}};const B=(e,t,n)=>{if(k(e))throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Yl=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 k(r)?r.then(n):n(r)}:void 0};var Xl=class extends Jl{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return`video`}async getCodec(){return this._backing.getCodec()}get codec(){return B(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 B(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return B(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return c(await this._backing.getTransformationMatrix())}get rotation(){return c(B(this._backing.getTransformationMatrix(),`rotation`,`getRotation`))}async getFlip(){return l(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return B(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return B(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=xt({num:B(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:B(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*B(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=B(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}let t=c(B(this._backing.getTransformationMatrix(),`displayWidth`,`getDisplayWidth`))%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return B(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=B(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}let t=c(B(this._backing.getTransformationMatrix(),`displayHeight`,`getDisplayHeight`))%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return B(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 t=await this._backing.getCodec();return n(t!==null),xl.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return A._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let r=await this.getDecoderConfig();return n(r),Zn(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.targetPacketCount!==void 0&&(!ht(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError(`options.targetPacketCount must be a non-negative number.`);let t=await this.getTimeResolution(),n=e.targetPacketCount??256,r=new Pl(this),i=[],a=-1/0,o=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(i.length>=n&&e.timestamp>=a)break;i.push(e.timestamp),a=Math.max(a,e.timestamp),o++}let s=new Float64Array(i.length);for(let e=0;e<i.length;e++)s[e]=Math.round(i[e]*t);s.sort();let c=1;for(let e=1;e<s.length;e++)s[e]!==s[c-1]&&(s[c++]=s[e]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};let l=s.subarray(0,c),u=iu(l,t),d=u??t,f=u===null?null:t/u,p=/* @__PURE__ */ new Map,m=1/0,h=-1/0,g=0;for(let e=1;e<c;e++){let t=l[e]-l[e-1],n=f===null?t:Math.max(1,Math.round(t/f));p.set(n,(p.get(n)??0)+1),m=Math.min(m,n),h=Math.max(h,n),g+=n}let _=c-1,v=[...p.keys()].sort((e,t)=>e-t),y=_-1>>1,b=_>>1,x=0,S=0,C=0;for(let e of v)if(C+=p.get(e),x===0&&C>y&&(x=e),C>b){S=e;break}let ee=(d/x+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:u===null?ou(ee):u,minFrameRate:d/h,maxFrameRate:d/m,averageFrameRate:d*_/g,medianFrameRate:ee,frameRateIsConstant:u!==null&&m===1&&h===1,probedPacketCount:o}}},Zl=class extends Jl{constructor(e,t){super(e,t)}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return B(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return B(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return B(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 t=await this._backing.getCodec();return n(t!==null),Sl.some(n=>n.supports(t,e))||P.includes(e.codec)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return A._error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}};const Ql=e=>e??1/0,$l=e=>-(e??-1/0),eu=e=>-e,tu=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 k(r)?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 k(r)?r.then(n):n(r)}:void 0}},nu=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return k(r)?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 k(r)||k(i)?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),ru=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>k(e))){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=>k(e))?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)},iu=(e,t)=>{let n=1e6,r=.98,i=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;let o=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let n=e[t]-e[t-1];if(!(n>0))return null;o[t-1]=n}let s=o.slice();s.sort();let c=s[Math.floor(s.length*.05)];for(let e=0;e<6;e++){let e=0,t=0;for(let n of o){let r=Math.max(1,Math.round(n/c));Math.abs(n-r*c)>=i||(e+=n,t+=r)}if(t===0)return null;let n=e/t;if(Math.abs(n-c)<=1e-12*Math.max(1,c)){c=n;break}c=n}let l=0,u=0,d=0;for(let e of o){let t=Math.max(1,Math.round(e/c));Math.abs(e-t*c)>=i||(l++,u+=e,d+=t)}if(l/o.length<r)return null;c=u/d;let f=1/Math.min(d,1e3),p=Math.max(2**-52,c-f),m=c+f,h=t/m,g=t/p,_=t/c,v=null,y=1/0;for(let e of a){if(e<h||e>g)continue;let t=Math.abs(e/_-1);t<y&&(v=e,y=t)}if(v===null){let e=au(p,m,n),r=au(h,g,n);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))v=r.num/r.den;else if(e)v=t*e.den/e.num;else return null}let b=t/v,x=0;for(let e of o){let t=Math.max(1,Math.round(e/b));Math.abs(e-t*b)<i&&x++}return x/o.length<r?null:v},au=(e,t,n)=>{for(let r=1;r<=n;r++){let n=Math.floor(e*r)+1;if(n/r<t)return xt({num:n,den:r})}return null},ou=e=>{let t=[24/1.001,30/1.001,60/1.001,120/1.001],n=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(let n of t)if(Math.abs(n/e-1)<=5e-4)return n;let r=e,i=1/0;for(let t of n){let n=Math.abs(t/e-1);n<=.025&&n<i&&(r=t,i=n)}return r};
|
|
353
353
|
/*!
|
|
354
354
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
355
355
|
*
|
|
@@ -357,7 +357,7 @@ this.input=e,this._backing=t}isVideoTrack(){return this instanceof Yl}isAudioTra
|
|
|
357
357
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
358
358
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
359
359
|
*/
|
|
360
|
-
mt();var
|
|
360
|
+
mt();var su=class e extends Pt{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */ 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 Ss)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Uo||t.source instanceof Wo))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Uo&&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&&Js(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Uo?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){n(this._rootSource instanceof Go);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let r=this._sourceCache.find(n=>n.cacheGroup===t&&Ko(n.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());let i=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Ko(n.request,e));if(i)return i.promise.then(e=>e.sourceRef.source.ref());let a=(async()=>{let r=await this._getSourceUncached(e);if(this._disposed)throw r.free(),new lu;if(vt(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=yt(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);n(e!==-1);let r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),xe(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);let i=this._sourceCachePromises.findIndex(t=>t.request===e);return n(i!==-1),this._sourceCachePromises.splice(i,1),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,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 uu(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 cu})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),n(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof cu)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._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...n.map(e=>e?.timestamp??1/0));return r===1/0?0:r}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){e&&=tu(e);let t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return ru(t,e)}async getVideoTracks(e){e&&=tu(e);let t=(await this.getTracks()).filter(e=>e.isVideoTrack());return ru(t,e)}async getAudioTracks(e){e&&=tu(e);let t=(await this.getTracks()).filter(e=>e.isAudioTrack());return ru(t,e)}async getPrimaryVideoTrack(e){e&&=tu(e);let t=nu(e,{sortBy:async e=>[eu((await e.getDisposition()).default),eu(await e.hasPairableAudioTrack()),eu(!await e.hasOnlyKeyPackets()),$l(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=tu(e);let t=await this.getPrimaryVideoTrack(),n=nu(e,{sortBy:async e=>[eu(!t||e.canBePairedWith(t)),eu((await e.getDisposition()).default),$l(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 Xl(this,e):new Zl(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()}},cu=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},lu=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},uu=class{constructor(e){
|
|
361
361
|
/*!
|
|
362
362
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
363
363
|
*
|
|
@@ -365,7 +365,7 @@ mt();var ou=class e extends Pt{get disposed(){return this._disposed}constructor(
|
|
|
365
365
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
366
366
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
367
367
|
*/
|
|
368
|
-
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
|
|
368
|
+
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 lu;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=/* @__PURE__ */ new Uint8Array;return new du(t,C(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Vo);return k(r)?r.then(t=>t?new du(t.bytes,t.view,t.offset,e,n):null):r?new du(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new lu;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,O(this.fileSizeNonStrict-e,t,r));{let i=this.requestSlice(e,r),a=i=>i||(n(this.fileSizeNonStrict!==null),this.requestSlice(e,O(this.fileSizeNonStrict-e,t,r)));return k(i)?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(k(n)&&(n=await n),!n||n.length===0)break;let r=V(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 du(n,C(n),0,0,t)})():this.requestSlice(0,this.fileSizeNonStrict)}},du=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,C(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)}};const fu=(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.`)},V=(e,t)=>{fu(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},H=e=>(fu(e,1),e.view.getUint8(e.bufferPos++)),pu=(e,t)=>{fu(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},U=e=>{fu(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},mu=e=>{fu(e,3);let t=De(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},hu=e=>{fu(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},gu=(e,t)=>{fu(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},W=e=>{fu(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},_u=e=>{fu(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},vu=e=>{fu(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},yu=e=>{fu(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},bu=(e,t)=>{let n,r;return t?(n=gu(e,!0),r=gu(e,!0)):(r=gu(e,!1),n=gu(e,!1)),r*4294967296+n},xu=e=>{let t=W(e),n=W(e);return t*4294967296+n},Su=e=>{let t=vu(e),n=W(e);return t*4294967296+n},Cu=e=>{let t=_u(e);return yu(e)*4294967296+t},wu=e=>{fu(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Tu=e=>{fu(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},G=(e,t)=>{fu(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Eu=(e,t,n)=>w.decode(V(e,t)).split(`
|
|
369
369
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e));
|
|
370
370
|
/*!
|
|
371
371
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
@@ -374,7 +374,7 @@ this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)thro
|
|
|
374
374
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
375
375
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
376
376
|
*/
|
|
377
|
-
var Eu;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Eu||={});var Du;(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`})(Du||={});const Ou=/* @__PURE__ */ `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(`.`),ku=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=V(e,125),e.filePos=n;let r=Au(e,30);r&&(t.title??=r);let i=Au(e,30);i&&(t.artist??=i);let a=Au(e,30);a&&(t.album??=a);let o=Au(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=V(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Au(e,28),e.skip(2)}else e.skip(-30),l=Au(e,30);l&&(t.comment??=l);let u=H(e);u<Ou.length&&(t.genre??=Ou[u])},Au=(e,t)=>{let n=V(e,t),r=st(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()},ju=e=>{let t=e.filePos,n=G(e,3),r=H(e),i=H(e),a=H(e),o=W(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=di(o);return a&Eu.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},Mu=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){A._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&Eu.Footer?t.size-10:t.size,i=new Nu(t,V(e,r));if(t.flags&Eu.Unsynchronisation&&t.majorVersion===3&&i.ununsynchronizeAll(),t.flags&Eu.ExtendedHeader){let e=i.readU32();t.majorVersion===3?i.pos+=e:i.pos+=e-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let e=i.readId3V2Frame();if(!e)break;let r=i.pos,a=i.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&Eu.Unsynchronisation)),o){A._warn(`Skipping encrypted ID3v2 frame ${e.id}`),i.pos=a;continue}if(s){A._warn(`Skipping compressed ID3v2 frame ${e.id}`),i.pos=a;continue}if(c&&i.ununsynchronizeRegion(i.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=i.readId3V2TextEncoding(),r=i.readId3V2Text(t,a),o=i.readId3V2Text(t,a);e[r]??=o}else e.id[0]===`T`?n.raw[e.id]??=i.readId3V2EncodingAndText(a):n.raw[e.id]??=i.readBytes(e.size);switch(i.pos=r,e.id){case`TIT2`:case`TT2`:n.title??=i.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=i.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=i.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=i.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=i.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=i.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.tracksTotal??=r)}break;case`TPOS`:case`TPA`:{let e=i.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.discsTotal??=r)}break;case`TCON`:case`TCO`:{let e=i.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(Ou[e]!==void 0){n.genre??=Ou[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(Ou[e]!==void 0){n.genre??=Ou[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=i.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=i.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`TBPM`:case`TBP`:{let e=i.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.beatsPerMinute??=t)}break;case`USLT`:case`ULT`:{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,a),n.lyrics??=i.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,a),n.comment??=i.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=i.readId3V2TextEncoding(),r;if(t.majorVersion===2){let e=i.readAscii(3);r=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else r=i.readId3V2Text(e,a);let o=i.readU8(),s=i.readId3V2Text(e,a).trimEnd(),c=a-i.pos;if(c>=0){let e=i.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:r,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:i.pos+=e.size}i.pos=a}};var Nu=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}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?di(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:di(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 Du.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 Du.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new te(`utf-16le`),t=st(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))}if(r[0]===254&&r[1]===255){let e=new te(`utf-16be`),t=st(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))}{let e=st(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}case Du.UTF_16_BE_NO_BOM:{let e=new te(`utf-16be`),t=st(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 Du.UTF_8:{let e=st(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Pu=class{constructor(e){this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=C(this.helper),this.writer=e}writeId3V2Tag(e){let t=this.writer.getPos();this.writeAscii(`ID3`),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let n=this.writer.getPos(),r=/* @__PURE__ */ new Set;for(let{key:t,value:n}of lt(e))switch(t){case`title`:this.writeId3V2TextFrame(`TIT2`,n),r.add(`TIT2`);break;case`description`:this.writeId3V2TextFrame(`TIT3`,n),r.add(`TIT3`);break;case`artist`:this.writeId3V2TextFrame(`TPE1`,n),r.add(`TPE1`);break;case`album`:this.writeId3V2TextFrame(`TALB`,n),r.add(`TALB`);break;case`albumArtist`:this.writeId3V2TextFrame(`TPE2`,n),r.add(`TPE2`);break;case`trackNumber`:{let t=e.tracksTotal===void 0?n.toString():`${n}/${e.tracksTotal}`;this.writeId3V2TextFrame(`TRCK`,t),r.add(`TRCK`)}break;case`discNumber`:{let t=e.discsTotal===void 0?n.toString():`${n}/${e.discsTotal}`;this.writeId3V2TextFrame(`TPOS`,t),r.add(`TPOS`)}break;case`genre`:this.writeId3V2TextFrame(`TCON`,n),r.add(`TCON`);break;case`date`:this.writeId3V2TextFrame(`TDRC`,n.toISOString().slice(0,10)),r.add(`TDRC`);break;case`beatsPerMinute`:this.writeId3V2TextFrame(`TBPM`,`${n}`),r.add(`TBPM`);break;case`lyrics`:this.writeId3V2LyricsFrame(n),r.add(`USLT`);break;case`comment`:this.writeId3V2CommentFrame(n),r.add(`COMM`);break;case`images`:{let e={coverFront:3,coverBack:4,unknown:0};for(let t of n){let n=e[t.kind]??0,r=t.description??``;this.writeId3V2ApicFrame(t.mimeType,n,r,t.data)}}break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ee(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];if(n==null||t.length!==4||r.has(t))continue;let i;if(typeof n==`string`){if(ne(n)){i=new Uint8Array(n.length+2),i[0]=Du.ISO_8859_1;for(let e=0;e<n.length;e++)i[e+1]=n.charCodeAt(e)}else{let e=T.encode(n);i=new Uint8Array(e.byteLength+2),i[0]=Du.UTF_8,i.set(e,1)}}else if(n instanceof Uint8Array)i=n;else if(t===`TXXX`&&Lt(n)){for(let e in n){let t=n[e],r=ne(e)&&ne(t),i=r?null:T.encode(e),a=r?null:T.encode(t),o=r?e.length:i.byteLength,s=r?t.length:a.byteLength,c=1+o+1+s+1;this.writeAscii(`TXXX`),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(r?Du.ISO_8859_1:Du.UTF_8),r?(this.writeIsoString(e),this.writeIsoString(t)):(this.writer.write(i),this.writeU8(0),this.writer.write(a),this.writeU8(0))}continue}else continue;this.writeAscii(t),this.writeSynchsafeU32(i.byteLength),this.writeU16(0),this.writer.write(i)}let i=this.writer.getPos(),a=i-n;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(i),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(ui(e))}writeIsoString(e){let t=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);this.writer.write(t)}writeUtf8String(e){let t=T.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){let n=ne(t),r=1+(n?t.length:T.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(r),this.writeU16(0),this.writeU8(n?Du.ISO_8859_1:Du.UTF_8),n?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){let t=ne(e),n=5+e.length+1;this.writeAscii(`USLT`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Du.ISO_8859_1:Du.UTF_8),this.writeAscii(`und`),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let t=ne(e),n=5+(t?e.length:T.encode(e).byteLength)+1;this.writeAscii(`COMM`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Du.ISO_8859_1:Du.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,n,r){let i=ne(e)&&ne(n),a=i?n.length:T.encode(n).byteLength,o=1+e.length+1+1+a+1+r.byteLength;this.writeAscii(`APIC`),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(i?Du.ISO_8859_1:Du.UTF_8),i?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),i?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(r)}},Fu=class{constructor(e){
|
|
377
|
+
var Du;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Du||={});var Ou;(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`})(Ou||={});const ku=/* @__PURE__ */ `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(`.`),Au=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=V(e,125),e.filePos=n;let r=ju(e,30);r&&(t.title??=r);let i=ju(e,30);i&&(t.artist??=i);let a=ju(e,30);a&&(t.album??=a);let o=ju(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=V(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=ju(e,28),e.skip(2)}else e.skip(-30),l=ju(e,30);l&&(t.comment??=l);let u=H(e);u<ku.length&&(t.genre??=ku[u])},ju=(e,t)=>{let n=V(e,t),r=st(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()},Mu=e=>{let t=e.filePos,n=G(e,3),r=H(e),i=H(e),a=H(e),o=W(e);if(n!==`ID3`||r===255||i===255||o&2155905152)return e.filePos=t,null;let s=di(o);return a&Du.Footer&&(s+=10),{majorVersion:r,revision:i,flags:a,size:s}},Nu=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){A._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&Du.Footer?t.size-10:t.size,i=new Pu(t,V(e,r));if(t.flags&Du.Unsynchronisation&&t.majorVersion===3&&i.ununsynchronizeAll(),t.flags&Du.ExtendedHeader){let e=i.readU32();t.majorVersion===3?i.pos+=e:i.pos+=e-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){let e=i.readId3V2Frame();if(!e)break;let r=i.pos,a=i.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&Du.Unsynchronisation)),o){A._warn(`Skipping encrypted ID3v2 frame ${e.id}`),i.pos=a;continue}if(s){A._warn(`Skipping compressed ID3v2 frame ${e.id}`),i.pos=a;continue}if(c&&i.ununsynchronizeRegion(i.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=i.readId3V2TextEncoding(),r=i.readId3V2Text(t,a),o=i.readId3V2Text(t,a);e[r]??=o}else e.id[0]===`T`?n.raw[e.id]??=i.readId3V2EncodingAndText(a):n.raw[e.id]??=i.readBytes(e.size);switch(i.pos=r,e.id){case`TIT2`:case`TT2`:n.title??=i.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=i.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=i.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=i.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=i.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=i.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.tracksTotal??=r)}break;case`TPOS`:case`TPA`:{let e=i.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),r&&Number.isInteger(r)&&r>0&&(n.discsTotal??=r)}break;case`TCON`:case`TCO`:{let e=i.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(ku[e]!==void 0){n.genre??=ku[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(ku[e]!==void 0){n.genre??=ku[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=i.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=i.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`TBPM`:case`TBP`:{let e=i.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.beatsPerMinute??=t)}break;case`USLT`:case`ULT`:{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,a),n.lyrics??=i.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=i.readU8();i.pos+=3,i.readId3V2Text(e,a),n.comment??=i.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=i.readId3V2TextEncoding(),r;if(t.majorVersion===2){let e=i.readAscii(3);r=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else r=i.readId3V2Text(e,a);let o=i.readU8(),s=i.readId3V2Text(e,a).trimEnd(),c=a-i.pos;if(c>=0){let e=i.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:r,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:i.pos+=e.size}i.pos=a}};var Pu=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}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?di(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:di(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 Ou.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 Ou.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new te(`utf-16le`),t=st(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))}if(r[0]===254&&r[1]===255){let e=new te(`utf-16be`),t=st(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))}{let e=st(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}case Ou.UTF_16_BE_NO_BOM:{let e=new te(`utf-16be`),t=st(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 Ou.UTF_8:{let e=st(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),w.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Fu=class{constructor(e){this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=C(this.helper),this.writer=e}writeId3V2Tag(e){let t=this.writer.getPos();this.writeAscii(`ID3`),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let n=this.writer.getPos(),r=/* @__PURE__ */ new Set;for(let{key:t,value:n}of lt(e))switch(t){case`title`:this.writeId3V2TextFrame(`TIT2`,n),r.add(`TIT2`);break;case`description`:this.writeId3V2TextFrame(`TIT3`,n),r.add(`TIT3`);break;case`artist`:this.writeId3V2TextFrame(`TPE1`,n),r.add(`TPE1`);break;case`album`:this.writeId3V2TextFrame(`TALB`,n),r.add(`TALB`);break;case`albumArtist`:this.writeId3V2TextFrame(`TPE2`,n),r.add(`TPE2`);break;case`trackNumber`:{let t=e.tracksTotal===void 0?n.toString():`${n}/${e.tracksTotal}`;this.writeId3V2TextFrame(`TRCK`,t),r.add(`TRCK`)}break;case`discNumber`:{let t=e.discsTotal===void 0?n.toString():`${n}/${e.discsTotal}`;this.writeId3V2TextFrame(`TPOS`,t),r.add(`TPOS`)}break;case`genre`:this.writeId3V2TextFrame(`TCON`,n),r.add(`TCON`);break;case`date`:this.writeId3V2TextFrame(`TDRC`,n.toISOString().slice(0,10)),r.add(`TDRC`);break;case`beatsPerMinute`:this.writeId3V2TextFrame(`TBPM`,`${n}`),r.add(`TBPM`);break;case`lyrics`:this.writeId3V2LyricsFrame(n),r.add(`USLT`);break;case`comment`:this.writeId3V2CommentFrame(n),r.add(`COMM`);break;case`images`:{let e={coverFront:3,coverBack:4,unknown:0};for(let t of n){let n=e[t.kind]??0,r=t.description??``;this.writeId3V2ApicFrame(t.mimeType,n,r,t.data)}}break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ee(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];if(n==null||t.length!==4||r.has(t))continue;let i;if(typeof n==`string`){if(ne(n)){i=new Uint8Array(n.length+2),i[0]=Ou.ISO_8859_1;for(let e=0;e<n.length;e++)i[e+1]=n.charCodeAt(e)}else{let e=T.encode(n);i=new Uint8Array(e.byteLength+2),i[0]=Ou.UTF_8,i.set(e,1)}}else if(n instanceof Uint8Array)i=n;else if(t===`TXXX`&&Lt(n)){for(let e in n){let t=n[e],r=ne(e)&&ne(t),i=r?null:T.encode(e),a=r?null:T.encode(t),o=r?e.length:i.byteLength,s=r?t.length:a.byteLength,c=1+o+1+s+1;this.writeAscii(`TXXX`),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(r?Ou.ISO_8859_1:Ou.UTF_8),r?(this.writeIsoString(e),this.writeIsoString(t)):(this.writer.write(i),this.writeU8(0),this.writer.write(a),this.writeU8(0))}continue}else continue;this.writeAscii(t),this.writeSynchsafeU32(i.byteLength),this.writeU16(0),this.writer.write(i)}let i=this.writer.getPos(),a=i-n;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(i),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(ui(e))}writeIsoString(e){let t=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);this.writer.write(t)}writeUtf8String(e){let t=T.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){let n=ne(t),r=1+(n?t.length:T.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(r),this.writeU16(0),this.writeU8(n?Ou.ISO_8859_1:Ou.UTF_8),n?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){let t=ne(e),n=5+e.length+1;this.writeAscii(`USLT`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Ou.ISO_8859_1:Ou.UTF_8),this.writeAscii(`und`),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let t=ne(e),n=5+(t?e.length:T.encode(e).byteLength)+1;this.writeAscii(`COMM`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Ou.ISO_8859_1:Ou.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,n,r){let i=ne(e)&&ne(n),a=i?n.length:T.encode(n).byteLength,o=1+e.length+1+1+a+1+r.byteLength;this.writeAscii(`APIC`),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(i?Ou.ISO_8859_1:Ou.UTF_8),i?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),i?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(r)}},Iu=class{constructor(e){
|
|
378
378
|
/*!
|
|
379
379
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
380
380
|
*
|
|
@@ -382,7 +382,7 @@ var Eu;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedH
|
|
|
382
382
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
383
383
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
384
384
|
*/
|
|
385
|
-
this.mutex=new me,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},
|
|
385
|
+
this.mutex=new me,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Lu=class extends Iu{constructor(e,t){
|
|
386
386
|
/*!
|
|
387
387
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
388
388
|
*
|
|
@@ -390,7 +390,7 @@ this.mutex=new me,this.trackTimestampInfo=/* @__PURE__ */ new WeakMap,this.outpu
|
|
|
390
390
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
391
391
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
392
392
|
*/
|
|
393
|
-
super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),Ht(this.output._metadataTags)||new
|
|
393
|
+
super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),Ht(this.output._metadataTags)||new Fu(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return`audio/aac`}async addEncodedVideoPacket(){throw Error(`ADTS does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type===`key`),this.inputIsAdts===null){ni(r,e.source._codec);let t=r?.decoderConfig?.description;if(this.inputIsAdts=!t,!this.inputIsAdts){let e=qt(S(t)),n=en(e);this.header=n.header,this.headerBitstream=n.bitstream}}if(this.inputIsAdts){let e=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,e)}else{n(this.header);let e=t.data.byteLength+this.header.byteLength;tn(this.headerBitstream,e);let r=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){let n=new Uint8Array(e);n.set(this.header,0),n.set(t.data,this.header.byteLength),this.format._options.onFrame(n,r)}}await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw Error(`ADTS does not support subtitles.`)}async finalize(){let e=await this.mutex.acquire();if(this.inputIsAdts===null)throw Error(`Cannot finalize an empty ADTS file: not a single packet was added.`);e()}};
|
|
394
394
|
/*!
|
|
395
395
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
396
396
|
*
|
|
@@ -398,7 +398,7 @@ super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.f
|
|
|
398
398
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
399
399
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
400
400
|
*/
|
|
401
|
-
const
|
|
401
|
+
const Ru=/* #__PURE__ */ new Uint8Array([102,76,97,67]);var zu=class extends Iu{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(Ru);let t=this.output.tracks[0];n(t?.isAudioTrack()),t.metadata.decoderConfig&&(ni({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.applyDecoderConfig(t.metadata.decoderConfig)),e()}applyDecoderConfig(e){n(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let t=new j(S(e.description));t.skipBits(167),this.bitsPerSample=t.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:i,maximumFrameSize:a,sampleRate:o,channels:s,totalSamples:c}){n(this.writer.getPos()===4);let l=!Ht(this.output._metadataTags),u=new j(/* @__PURE__ */ new Uint8Array(4));u.writeBits(1,Number(!l)),u.writeBits(7,Qn.STREAMINFO),u.writeBits(24,34),this.writer.write(u.bytes);let d=new j(/* @__PURE__ */ new Uint8Array(18));if(d.writeBits(16,t),d.writeBits(16,r),d.writeBits(24,i),d.writeBits(24,a),d.writeBits(20,o),d.writeBits(3,s-1),d.writeBits(5,e-1),c>=2**32)throw Error(`This muxer only supports writing up to 2 ** 32 samples`);d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(/* @__PURE__ */ new Uint8Array(16))}writePictureBlock(e){let t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,r=new Uint8Array(t),i=0,a=C(r);a.setUint32(i,e.kind===`coverFront`?3:e.kind===`coverBack`?4:0),i+=4,a.setUint32(i,e.mimeType.length),i+=4,r.set(T.encode(e.mimeType),8),i+=e.mimeType.length,a.setUint32(i,e.description?.length??0),i+=4,r.set(T.encode(e.description??``),i),i+=e.description?.length??0,i+=16,a.setUint32(i,e.data.length),i+=4,r.set(e.data,i),i+=e.data.length,n(i===t);let o=new j(/* @__PURE__ */ new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,Qn.PICTURE),o.writeBits(24,t),this.writer.write(o.bytes),this.writer.write(r)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(38+Ru.byteLength),Ht(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let t of e)this.writePictureBlock(t);let t=er(/* @__PURE__ */ new Uint8Array,this.output._metadataTags,!1),n=new j(/* @__PURE__ */ new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,Qn.VORBIS_COMMENT),n.writeBits(24,t.length),this.writer.write(n.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return`audio/flac`}async addEncodedVideoPacket(){throw Error(`FLAC does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),this.sampleRate===null&&(ni(r,e.source._codec),n(r),n(r.decoderConfig),this.applyDecoderConfig(r.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let i=du.tempFromBytes(t.data);i.skip(2);let a=new j(V(i,2)),o=ao(a.readBits(4));if(o===null)throw Error(`Invalid FLAC frame: Invalid block size.`);so(i);let s=co(i,o);this.format._options.appendOnly||(this.blockSizes.push(s),this.frameSizes.push(t.data.length));let c=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,c),await this.writer.flush()}finally{i()}}addSubtitleCue(){throw Error(`FLAC does not support subtitles.`)}async finalize(){let e=await this.mutex.acquire();if(this.sampleRate===null)throw Error(`Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.`);if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let e=1/0,t=0,r=1/0,i=0,a=0;for(let n=0;n<this.blockSizes.length;n++)r=Math.min(r,this.frameSizes[n]),i=Math.max(i,this.frameSizes[n]),t=Math.max(t,this.blockSizes[n]),a+=this.blockSizes[n],n!==this.blockSizes.length-1&&(e=Math.min(e,this.blockSizes[n]));this.blockSizes.length===0&&(e=16,t=65535,r=0,i=0),n(this.channels!==null),n(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:e,maximumBlockSize:t,minimumFrameSize:r,maximumFrameSize:i,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}};
|
|
402
402
|
/*!
|
|
403
403
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
404
404
|
*
|
|
@@ -406,13 +406,13 @@ const Lu=/* #__PURE__ */ new Uint8Array([102,76,97,67]);var Ru=class extends Fu{
|
|
|
406
406
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
407
407
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
408
408
|
*/
|
|
409
|
-
const
|
|
409
|
+
const Bu=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Vu=/^WEBVTT(.|\n)*?\n{2}/,Hu=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;var Uu=class{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
|
|
410
410
|
`,`
|
|
411
411
|
`).replaceAll(`\r`,`
|
|
412
|
-
`),
|
|
412
|
+
`),Bu.lastIndex=0;let t;if(!this.preambleText){if(!Vu.test(e))throw Error(`WebVTT preamble incorrect.`);t=Bu.exec(e);let n=e.slice(0,t?.index??e.length).trimEnd();if(!n)throw Error(`No WebVTT preamble provided.`);this.preambleText=n,t&&(e=e.slice(t.index),Bu.lastIndex=0)}for(;t=Bu.exec(e);){let n=e.slice(0,t.index),r=t[1],i=t.index+t[0].length,a=e.indexOf(`
|
|
413
413
|
`,i)+1,o=e.slice(i,a).trim(),s=e.indexOf(`
|
|
414
414
|
|
|
415
|
-
`,i);s===-1&&(s=e.length);let c=
|
|
415
|
+
`,i);s===-1&&(s=e.length);let c=Gu(t[2]),l=Gu(t[3])-c,u=e.slice(a,s).trim();e=e.slice(s).trimStart(),Bu.lastIndex=0;let d={timestamp:c/1e3,duration:l/1e3,text:u,identifier:r,settings:o,notes:n},f={};this.preambleEmitted||=(f.config={description:this.preambleText},!0),this.options.output(d,f)}}};const Wu=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Gu=e=>{let t=Wu.exec(e);if(!t)throw Error(`Expected match.`);return 36e5*Number(t[1]||`0`)+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])},Ku=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)};
|
|
416
416
|
/*!
|
|
417
417
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
418
418
|
*
|
|
@@ -420,7 +420,7 @@ const zu=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\
|
|
|
420
420
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
421
421
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
422
422
|
*/
|
|
423
|
-
var Ku=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);n(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}};const K=/* #__PURE__ */ new Uint8Array(8),qu=/* #__PURE__ */ new DataView(K.buffer),q=e=>[(e%256+256)%256],J=e=>(qu.setUint16(0,e,!1),[K[0],K[1]]),Ju=e=>(qu.setInt16(0,e,!1),[K[0],K[1]]),Yu=e=>(qu.setUint32(0,e,!1),[K[1],K[2],K[3]]),Y=e=>(qu.setUint32(0,e,!1),[K[0],K[1],K[2],K[3]]),Xu=e=>(qu.setInt32(0,e,!1),[K[0],K[1],K[2],K[3]]),Zu=e=>(qu.setUint32(0,Math.floor(e/2**32),!1),qu.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Qu=e=>(qu.setInt32(0,Math.floor(e/2**32),!1),qu.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),$u=e=>(qu.setInt16(0,256*e,!1),[K[0],K[1]]),ed=e=>(qu.setInt32(0,2**16*e,!1),[K[0],K[1],K[2],K[3]]),td=e=>(qu.setInt32(0,2**30*e,!1),[K[0],K[1],K[2],K[3]]),nd=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},X=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},rd=e=>[ed(e[0]),ed(e[1]),td(e[2]),ed(e[3]),ed(e[4]),td(e[5]),ed(e[6]),ed(e[7]),td(e[8])],Z=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Q=(e,t,n,r,i)=>Z(e,[q(t),Yu(n),r??[]],i),id=e=>e.isQuickTime?Z(`ftyp`,[X(`qt `),Y(512),X(`qt `)]):e.fragmented?e.cmaf?Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]):Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`)]):Z(`ftyp`,[X(`isom`),Y(512),X(`isom`),e.holdsAvc?X(`avc1`):[],X(`mp41`)]),ad=()=>Z(`styp`,[X(`iso5`),Y(0),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]),od=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),Q(`sidx`,1,0,[Y(1),Y(Wf),Zu($(n,Wf)),Zu(0),J(0),J(1),Y(t&2147483647),Y($(r,Wf)),Y(0)])},sd=e=>({type:`mdat`,largeSize:e}),cd=e=>({type:`free`,size:e}),ld=e=>Z(`moov`,void 0,[ud(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>dd(t,e.creationTime)),e.isFragmented?ef(e.trackDatas):null,gf(e)]),ud=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,$(Kf(e),Wf)+$(e.startTimestampOffset??0,Wf)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!g(e)||!g(n),a=i?Zu:Y;return Q(`mvhd`,+i,0,[a(e),a(e),Y(Wf),a(n),ed(1),$u(1),Array(10).fill(0),rd(o),Array(24).fill(0),Y(r)])},dd=(e,t)=>{let n=Gf(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return Z(`trak`,void 0,[fd(e,t),r?pd(e):null,md(e,t),n.name===void 0?null:Z(`udta`,void 0,[Z(`name`,[...T.encode(n.name)])])])},fd=(e,t)=>{let n=Math.max(0,$(Kf(e),Wf)+$(e.startTimestampOffset??0,Wf)),r=!g(t)||!g(n),i=r?Zu:Y,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=p(u(t??0),f(n?-1:1,1));a=s(r,e.info.width,e.info.height)}else a=o;let c=2;e.track.metadata.disposition?.default!==!1&&(c|=1);let l=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Ee(e);return Q(`tkhd`,+r,c,[i(t),i(t),Y(e.track.id),Y(0),i(n),Array(8).fill(0),J(0),J(l),$u(+(e.type===`audio`)),J(0),rd(a),ed(e.type===`video`?e.info.width:0),ed(e.type===`video`?e.info.height:0)])},pd=e=>{let t=e.startTimestampOffset;if(n(t!==null),t>0){let n=$(t,Wf),r=$(Kf(e),Wf),i=!g(n)||!g(r),a=i?Zu:Y,o=i?Qu:Xu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(2),a(n),o(-1),ed(1),a(r),o(0),ed(1)])])}{let n=$(-t,e.timescale),r=Math.max(0,$(Kf(e),Wf)+$(t,Wf)),i=!_(n)||!g(r),a=i?Zu:Y,o=i?Qu:Xu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(1),a(r),o(n),ed(1)])])}},md=(e,t)=>Z(`mdia`,void 0,[hd(e,t),vd(!0,gd[e.type],_d[e.type]),yd(e)]),hd=(e,t)=>{let n=$(Kf(e),e.timescale),r=!g(t)||!g(n),i=r?Zu:Y;return Q(`mdhd`,+r,0,[i(t),i(t),Y(e.timescale),i(n),J(Af(e.track.metadata.languageCode??`und`)),J(0)])},gd={video:`vide`,audio:`soun`,subtitle:`text`},_d={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},vd=(e,t,n,r=`\0\0\0\0`)=>Q(`hdlr`,0,0,[e?X(`mhlr`):Y(0),X(t),X(r),Y(0),Y(0),X(n,!0)]),yd=e=>Z(`minf`,void 0,[bd[e.type](),xd(),wd(e)]),bd={video:()=>Q(`vmhd`,0,1,[J(0),J(0),J(0),J(0)]),audio:()=>Q(`smhd`,0,0,[J(0),J(0)]),subtitle:()=>Q(`nmhd`,0,0)},xd=()=>Z(`dinf`,void 0,[Sd()]),Sd=()=>Q(`dref`,0,0,[Y(1)],[Cd()]),Cd=()=>Q(`url `,0,1),wd=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return Z(`stbl`,void 0,[Td(e),qd(e),t?Qd(e):null,t?$d(e):null,Yd(e),Xd(e),Zd(e),Jd(e)])},Td=e=>{let t;if(e.type===`video`)t=Ed(wf(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let r=Ef(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);n(r),t=Pd(r,e)}else e.type===`subtitle`&&(t=Gd(Of[e.track.source._codec],e));return n(t),Q(`stsd`,0,0,[Y(1)],[t])},Ed=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1),J(0),J(0),Array(12).fill(0),J(t.info.width),J(t.info.height),Y(4718592),Y(4718592),Y(0),J(1),q(18),X(an),Array(13).fill(0),J(t.info.hasAlphaChannel?32:24),Ju(65535)],[Tf[t.track.source._codec]?.(t)??null,Od(t),de(t.info.decoderConfig.colorSpace)?null:kd(t),Dd(t)]),Dd=e=>e.avgBitrate===0&&e.maxBitrate===0?null:Z(`btrt`,[Y(0),Y(e.maxBitrate),Y(e.avgBitrate)]),Od=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Z(`pasp`,[Y(e.info.pixelAspectRatio.num),Y(e.info.pixelAspectRatio.den)]),kd=e=>{let t=e.info.decoderConfig.colorSpace;return Z(`colr`,[X(e.muxer.isQuickTime?`nclc`:`nclx`),J(t?.primaries==null?2:ie[t.primaries]),J(t?.transfer==null?2:oe[t.transfer]),J(t?.matrix==null?2:ce[t.matrix]),e.muxer.isQuickTime?[]:q(!!t?.fullRange<<7)])},Ad=e=>e.info.decoderConfig&&Z(`avcC`,[...S(e.info.decoderConfig.description)]),jd=e=>e.info.decoderConfig&&Z(`hvcC`,[...S(e.info.decoderConfig.description)]),Md=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?ie[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?oe[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ce[t.colorSpace.matrix]:1;return Q(`vpcC`,1,0,[q(r),q(i),q(c),q(l),q(u),q(d),J(0)])},Nd=e=>Z(`av1C`,Lr(e.info.decoderConfig.codec)),Pd=(e,t)=>{let n=0,r,i=16,a=P.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Gr(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(i),J(0),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(Math.min(i,16)),Ju(e),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0),a?[Y(1),Y(i/8),Y(t.info.numberOfChannels*i/8)]:[Y(0),Y(0),Y(0)],Y(2)]}return Z(e,r,[Df(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,Dd(t)])},Fd=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q(t),...q(21),...Yu(0),...Y(e.maxBitrate),...Y(e.avgBitrate)];if(e.info.decoderConfig.description){let t=S(e.info.decoderConfig.description);n=[...n,...q(5),...nd(t.byteLength),...t]}return n=[...J(1),...q(0),...q(4),...nd(n.length),...n,...q(6),...q(1),...q(2)],n=[...q(3),...nd(n.length),...n],Q(`esds`,0,0,n)},Id=e=>Z(`wave`,void 0,[Ld(e),Rd(e),Z(`\0\0\0\0`)]),Ld=e=>Z(`frma`,[X(Ef(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),Rd=e=>{let{littleEndian:t}=Gr(e.track.source._codec);return Z(`enda`,[J(+t)])},zd=e=>{let t=e.info.numberOfChannels,r=3840,i=e.info.sampleRate,a=0,o=0,s=/* @__PURE__ */ new Uint8Array,c=e.info.decoderConfig?.description;if(c){n(c.byteLength>=18);let e=S(c),l=qn(e);t=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,a=l.outputGain,o=l.channelMappingFamily,l.channelMappingTable&&(s=l.channelMappingTable)}return Z(`dOps`,[q(0),q(t),J(r),Y(i),Ju(a),q(o),...s])},Bd=e=>{let t=e.info.decoderConfig?.description;n(t);let r=S(t);return Q(`dfLa`,0,0,[...r.subarray(4)])},Vd=e=>{let{littleEndian:t,sampleSize:n}=Gr(e.track.source._codec),r=+t;return Q(`pcmC`,0,0,[q(r),q(8*n)])},Hd=e=>{n(e.info.primingPacket);let t=nr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let r=/* @__PURE__ */ new Uint8Array(3),i=new j(r);return i.writeBits(2,t.fscod),i.writeBits(5,t.bsid),i.writeBits(3,t.bsmod),i.writeBits(3,t.acmod),i.writeBits(1,t.lfeon),i.writeBits(5,t.bitRateCode),i.writeBits(5,0),Z(`dac3`,[...r])},Ud=e=>{n(e.info.primingPacket);let t=sr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let r=16;for(let e of t.substreams)r+=23,e.numDepSub>0?r+=9:r+=1;let i=Math.ceil(r/8),a=new Uint8Array(i),o=new j(a);o.writeBits(13,t.dataRate),o.writeBits(3,t.substreams.length-1);for(let e of t.substreams)o.writeBits(2,e.fscod),o.writeBits(5,e.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,e.bsmod),o.writeBits(3,e.acmod),o.writeBits(1,e.lfeon),o.writeBits(3,0),o.writeBits(4,e.numDepSub),e.numDepSub>0?o.writeBits(9,e.chanLoc):o.writeBits(1,0);return Z(`dec3`,[...a])},Wd=e=>{n(e.info.primingPacket);let t=yr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return Z(`ddts`,[...wr(t)])},Gd=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1)],[kf[t.track.source._codec](t),Dd(t)]),Kd=e=>Z(`vttC`,[...T.encode(e.info.config.description)]),qd=e=>Q(`stts`,0,0,[Y(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Y(e.sampleCount),Y(e.sampleDelta)])]),Jd=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Q(`stss`,0,0,[Y(t.length),t.map(([e])=>Y(e+1))])},Yd=e=>Q(`stsc`,0,0,[Y(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Y(e.firstChunk),Y(e.samplesPerChunk),Y(1)])]),Xd=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Gr(e.track.source._codec);return Q(`stsz`,0,0,[Y(t*e.info.numberOfChannels),Y(e.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0))])}return Q(`stsz`,0,0,[Y(0),Y(e.samples.length),e.samples.map(e=>Y(e.size))])},Zd=e=>e.finalizedChunks.length>0&&h(e.finalizedChunks).offset>=2**32?Q(`co64`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Zu(e.offset))]):Q(`stco`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Y(e.offset))]),Qd=e=>Q(`ctts`,1,0,[Y(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Y(e.sampleCount),Xu(e.sampleCompositionTimeOffset)])]),$d=e=>{let t=1/0,r=-1/0,i=1/0,a=-1/0;n(e.compositionTimeOffsetTable.length>0),n(e.samples.length>0);for(let n=0;n<e.compositionTimeOffsetTable.length;n++){let i=e.compositionTimeOffsetTable[n];t=Math.min(t,i.sampleCompositionTimeOffset),r=Math.max(r,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];i=Math.min(i,$(n.timestamp,e.timescale)),a=Math.max(a,$(n.timestamp+n.duration,e.timescale))}let o=Math.max(-t,0);return a>=2**31?null:Q(`cslg`,0,0,[Xu(o),Xu(t),Xu(r),Xu(i),Xu(a)])},ef=e=>Z(`mvex`,void 0,e.map(tf)),tf=e=>Q(`trex`,0,0,[Y(e.track.id),Y(1),Y(0),Y(0),Y(0)]),nf=(e,t)=>Z(`moof`,void 0,[rf(e),...t.map(of)]),rf=e=>Q(`mfhd`,0,0,[Y(e)]),af=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},of=e=>Z(`traf`,void 0,[sf(e),cf(e),lf(e)]),sf=e=>{n(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:af(r)};return Q(`tfhd`,0,t,[Y(e.track.id),Y(i.duration),Y(i.size),Y(i.flags)])},cf=e=>(n(e.currentChunk),Q(`tfdt`,1,0,[Zu($(e.currentChunk.startTimestamp,e.timescale))])),lf=e=>{n(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),i=e.currentChunk.samples.map(af),a=e.currentChunk.samples.map(t=>$(t.timestamp-t.decodeTimestamp,e.timescale)),o=new Set(t),s=new Set(r),c=new Set(i),l=new Set(a),u=c.size===2&&i[0]!==i[1],d=o.size>1,f=s.size>1,p=!u&&c.size>1,m=l.size>1||[...l].some(e=>e!==0),h=0;return h|=1,h|=4*u,h|=256*d,h|=512*f,h|=1024*p,h|=2048*m,Q(`trun`,1,h,[Y(e.currentChunk.samples.length),Y(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?Y(i[0]):[],e.currentChunk.samples.map((e,n)=>[d?Y(t[n]):[],f?Y(r[n]):[],p?Y(i[n]):[],m?Xu(a[n]):[]])])},uf=e=>Z(`mfra`,void 0,[...e.map(df),ff()]),df=e=>Q(`tfra`,1,0,[Y(e.track.id),Y(63),Y(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Zu($(t.samples[0].timestamp,e.timescale)),Zu(t.moofOffset),Y(t.trafIndex+1),Y(1),Y(1)])]),ff=()=>Q(`mfro`,0,0,[Y(0)]),pf=()=>Z(`vtte`),mf=(e,t,n,r,i)=>Z(`vttc`,void 0,[i===null?null:Z(`vsid`,[Xu(i)]),n===null?null:Z(`iden`,[...T.encode(n)]),t===null?null:Z(`ctim`,[...T.encode(Gu(t))]),r===null?null:Z(`sttg`,[...T.encode(r)]),Z(`payl`,[...T.encode(e)])]),hf=e=>Z(`vtta`,[...T.encode(e)]),gf=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=xf(r);e&&t.push(e)}else if(n===`mdta`){let e=Sf(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&_f(t,e.output._metadataTags);return t.length===0?null:Z(`udta`,void 0,t)},_f=(e,t)=>{for(let{key:n,value:r}of lt(t))switch(n){case`title`:e.push(vf(`©nam`,r));break;case`description`:e.push(vf(`©des`,r));break;case`artist`:e.push(vf(`©ART`,r));break;case`album`:e.push(vf(`©alb`,r));break;case`albumArtist`:e.push(vf(`albr`,r));break;case`genre`:e.push(vf(`©gen`,r));break;case`date`:e.push(vf(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(vf(`©cmt`,r));break;case`lyrics`:e.push(vf(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`beatsPerMinute`:case`images`:break;default:Ee(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(vf(n,r)):r instanceof Uint8Array&&e.push(Z(n,Array.from(r))))}},vf=(e,t)=>{let n=T.encode(t);return Z(e,[J(n.length),J(Af(`und`)),Array.from(n)])},yf={"image/jpeg":13,"image/png":14,"image/bmp":27},bf=(e,t)=>{let n=[];for(let{key:r,value:i}of lt(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:Cf(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:Cf(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:Cf(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:Cf(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:Cf(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:Cf(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:Cf(i)});break;case`beatsPerMinute`:t||n.push({key:`tmpo`,value:Z(`data`,[Y(21),Y(0),J(i)])});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:Cf(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:Cf(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:Z(`data`,[Y(yf[e.mimeType]??0),Y(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:Cf(t)})}else n.push({key:`trkn`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.tracksTotal??0),J(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.discsTotal??0),J(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ee(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:Cf(i)}):i instanceof Uint8Array?n.push({key:r,value:Z(`data`,[Y(0),Y(0),Array.from(i)])}):i instanceof zt&&n.push({key:r,value:Z(`data`,[Y(yf[i.mimeType]??0),Y(0),Array.from(i.data)])}))}return n},xf=e=>{let t=bf(e,!1);return t.length===0?null:Q(`meta`,0,0,void 0,[vd(!1,`mdir`,``,`appl`),Z(`ilst`,void 0,t.map(e=>Z(e.key,void 0,[e.value])))])},Sf=e=>{let t=bf(e,!0);return t.length===0?null:Z(`meta`,void 0,[vd(!1,`mdta`,``),Q(`keys`,0,0,[Y(t.length)],t.map(e=>Z(`mdta`,[...T.encode(e.key)]))),Z(`ilst`,void 0,t.map((e,t)=>{let n=String.fromCharCode(...Y(t+1));return Z(n,void 0,[e.value])}))])},Cf=e=>Z(`data`,[Y(1),Y(0),...T.encode(e)]),wf=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Tf={avc:Ad,hevc:jd,vp8:Md,vp9:Md,av1:Nd,prores:null},Ef=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Df=(e,t)=>{switch(e){case`aac`:return Fd;case`mp3`:return Fd;case`opus`:return zd;case`vorbis`:return Fd;case`flac`:return Bd;case`ac3`:return Hd;case`eac3`:return Ud;case`dts`:return Wd}if(t)switch(e){case`pcm-s24`:return Id;case`pcm-s24be`:return Id;case`pcm-s32`:return Id;case`pcm-s32be`:return Id;case`pcm-f32`:return Id;case`pcm-f32be`:return Id;case`pcm-f64`:return Id;case`pcm-f64be`:return Id}else switch(e){case`pcm-s16`:return Vd;case`pcm-s16be`:return Vd;case`pcm-s24`:return Vd;case`pcm-s24be`:return Vd;case`pcm-s32`:return Vd;case`pcm-s32be`:return Vd;case`pcm-f32`:return Vd;case`pcm-f32be`:return Vd;case`pcm-f64`:return Vd;case`pcm-f64be`:return Vd}return null},Of={webvtt:`wvtt`},kf={webvtt:Kd},Af=e=>{n(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t};
|
|
423
|
+
var qu=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */ new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);n(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}};const K=/* #__PURE__ */ new Uint8Array(8),Ju=/* #__PURE__ */ new DataView(K.buffer),q=e=>[(e%256+256)%256],J=e=>(Ju.setUint16(0,e,!1),[K[0],K[1]]),Yu=e=>(Ju.setInt16(0,e,!1),[K[0],K[1]]),Xu=e=>(Ju.setUint32(0,e,!1),[K[1],K[2],K[3]]),Y=e=>(Ju.setUint32(0,e,!1),[K[0],K[1],K[2],K[3]]),Zu=e=>(Ju.setInt32(0,e,!1),[K[0],K[1],K[2],K[3]]),Qu=e=>(Ju.setUint32(0,Math.floor(e/2**32),!1),Ju.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),$u=e=>(Ju.setInt32(0,Math.floor(e/2**32),!1),Ju.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),ed=e=>(Ju.setInt16(0,256*e,!1),[K[0],K[1]]),td=e=>(Ju.setInt32(0,2**16*e,!1),[K[0],K[1],K[2],K[3]]),nd=e=>(Ju.setInt32(0,2**30*e,!1),[K[0],K[1],K[2],K[3]]),rd=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},X=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},id=e=>[td(e[0]),td(e[1]),nd(e[2]),td(e[3]),td(e[4]),nd(e[5]),td(e[6]),td(e[7]),nd(e[8])],Z=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Q=(e,t,n,r,i)=>Z(e,[q(t),Xu(n),r??[]],i),ad=e=>e.isQuickTime?Z(`ftyp`,[X(`qt `),Y(512),X(`qt `)]):e.fragmented?e.cmaf?Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]):Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`)]):Z(`ftyp`,[X(`isom`),Y(512),X(`isom`),e.holdsAvc?X(`avc1`):[],X(`mp41`)]),od=()=>Z(`styp`,[X(`iso5`),Y(0),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]),sd=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),Q(`sidx`,1,0,[Y(1),Y(Gf),Qu($(n,Gf)),Qu(0),J(0),J(1),Y(t&2147483647),Y($(r,Gf)),Y(0)])},cd=e=>({type:`mdat`,largeSize:e}),ld=e=>({type:`free`,size:e}),ud=e=>Z(`moov`,void 0,[dd(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>fd(t,e.creationTime)),e.isFragmented?tf(e.trackDatas):null,_f(e)]),dd=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,$(qf(e),Gf)+$(e.startTimestampOffset??0,Gf)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!g(e)||!g(n),a=i?Qu:Y;return Q(`mvhd`,+i,0,[a(e),a(e),Y(Gf),a(n),td(1),ed(1),Array(10).fill(0),id(o),Array(24).fill(0),Y(r)])},fd=(e,t)=>{let n=Kf(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return Z(`trak`,void 0,[pd(e,t),r?md(e):null,hd(e,t),n.name===void 0?null:Z(`udta`,void 0,[Z(`name`,[...T.encode(n.name)])])])},pd=(e,t)=>{let n=Math.max(0,$(qf(e),Gf)+$(e.startTimestampOffset??0,Gf)),r=!g(t)||!g(n),i=r?Qu:Y,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=p(u(t??0),f(n?-1:1,1));a=s(r,e.info.width,e.info.height)}else a=o;let c=2;e.track.metadata.disposition?.default!==!1&&(c|=1);let l=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Ee(e);return Q(`tkhd`,+r,c,[i(t),i(t),Y(e.track.id),Y(0),i(n),Array(8).fill(0),J(0),J(l),ed(+(e.type===`audio`)),J(0),id(a),td(e.type===`video`?e.info.width:0),td(e.type===`video`?e.info.height:0)])},md=e=>{let t=e.startTimestampOffset;if(n(t!==null),t>0){let n=$(t,Gf),r=$(qf(e),Gf),i=!g(n)||!g(r),a=i?Qu:Y,o=i?$u:Zu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(2),a(n),o(-1),td(1),a(r),o(0),td(1)])])}{let n=$(-t,e.timescale),r=Math.max(0,$(qf(e),Gf)+$(t,Gf)),i=!_(n)||!g(r),a=i?Qu:Y,o=i?$u:Zu;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(1),a(r),o(n),td(1)])])}},hd=(e,t)=>Z(`mdia`,void 0,[gd(e,t),yd(!0,_d[e.type],vd[e.type]),bd(e)]),gd=(e,t)=>{let n=$(qf(e),e.timescale),r=!g(t)||!g(n),i=r?Qu:Y;return Q(`mdhd`,+r,0,[i(t),i(t),Y(e.timescale),i(n),J(jf(e.track.metadata.languageCode??`und`)),J(0)])},_d={video:`vide`,audio:`soun`,subtitle:`text`},vd={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},yd=(e,t,n,r=`\0\0\0\0`)=>Q(`hdlr`,0,0,[e?X(`mhlr`):Y(0),X(t),X(r),Y(0),Y(0),X(n,!0)]),bd=e=>Z(`minf`,void 0,[xd[e.type](),Sd(),Td(e)]),xd={video:()=>Q(`vmhd`,0,1,[J(0),J(0),J(0),J(0)]),audio:()=>Q(`smhd`,0,0,[J(0),J(0)]),subtitle:()=>Q(`nmhd`,0,0)},Sd=()=>Z(`dinf`,void 0,[Cd()]),Cd=()=>Q(`dref`,0,0,[Y(1)],[wd()]),wd=()=>Q(`url `,0,1),Td=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return Z(`stbl`,void 0,[Ed(e),Jd(e),t?$d(e):null,t?ef(e):null,Xd(e),Zd(e),Qd(e),Yd(e)])},Ed=e=>{let t;if(e.type===`video`)t=Dd(Tf(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let r=Df(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);n(r),t=Fd(r,e)}else e.type===`subtitle`&&(t=Kd(kf[e.track.source._codec],e));return n(t),Q(`stsd`,0,0,[Y(1)],[t])},Dd=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1),J(0),J(0),Array(12).fill(0),J(t.info.width),J(t.info.height),Y(4718592),Y(4718592),Y(0),J(1),q(18),X(an),Array(13).fill(0),J(t.info.hasAlphaChannel?32:24),Yu(65535)],[Ef[t.track.source._codec]?.(t)??null,kd(t),de(t.info.decoderConfig.colorSpace)?null:Ad(t),Od(t)]),Od=e=>e.avgBitrate===0&&e.maxBitrate===0?null:Z(`btrt`,[Y(0),Y(e.maxBitrate),Y(e.avgBitrate)]),kd=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Z(`pasp`,[Y(e.info.pixelAspectRatio.num),Y(e.info.pixelAspectRatio.den)]),Ad=e=>{let t=e.info.decoderConfig.colorSpace;return Z(`colr`,[X(e.muxer.isQuickTime?`nclc`:`nclx`),J(t?.primaries==null?2:ie[t.primaries]),J(t?.transfer==null?2:oe[t.transfer]),J(t?.matrix==null?2:ce[t.matrix]),e.muxer.isQuickTime?[]:q(!!t?.fullRange<<7)])},jd=e=>e.info.decoderConfig&&Z(`avcC`,[...S(e.info.decoderConfig.description)]),Md=e=>e.info.decoderConfig&&Z(`hvcC`,[...S(e.info.decoderConfig.description)]),Nd=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?ie[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?oe[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ce[t.colorSpace.matrix]:1;return Q(`vpcC`,1,0,[q(r),q(i),q(c),q(l),q(u),q(d),J(0)])},Pd=e=>Z(`av1C`,Lr(e.info.decoderConfig.codec)),Fd=(e,t)=>{let n=0,r,i=16,a=P.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Gr(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(i),J(0),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(Math.min(i,16)),Yu(e),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0),a?[Y(1),Y(i/8),Y(t.info.numberOfChannels*i/8)]:[Y(0),Y(0),Y(0)],Y(2)]}return Z(e,r,[Of(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,Od(t)])},Id=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q(t),...q(21),...Xu(0),...Y(e.maxBitrate),...Y(e.avgBitrate)];if(e.info.decoderConfig.description){let t=S(e.info.decoderConfig.description);n=[...n,...q(5),...rd(t.byteLength),...t]}return n=[...J(1),...q(0),...q(4),...rd(n.length),...n,...q(6),...q(1),...q(2)],n=[...q(3),...rd(n.length),...n],Q(`esds`,0,0,n)},Ld=e=>Z(`wave`,void 0,[Rd(e),zd(e),Z(`\0\0\0\0`)]),Rd=e=>Z(`frma`,[X(Df(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),zd=e=>{let{littleEndian:t}=Gr(e.track.source._codec);return Z(`enda`,[J(+t)])},Bd=e=>{let t=e.info.numberOfChannels,r=3840,i=e.info.sampleRate,a=0,o=0,s=/* @__PURE__ */ new Uint8Array,c=e.info.decoderConfig?.description;if(c){n(c.byteLength>=18);let e=S(c),l=qn(e);t=l.outputChannelCount,r=l.preSkip,i=l.inputSampleRate,a=l.outputGain,o=l.channelMappingFamily,l.channelMappingTable&&(s=l.channelMappingTable)}return Z(`dOps`,[q(0),q(t),J(r),Y(i),Yu(a),q(o),...s])},Vd=e=>{let t=e.info.decoderConfig?.description;n(t);let r=S(t);return Q(`dfLa`,0,0,[...r.subarray(4)])},Hd=e=>{let{littleEndian:t,sampleSize:n}=Gr(e.track.source._codec),r=+t;return Q(`pcmC`,0,0,[q(r),q(8*n)])},Ud=e=>{n(e.info.primingPacket);let t=nr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let r=/* @__PURE__ */ new Uint8Array(3),i=new j(r);return i.writeBits(2,t.fscod),i.writeBits(5,t.bsid),i.writeBits(3,t.bsmod),i.writeBits(3,t.acmod),i.writeBits(1,t.lfeon),i.writeBits(5,t.bitRateCode),i.writeBits(5,0),Z(`dac3`,[...r])},Wd=e=>{n(e.info.primingPacket);let t=sr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let r=16;for(let e of t.substreams)r+=23,e.numDepSub>0?r+=9:r+=1;let i=Math.ceil(r/8),a=new Uint8Array(i),o=new j(a);o.writeBits(13,t.dataRate),o.writeBits(3,t.substreams.length-1);for(let e of t.substreams)o.writeBits(2,e.fscod),o.writeBits(5,e.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,e.bsmod),o.writeBits(3,e.acmod),o.writeBits(1,e.lfeon),o.writeBits(3,0),o.writeBits(4,e.numDepSub),e.numDepSub>0?o.writeBits(9,e.chanLoc):o.writeBits(1,0);return Z(`dec3`,[...a])},Gd=e=>{n(e.info.primingPacket);let t=yr(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return Z(`ddts`,[...wr(t)])},Kd=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1)],[Af[t.track.source._codec](t),Od(t)]),qd=e=>Z(`vttC`,[...T.encode(e.info.config.description)]),Jd=e=>Q(`stts`,0,0,[Y(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Y(e.sampleCount),Y(e.sampleDelta)])]),Yd=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Q(`stss`,0,0,[Y(t.length),t.map(([e])=>Y(e+1))])},Xd=e=>Q(`stsc`,0,0,[Y(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Y(e.firstChunk),Y(e.samplesPerChunk),Y(1)])]),Zd=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Gr(e.track.source._codec);return Q(`stsz`,0,0,[Y(t*e.info.numberOfChannels),Y(e.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0))])}return Q(`stsz`,0,0,[Y(0),Y(e.samples.length),e.samples.map(e=>Y(e.size))])},Qd=e=>e.finalizedChunks.length>0&&h(e.finalizedChunks).offset>=2**32?Q(`co64`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Qu(e.offset))]):Q(`stco`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Y(e.offset))]),$d=e=>Q(`ctts`,1,0,[Y(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Y(e.sampleCount),Zu(e.sampleCompositionTimeOffset)])]),ef=e=>{let t=1/0,r=-1/0,i=1/0,a=-1/0;n(e.compositionTimeOffsetTable.length>0),n(e.samples.length>0);for(let n=0;n<e.compositionTimeOffsetTable.length;n++){let i=e.compositionTimeOffsetTable[n];t=Math.min(t,i.sampleCompositionTimeOffset),r=Math.max(r,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];i=Math.min(i,$(n.timestamp,e.timescale)),a=Math.max(a,$(n.timestamp+n.duration,e.timescale))}let o=Math.max(-t,0);return a>=2**31?null:Q(`cslg`,0,0,[Zu(o),Zu(t),Zu(r),Zu(i),Zu(a)])},tf=e=>Z(`mvex`,void 0,e.map(nf)),nf=e=>Q(`trex`,0,0,[Y(e.track.id),Y(1),Y(0),Y(0),Y(0)]),rf=(e,t)=>Z(`moof`,void 0,[af(e),...t.map(sf)]),af=e=>Q(`mfhd`,0,0,[Y(e)]),of=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},sf=e=>Z(`traf`,void 0,[cf(e),lf(e),uf(e)]),cf=e=>{n(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:of(r)};return Q(`tfhd`,0,t,[Y(e.track.id),Y(i.duration),Y(i.size),Y(i.flags)])},lf=e=>(n(e.currentChunk),Q(`tfdt`,1,0,[Qu($(e.currentChunk.startTimestamp,e.timescale))])),uf=e=>{n(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),i=e.currentChunk.samples.map(of),a=e.currentChunk.samples.map(t=>$(t.timestamp-t.decodeTimestamp,e.timescale)),o=new Set(t),s=new Set(r),c=new Set(i),l=new Set(a),u=c.size===2&&i[0]!==i[1],d=o.size>1,f=s.size>1,p=!u&&c.size>1,m=l.size>1||[...l].some(e=>e!==0),h=0;return h|=1,h|=4*u,h|=256*d,h|=512*f,h|=1024*p,h|=2048*m,Q(`trun`,1,h,[Y(e.currentChunk.samples.length),Y(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?Y(i[0]):[],e.currentChunk.samples.map((e,n)=>[d?Y(t[n]):[],f?Y(r[n]):[],p?Y(i[n]):[],m?Zu(a[n]):[]])])},df=e=>Z(`mfra`,void 0,[...e.map(ff),pf()]),ff=e=>Q(`tfra`,1,0,[Y(e.track.id),Y(63),Y(e.finalizedChunks.length),e.finalizedChunks.map(t=>[Qu($(t.samples[0].timestamp,e.timescale)),Qu(t.moofOffset),Y(t.trafIndex+1),Y(1),Y(1)])]),pf=()=>Q(`mfro`,0,0,[Y(0)]),mf=()=>Z(`vtte`),hf=(e,t,n,r,i)=>Z(`vttc`,void 0,[i===null?null:Z(`vsid`,[Zu(i)]),n===null?null:Z(`iden`,[...T.encode(n)]),t===null?null:Z(`ctim`,[...T.encode(Ku(t))]),r===null?null:Z(`sttg`,[...T.encode(r)]),Z(`payl`,[...T.encode(e)])]),gf=e=>Z(`vtta`,[...T.encode(e)]),_f=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Sf(r);e&&t.push(e)}else if(n===`mdta`){let e=Cf(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&vf(t,e.output._metadataTags);return t.length===0?null:Z(`udta`,void 0,t)},vf=(e,t)=>{for(let{key:n,value:r}of lt(t))switch(n){case`title`:e.push(yf(`©nam`,r));break;case`description`:e.push(yf(`©des`,r));break;case`artist`:e.push(yf(`©ART`,r));break;case`album`:e.push(yf(`©alb`,r));break;case`albumArtist`:e.push(yf(`albr`,r));break;case`genre`:e.push(yf(`©gen`,r));break;case`date`:e.push(yf(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(yf(`©cmt`,r));break;case`lyrics`:e.push(yf(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`beatsPerMinute`:case`images`:break;default:Ee(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(yf(n,r)):r instanceof Uint8Array&&e.push(Z(n,Array.from(r))))}},yf=(e,t)=>{let n=T.encode(t);return Z(e,[J(n.length),J(jf(`und`)),Array.from(n)])},bf={"image/jpeg":13,"image/png":14,"image/bmp":27},xf=(e,t)=>{let n=[];for(let{key:r,value:i}of lt(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:wf(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:wf(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:wf(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:wf(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:wf(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:wf(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:wf(i)});break;case`beatsPerMinute`:t||n.push({key:`tmpo`,value:Z(`data`,[Y(21),Y(0),J(i)])});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:wf(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:wf(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:Z(`data`,[Y(bf[e.mimeType]??0),Y(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:wf(t)})}else n.push({key:`trkn`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.tracksTotal??0),J(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.discsTotal??0),J(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ee(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:wf(i)}):i instanceof Uint8Array?n.push({key:r,value:Z(`data`,[Y(0),Y(0),Array.from(i)])}):i instanceof zt&&n.push({key:r,value:Z(`data`,[Y(bf[i.mimeType]??0),Y(0),Array.from(i.data)])}))}return n},Sf=e=>{let t=xf(e,!1);return t.length===0?null:Q(`meta`,0,0,void 0,[yd(!1,`mdir`,``,`appl`),Z(`ilst`,void 0,t.map(e=>Z(e.key,void 0,[e.value])))])},Cf=e=>{let t=xf(e,!0);return t.length===0?null:Z(`meta`,void 0,[yd(!1,`mdta`,``),Q(`keys`,0,0,[Y(t.length)],t.map(e=>Z(`mdta`,[...T.encode(e.key)]))),Z(`ilst`,void 0,t.map((e,t)=>{let n=String.fromCharCode(...Y(t+1));return Z(n,void 0,[e.value])}))])},wf=e=>Z(`data`,[Y(1),Y(0),...T.encode(e)]),Tf=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},Ef={avc:jd,hevc:Md,vp8:Nd,vp9:Nd,av1:Pd,prores:null},Df=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Of=(e,t)=>{switch(e){case`aac`:return Id;case`mp3`:return Id;case`opus`:return Bd;case`vorbis`:return Id;case`flac`:return Vd;case`ac3`:return Ud;case`eac3`:return Wd;case`dts`:return Gd}if(t)switch(e){case`pcm-s24`:return Ld;case`pcm-s24be`:return Ld;case`pcm-s32`:return Ld;case`pcm-s32be`:return Ld;case`pcm-f32`:return Ld;case`pcm-f32be`:return Ld;case`pcm-f64`:return Ld;case`pcm-f64be`:return Ld}else switch(e){case`pcm-s16`:return Hd;case`pcm-s16be`:return Hd;case`pcm-s24`:return Hd;case`pcm-s24be`:return Hd;case`pcm-s32`:return Hd;case`pcm-s32be`:return Hd;case`pcm-f32`:return Hd;case`pcm-f32be`:return Hd;case`pcm-f64`:return Hd;case`pcm-f64be`:return Hd}return null},kf={webvtt:`wvtt`},Af={webvtt:qd},jf=e=>{n(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t};
|
|
424
424
|
/*!
|
|
425
425
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
426
426
|
*
|
|
@@ -428,7 +428,7 @@ var Ku=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8A
|
|
|
428
428
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
429
429
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
430
430
|
*/
|
|
431
|
-
var
|
|
431
|
+
var Mf=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){n(!this.started),this.target._start(),this.started=!0}write(e){n(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return n(this.started&&!this.finalized),this.target._flush()}async finalize(){n(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=/* @__PURE__ */ new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};
|
|
432
432
|
/*!
|
|
433
433
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
434
434
|
*
|
|
@@ -436,7 +436,7 @@ var jf=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,th
|
|
|
436
436
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
437
437
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
438
438
|
*/
|
|
439
|
-
const
|
|
439
|
+
const Nf=zo===void 0?void 0:zo;var Pf=class extends Pt{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new Uf(this,e)}};const Ff=2**16,If=2**32;var Lf=class extends Pf{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in/* @__PURE__ */ new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Ff,{maxByteLength:If})}catch{this._buffer=new ArrayBuffer(Ff),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Ff);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>If)throw Error(`ArrayBuffer exceeded maximum size of ${If} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}};const Rf=2**24;var zf=class extends Pf{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw TypeError(`StreamTarget requires a WritableStream instance.`);if(t!=null&&typeof t!=`object`)throw TypeError(`StreamTarget options, when provided, must be an object.`);if(t.chunked!==void 0&&typeof t.chunked!=`boolean`)throw TypeError(`options.chunked, when provided, must be a boolean.`);if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw TypeError(`options.chunkSize, when provided, must be an integer and not smaller than 1024.`);this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??Rf}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let e=t-this._lastWriteEnd;this._write(new Uint8Array(e),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(n(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((e,t)=>e.start-t.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let r=e[e.length-1],i=t[n];i.start<=r.start+r.size?r.size=Math.max(r.size,i.start+i.data.byteLength-r.start):e.push({start:i.start,size:i.data.byteLength})}for(let t of e){t.data=new Uint8Array(t.size);for(let e of this._sections)t.start<=e.start&&e.start<t.start+t.size&&t.data.set(e.data,e.start-t.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(t.data,t.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&t.start!==this._lastFlushEnd)throw Error(`Internal error: Monotonicity violation.`);this._streamWriter.write({type:`write`,data:t.data,position:t.start}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=t.start+t.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(e=>e.start<=t&&t<e.start+this._chunkSize);n===-1&&(n=this._createChunk(t));let r=this._chunks[n],i=t-r.start,a=e.subarray(0,Math.min(this._chunkSize-i,e.byteLength));r.data.set(a,i);let o={start:i,end:i+a.byteLength};if(this._insertSectionIntoChunk(r,o),r.written[0].start===0&&r.written[0].end===this._chunkSize&&(r.shouldFlush=!0),this._chunks.length>2){for(let e=0;e<this._chunks.length-1;e++)this._chunks[e].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,r=e.written.length-1,i=-1;for(;n<=r;){let a=Math.floor(n+(r-n+1)/2);e.written[a].start<=t.start?(n=a+1,i=a):r=a-1}for(e.written.splice(i+1,0,t),(i===-1||e.written[i].end<t.start)&&i++;i<e.written.length-1&&e.written[i].end>=e.written[i+1].start;)e.written[i].end=Math.max(e.written[i].end,e.written[i+1].end),e.written.splice(i+1,1)}_createChunk(e){let t={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(t),this._chunks.sort((e,t)=>e.start-t.start),this._chunks.indexOf(t)}_tryToFlushChunks(e=!1){n(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let n=this._chunks[t];if(n.shouldFlush||e){for(let e of n.written){let t=n.start+e.start;if(this._monotonicity===!0&&t!==this._lastFlushEnd)throw Error(`Internal error: Monotonicity violation.`);let r=e.start!==0||e.end!==n.data.byteLength,i;i=r&&Ze()?n.data.slice(e.start,e.end):n.data.subarray(e.start,e.end),this._streamWriter.write({type:`write`,data:i,position:t}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=n.start+e.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;n(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit(`finalized`)}async _close(){return this._streamWriter?.close()}},Bf=class extends Pf{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new zf(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:e=>{if(this._monotonicity!==!0)throw Error(`AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.`);return n(e.position===this._nextWritePos),this._nextWritePos+=e.data.byteLength,n(this._writer),this._writer.write(e.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Vf=class extends Pf{constructor(e,t={}){if(typeof e!=`string`)throw TypeError(`filePath must be a string.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Nf.fs)throw Error(`FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).`);super(),this._fileHandle=null;let r=new WritableStream({start:async()=>{this._fileHandle=await Nf.fs.open(e,`w`)},write:async e=>{n(this._fileHandle),await this._fileHandle.write(e.data,0,e.data.byteLength,e.position)},close:async()=>{this._fileHandle&&=(await this._fileHandle.close(),null)}});this._streamTarget=new zf(r,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit(`finalized`)}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Hf=class extends Pf{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},Uf=class extends Pf{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Wf=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}};
|
|
440
440
|
/*!
|
|
441
441
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
442
442
|
*
|
|
@@ -444,7 +444,7 @@ const Mf=Ro===void 0?void 0:Ro;var Nf=class extends Pt{constructor(){super(...ar
|
|
|
444
444
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
445
445
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
446
446
|
*/
|
|
447
|
-
const Wf=57600,Gf=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},$=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Kf=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t};var qf=class extends Fu{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new If,this.auxWriter=new jf(this.auxTarget,!1),this.auxBoxWriter=new Ku(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=D(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Yp,this.isCmaf=t instanceof Jp,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Jp?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof If:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Ku(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof If&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new jf(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Ku(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(n(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(id({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(n(this.writer),n(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=sd(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return gi({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig};n(a.codedWidth!==void 0),n(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=_n(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=vn(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=On(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=In(e),o=!0}let s=Je(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:xt({num:c*a.codedHeight,den:l*a.codedWidth}),d=a.codec===`ap4h`||a.codec===`ap4x`,f={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:o,hasAlphaChannel:d},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=eo(uu.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Gt[e.samplingFrequencyIndex],r=Kt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Xt({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),o=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let s={muxer:this,track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&P.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:t},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ri(t),n(t),n(t.config);let i={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...sn(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=hn(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=eo(uu.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=Gr(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=$(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Gr(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let r=/* @__PURE__ */ new Set([]);for(let i of e.cueQueue)n(i.timestamp<=t),n(e.lastCueEndTimestamp<=i.timestamp+i.duration),r.add(Math.max(i.timestamp,e.lastCueEndTimestamp)),r.add(i.timestamp+i.duration);let i=[...r].sort((e,t)=>e-t),a=i[0],o=i[1]??a;if(t<o)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);let t=pf();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=o)break;Vu.lastIndex=0;let r=Vu.test(n.text),i=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&o<i&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=hf(n.notes);this.auxBoxWriter.writeBox(e)}let c=mf(n.text,r?a:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),i===o&&e.cueQueue.splice(t--,1)}let s=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,s,a,o-a,`key`);await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:$(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){n(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=$(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=h(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(r[0],0):e.startTimestampOffset??=r[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let i=e.timestampProcessingQueue[t];i.decodeTimestamp=r[t];let a=$(i.timestamp-i.decodeTimestamp,e.timescale),o=$(i.duration,e.timescale);if(e.lastTimescaleUnits!==null){n(e.lastSample);let t=$(i.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(n(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=h(e.timeToSampleTable);if(n(t),t.sampleCount===1){t.sampleDelta=r;let n=e.timeToSampleTable[e.timeToSampleTable.length-2];n&&n.sampleDelta===r&&(n.sampleCount++,e.timeToSampleTable.pop(),t=n)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===o?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let i=h(e.compositionTimeOffsetTable);n(i),i.sampleCompositionTimeOffset===a?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$(i.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=i}if(e.timestampProcessingQueue.length=0,n(e.lastSample),n(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){n(t.type===`key`);let r=$(t.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(n(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});n>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=n>=.5}r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),n(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(n(!this.isFragmented),n(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||h(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)n(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(n(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(n(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;n(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=ld(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){n(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Ku(this.writer);let e=this.boxWriter.measureBox(ad()),t=this.boxWriter.measureBox(od(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}n(this.writer),n(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let r=this.nextFragmentNumber++,i=nf(r,t),a=this.writer.getPos(),o=a+this.boxWriter.measureBox(i),s=o+8,c=1/0;for(let e=0;e<t.length;e++){let r=t[e];n(r.currentChunk),n(r.startTimestampOffset!==null),r.currentChunk.offset=s,r.currentChunk.moofOffset=a,r.currentChunk.trafIndex=e,r.currentChunk.startTimestamp-=r.startTimestampOffset;for(let e of r.currentChunk.samples)s+=e.size,e.timestamp-=r.startTimestampOffset,e.decodeTimestamp-=r.startTimestampOffset;c=Math.min(c,r.currentChunk.startTimestamp)}let l=s-o,u=l>=2**32;if(u)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let d=nf(r,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,c)}n(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=sd(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(u?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){n(this.writer),n(this.boxWriter),this.ensureOneEnabledTrack();let e=ld(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;n(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=sd(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){n(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let r=t.track.metadata.maximumPacketCount;n(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){n(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=Kf(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(n(this.writer),n(this.boxWriter),this.fastStart===`in-memory`){this.mdat=sd(!1);let e;for(let t=0;t<2;t++){let t=ld(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let i=this.writer.getPos()+r+e;for(let t of this.finalizedChunks){t.offset=i;for(let{data:r}of t.samples)n(r),i+=r.byteLength,e+=r.byteLength}if(i<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=ld(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)n(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(ad()),this.boxWriter.writeBox(od(this,e))}else{let e=this.writer.getPos(),t=uf(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{n(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);n(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let r=ld(this);if(this.fastStart===`reserve`){n(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(cd(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}};
|
|
447
|
+
const Gf=57600,Kf=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},$=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},qf=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t};var Jf=class extends Iu{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Lf,this.auxWriter=new Mf(this.auxTarget,!1),this.auxBoxWriter=new qu(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=D(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Qp,this.isCmaf=t instanceof Zp,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Zp?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof Lf:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new qu(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Lf&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new Mf(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new qu(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(n(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(ad({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(n(this.writer),n(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=cd(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return gi({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig};n(a.codedWidth!==void 0),n(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=_n(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=vn(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=On(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=In(e),o=!0}let s=Je(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:xt({num:c*a.codedHeight,den:l*a.codedWidth}),d=a.codec===`ap4h`||a.codec===`ap4x`,f={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:o,hasAlphaChannel:d},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=to(du.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Gt[e.samplingFrequencyIndex],r=Kt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Xt({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),o=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let s={muxer:this,track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&P.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:t},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ri(t),n(t),n(t.config);let i={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */ new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...sn(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=hn(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=to(du.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=Gr(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=$(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Gr(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let r=/* @__PURE__ */ new Set([]);for(let i of e.cueQueue)n(i.timestamp<=t),n(e.lastCueEndTimestamp<=i.timestamp+i.duration),r.add(Math.max(i.timestamp,e.lastCueEndTimestamp)),r.add(i.timestamp+i.duration);let i=[...r].sort((e,t)=>e-t),a=i[0],o=i[1]??a;if(t<o)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);let t=mf();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=o)break;Hu.lastIndex=0;let r=Hu.test(n.text),i=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&o<i&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=gf(n.notes);this.auxBoxWriter.writeBox(e)}let c=hf(n.text,r?a:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),i===o&&e.cueQueue.splice(t--,1)}let s=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,s,a,o-a,`key`);await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:$(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){n(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=$(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=h(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(r[0],0):e.startTimestampOffset??=r[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let i=e.timestampProcessingQueue[t];i.decodeTimestamp=r[t];let a=$(i.timestamp-i.decodeTimestamp,e.timescale),o=$(i.duration,e.timescale);if(e.lastTimescaleUnits!==null){n(e.lastSample);let t=$(i.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(n(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=h(e.timeToSampleTable);if(n(t),t.sampleCount===1){t.sampleDelta=r;let n=e.timeToSampleTable[e.timeToSampleTable.length-2];n&&n.sampleDelta===r&&(n.sampleCount++,e.timeToSampleTable.pop(),t=n)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===o?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let i=h(e.compositionTimeOffsetTable);n(i),i.sampleCompositionTimeOffset===a?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=$(i.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=i}if(e.timestampProcessingQueue.length=0,n(e.lastSample),n(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){n(t.type===`key`);let r=$(t.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(n(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});n>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=n>=.5}r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),n(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(n(!this.isFragmented),n(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||h(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)n(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(n(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(n(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;n(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=ud(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){n(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new qu(this.writer);let e=this.boxWriter.measureBox(od()),t=this.boxWriter.measureBox(sd(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}n(this.writer),n(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let r=this.nextFragmentNumber++,i=rf(r,t),a=this.writer.getPos(),o=a+this.boxWriter.measureBox(i),s=o+8,c=1/0;for(let e=0;e<t.length;e++){let r=t[e];n(r.currentChunk),n(r.startTimestampOffset!==null),r.currentChunk.offset=s,r.currentChunk.moofOffset=a,r.currentChunk.trafIndex=e,r.currentChunk.startTimestamp-=r.startTimestampOffset;for(let e of r.currentChunk.samples)s+=e.size,e.timestamp-=r.startTimestampOffset,e.decodeTimestamp-=r.startTimestampOffset;c=Math.min(c,r.currentChunk.startTimestamp)}let l=s-o,u=l>=2**32;if(u)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let d=rf(r,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,c)}n(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=cd(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(u?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){n(this.writer),n(this.boxWriter),this.ensureOneEnabledTrack();let e=ud(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;n(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=cd(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){n(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let r=t.track.metadata.maximumPacketCount;n(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){n(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=qf(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(n(this.writer),n(this.boxWriter),this.fastStart===`in-memory`){this.mdat=cd(!1);let e;for(let t=0;t<2;t++){let t=ud(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let i=this.writer.getPos()+r+e;for(let t of this.finalizedChunks){t.offset=i;for(let{data:r}of t.samples)n(r),i+=r.byteLength,e+=r.byteLength}if(i<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=ud(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)n(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(od()),this.boxWriter.writeBox(sd(this,e))}else{let e=this.writer.getPos(),t=df(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{n(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);n(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let r=ud(this);if(this.fastStart===`reserve`){n(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(ld(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}};
|
|
448
448
|
/*!
|
|
449
449
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
450
450
|
*
|
|
@@ -452,7 +452,7 @@ const Wf=57600,Gf=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.nam
|
|
|
452
452
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
453
453
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
454
454
|
*/
|
|
455
|
-
const Jf=-(2**15),Yf=2**15-1,Xf={video:1,audio:2,subtitle:17};var Zf=class extends Fu{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=D(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */ new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new fa(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:L.EBML,data:[{id:L.EBMLVersion,data:1},{id:L.EBMLReadVersion,data:1},{id:L.EBMLMaxIDLength,data:4},{id:L.EBMLMaxSizeLength,data:8},{id:L.DocType,data:this.format instanceof Zp?`webm`:`matroska`},{id:L.DocTypeVersion,data:4},{id:L.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),i=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:L.SeekHead,data:[{id:L.Seek,data:[{id:L.SeekID,data:n},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:L.Seek,data:[{id:L.SeekID,data:r},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:L.Seek,data:[{id:L.SeekID,data:i},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:L.Seek,data:[{id:L.SeekID,data:a},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:L.Seek,data:[{id:L.SeekID,data:t},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=o}createSegmentInfo(){let e={id:L.Duration,data:new na(0)};this.segmentDuration=e;let t={id:L.Info,data:[{id:L.TimestampScale,data:1e6},{id:L.MuxingApp,data:an},{id:L.WritingApp,data:an},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){let e={id:L.Tracks,data:[]};this.tracksElement=e;for(let t of this.trackDatas){let r=wa[t.track.source._codec];n(r),t.type===`audio`&&t.track.source._codec===`dts`&&(t.info.decoderConfig.codec===`dtse`?r=`A_DTS/EXPRESS`:t.info.decoderConfig.codec===`dtsl`&&(r=`A_DTS/LOSSLESS`));let i=0;if(t.type===`audio`&&t.track.source._codec===`opus`){i=8e7;let e=t.info.decoderConfig.description;if(e){let t=S(e),n=qn(t);i=Math.round(1e9*(n.preSkip/Ur))}}e.data.push({id:L.TrackEntry,data:[{id:L.TrackNumber,data:t.track.id},{id:L.TrackUID,data:t.track.id},{id:L.TrackType,data:Xf[t.type]},t.track.metadata.disposition?.default===!1?{id:L.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:L.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:L.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:L.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:L.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:L.FlagCommentary,data:1}:null,{id:L.FlagLacing,data:0},{id:L.Language,data:t.track.metadata.languageCode??`und`},{id:L.CodecID,data:r},t.codecPrivate?{id:L.CodecPrivate,data:S(t.codecPrivate)}:null,i>0?{id:L.SeekPreRoll,data:i}:null,t.track.metadata.name===void 0?null:{id:L.Name,data:new ia(t.track.metadata.name)},t.type===`video`?this.videoSpecificTrackInfo(t):null,t.type===`audio`?this.audioSpecificTrackInfo(t):null,t.type===`subtitle`?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,transformationMatrix:n}=e.track.metadata,r=[t?{id:L.DefaultDuration,data:1e9/t}:null],o,s,l;if(n){o=c(n);let e=p(u(-o),n);s=Math.sign(e[0]),l=Math.sign(e[4]),l===-1&&(l=1,s=-s,o=a(o+180))}else o=e.track.metadata.rotation??0,s=e.track.metadata.flip?-1:1,l=1;let d=o?a(s===-1?o:-o):0,f=Math.round(Math.acos(s)*i),m=Math.round(Math.acos(l)*i),h=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,g=e.info.decoderConfig.colorSpace,_={id:L.Video,data:[{id:L.PixelWidth,data:e.info.width},{id:L.PixelHeight,data:e.info.height},h?{id:L.DisplayWidth,data:e.info.aspectRatio.num}:null,h?{id:L.DisplayHeight,data:e.info.aspectRatio.den}:null,h?{id:L.DisplayUnit,data:3}:null,e.info.alphaMode?{id:L.AlphaMode,data:1}:null,de(g)?null:{id:L.Colour,data:[{id:L.MatrixCoefficients,data:g?.matrix==null?2:ce[g.matrix]},{id:L.TransferCharacteristics,data:g?.transfer==null?2:oe[g.transfer]},{id:L.Primaries,data:g?.primaries==null?2:ie[g.primaries]},{id:L.Range,data:g?.fullRange==null?0:g.fullRange?2:1}]},d||f||m?{id:L.Projection,data:[{id:L.ProjectionType,data:0},f?{id:L.ProjectionPoseYaw,data:new ta(f)}:null,m?{id:L.ProjectionPosePitch,data:new ta(m)}:null,d?{id:L.ProjectionPoseRoll,data:new ta((d+180)%360-180)}:null]}:null]};return r.push(_),r}audioSpecificTrackInfo(e){let t=P.includes(e.track.source._codec)?Gr(e.track.source._codec):null;return[{id:L.Audio,data:[{id:L.SamplingFrequency,data:new ta(e.info.sampleRate)},{id:L.Channels,data:e.info.numberOfChannels},t?{id:L.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],t=(t,n)=>{e.push({id:L.SimpleTag,data:[{id:L.TagName,data:new ia(t)},typeof n==`string`?{id:L.TagString,data:new ia(n)}:{id:L.TagBinary,data:n}]})},n=this.output._metadataTags,r=/* @__PURE__ */ new Set;for(let{key:e,value:i}of lt(n))switch(e){case`title`:t(`TITLE`,i),r.add(`TITLE`);break;case`description`:t(`DESCRIPTION`,i),r.add(`DESCRIPTION`);break;case`artist`:t(`ARTIST`,i),r.add(`ARTIST`);break;case`album`:t(`ALBUM`,i),r.add(`ALBUM`);break;case`albumArtist`:t(`ALBUM_ARTIST`,i),r.add(`ALBUM_ARTIST`);break;case`genre`:t(`GENRE`,i),r.add(`GENRE`);break;case`beatsPerMinute`:t(`BPM`,i.toString()),r.add(`BPM`);break;case`comment`:t(`COMMENT`,i),r.add(`COMMENT`);break;case`lyrics`:t(`LYRICS`,i),r.add(`LYRICS`);break;case`date`:t(`DATE`,i.toISOString().slice(0,10)),r.add(`DATE`);break;case`trackNumber`:t(`PART_NUMBER`,n.tracksTotal===void 0?i.toString():`${i}/${n.tracksTotal}`),r.add(`PART_NUMBER`);break;case`discNumber`:t(`DISC`,n.discsTotal===void 0?i.toString():`${i}/${n.discsTotal}`),r.add(`DISC`);break;case`tracksTotal`:case`discsTotal`:break;case`images`:case`raw`:break;default:Ee(e)}if(n.raw)for(let e in n.raw){let i=n.raw[e];i==null||r.has(e)||(typeof i==`string`||i instanceof Uint8Array)&&t(e,i)}e.length!==0&&(this.tagsElement={id:L.Tags,data:[{id:L.Tag,data:[{id:L.Targets,data:[{id:L.TargetTypeValue,data:50},{id:L.TargetType,data:`MOVIE`}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],n=/* @__PURE__ */ new Set,r=e.images??[];for(let e of r){let r=e.name;r===void 0&&(r=(e.kind===`coverFront`?`cover`:e.kind===`coverBack`?`back`:`image`)+(ut(e.mimeType)??``));let i;for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(Math.random()*256));if(i!==0n&&!n.has(i))break}n.add(i),t.push({id:L.AttachedFile,data:[e.description===void 0?null:{id:L.FileDescription,data:new ia(e.description)},{id:L.FileName,data:new ia(r)},{id:L.FileMediaType,data:e.mimeType},{id:L.FileData,data:e.data},{id:L.FileUID,data:i}]})}for(let[n,i]of Object.entries(e.raw??{}))i instanceof Bt&&/^\d+$/.test(n)&&(r.find(e=>e.mimeType===i.mimeType&&pt(e.data,i.data))||t.push({id:L.AttachedFile,data:[i.description===void 0?null:{id:L.FileDescription,data:new ia(i.description)},{id:L.FileName,data:new ia(i.name??``)},{id:L.FileMediaType,data:i.mimeType??``},{id:L.FileData,data:i.data},{id:L.FileUID,data:BigInt(n)}]}));t.length!==0&&(this.attachmentsElement={id:L.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:L.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:L.Cues,data:[]}}get segmentDataOffset(){return n(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Ea({isWebM:this.format instanceof Zp,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r.decoderConfig),n(r.decoderConfig.codedWidth!==void 0),n(r.decoderConfig.codedHeight!==void 0);let a=r.decoderConfig.displayAspectWidth,o=r.decoderConfig.displayAspectHeight,s=a===void 0||o===void 0?null:xt({num:a,den:o}),c={track:e,type:`video`,info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:r.decoderConfig,alphaMode:e.metadata.canBeTransparent||(t?!!t.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:r.decoderConfig.description??null,closed:!1};return e.source._codec===`vp9`?c.codecPrivate=new Uint8Array(Ir(c.info.decoderConfig.codec)):e.source._codec===`av1`?c.codecPrivate=new Uint8Array(Lr(c.info.decoderConfig.codec)):e.source._codec===`prores`&&(c.codecPrivate=T.encode(r.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=eo(uu.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Gt[e.samplingFrequencyIndex],r=Kt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Xt({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),o=!0}let s={track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:a.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ri(t),n(t),n(t.config);let i={track:e,type:`subtitle`,info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:T.encode(t.config.description),closed:!1};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n);r.info.alphaMode??=!!t.sideData.alpha;let i=t.data;if(e.source._codec===`prores`){if(i.byteLength<8)throw Error(`ProRes packet too small, expected at least 8 bytes.`);i=i.subarray(8)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=t.timestamp,s=t.duration;e.metadata.frameRate!==void 0&&(o=Le(o,e.metadata.frameRate),s=Le(s,e.metadata.frameRate));let c=r.info.alphaMode?t.sideData.alpha??null:null,l=this.createInternalChunk(i,o,s,t.type,c);e.source._codec===`vp9`&&this.fixVP9ColorSpace(r,l),r.chunkQueue.push(l),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=eo(uu.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=this.createInternalChunk(i,t.timestamp,t.duration,t.type);r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0);let i=t.text,a=Math.round(t.timestamp*1e3);Vu.lastIndex=0,i=i.replace(Vu,e=>{let t=Wu(e.slice(1,-1))-a;return`<${Gu(t)}>`});let o=T.encode(i),s=`${t.settings??``}\n${t.identifier??``}\n${t.notes??``}`,c=this.createInternalChunk(o,t.timestamp,t.duration,`key`,s.trim()?T.encode(s):null);r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.chunkQueue.length===0&&!r.closed)break outer;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<n&&(t=r,n=r.chunkQueue[0].timestamp)}if(!t)break;let r=t.chunkQueue.shift();this.writeBlock(t,r)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!==`key`||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new j(t.data);n.skipBits(2);let r=n.readBits(1),i=(n.readBits(1)<<1)+r;if(i===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;i>=2&&n.skipBits(1);let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];x(t.data,n.pos,n.pos+3,a)}createInternalChunk(e,t,n,r,i=null){return{data:e,type:r,timestamp:t,duration:n,additions:i}}writeBlock(e,t){this.segment||this.createSegment();let r=Math.round(1e3*t.timestamp),i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.chunkQueue[0];return r?r.type===`key`:n.closed}),a=!1;if(!this.currentCluster)a=!0;else{n(this.currentClusterStartMsTimestamp!==null),n(this.currentClusterMaxMsTimestamp!==null);let e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>Yf}a&&this.createNewCluster(r);let o=r-this.currentClusterStartMsTimestamp;if(o<Jf){if(!this.warnedAboutTooNegativeTimestamp){let e=this.format instanceof Zp?`WebM`:`Matroska`;A._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${e}.`),this.warnedAboutTooNegativeTimestamp=!0}return}let s=/* @__PURE__ */ new Uint8Array(4),c=new DataView(s.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,o,!1);let l=Math.round(1e3*t.duration);if(t.additions||e.type===`subtitle`){let n={id:L.BlockGroup,data:[{id:L.Block,data:[s,t.data]},t.type===`delta`?{id:L.ReferenceBlock,data:new ra(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:L.BlockAdditions,data:[{id:L.BlockMore,data:[{id:L.BlockAddID,data:1},{id:L.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:L.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(n)}else{c.setUint8(3,Number(t.type===`key`)<<7);let e={id:L.SimpleBlock,data:[s,t.data]};this.ebmlWriter.writeEBML(e)}this.startTimestamp=Math.min(this.startTimestamp,r),this.endTimestamp=Math.max(this.endTimestamp,r+l),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:L.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:L.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(n(this.currentCluster),!this.format._options.appendOnly){let e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){n(this.currentClusterStartMsTimestamp!==null);let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=/* @__PURE__ */ new Map;for(let[e,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(e);let r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(let[t,i]of r)n(this.cues),this.cues.data.push({id:L.CuePoint,data:[{id:L.CueTime,data:Math.max(0,t)},...i.map(t=>({id:L.CueTrackPositions,data:[{id:L.CueTrack,data:t.track.id},{id:L.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),n(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);let t=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new na(t),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),n(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}},Qf=class{constructor(e){
|
|
455
|
+
const Yf=-(2**15),Xf=2**15-1,Zf={video:1,audio:2,subtitle:17};var Qf=class extends Iu{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=D(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */ new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new pa(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:L.EBML,data:[{id:L.EBMLVersion,data:1},{id:L.EBMLReadVersion,data:1},{id:L.EBMLMaxIDLength,data:4},{id:L.EBMLMaxSizeLength,data:8},{id:L.DocType,data:this.format instanceof em?`webm`:`matroska`},{id:L.DocTypeVersion,data:4},{id:L.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),i=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:L.SeekHead,data:[{id:L.Seek,data:[{id:L.SeekID,data:n},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:L.Seek,data:[{id:L.SeekID,data:r},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:L.Seek,data:[{id:L.SeekID,data:i},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:L.Seek,data:[{id:L.SeekID,data:a},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:L.Seek,data:[{id:L.SeekID,data:t},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=o}createSegmentInfo(){let e={id:L.Duration,data:new ra(0)};this.segmentDuration=e;let t={id:L.Info,data:[{id:L.TimestampScale,data:1e6},{id:L.MuxingApp,data:an},{id:L.WritingApp,data:an},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){let e={id:L.Tracks,data:[]};this.tracksElement=e;for(let t of this.trackDatas){let r=Ta[t.track.source._codec];n(r),t.type===`audio`&&t.track.source._codec===`dts`&&(t.info.decoderConfig.codec===`dtse`?r=`A_DTS/EXPRESS`:t.info.decoderConfig.codec===`dtsl`&&(r=`A_DTS/LOSSLESS`));let i=0;if(t.type===`audio`&&t.track.source._codec===`opus`){i=8e7;let e=t.info.decoderConfig.description;if(e){let t=S(e),n=qn(t);i=Math.round(1e9*(n.preSkip/Ur))}}e.data.push({id:L.TrackEntry,data:[{id:L.TrackNumber,data:t.track.id},{id:L.TrackUID,data:t.track.id},{id:L.TrackType,data:Zf[t.type]},t.track.metadata.disposition?.default===!1?{id:L.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:L.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:L.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:L.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:L.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:L.FlagCommentary,data:1}:null,{id:L.FlagLacing,data:0},{id:L.Language,data:t.track.metadata.languageCode??`und`},{id:L.CodecID,data:r},t.codecPrivate?{id:L.CodecPrivate,data:S(t.codecPrivate)}:null,i>0?{id:L.SeekPreRoll,data:i}:null,t.track.metadata.name===void 0?null:{id:L.Name,data:new aa(t.track.metadata.name)},t.type===`video`?this.videoSpecificTrackInfo(t):null,t.type===`audio`?this.audioSpecificTrackInfo(t):null,t.type===`subtitle`?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,transformationMatrix:n}=e.track.metadata,r=[t?{id:L.DefaultDuration,data:1e9/t}:null],o,s,l;if(n){o=c(n);let e=p(u(-o),n);s=Math.sign(e[0]),l=Math.sign(e[4]),l===-1&&(l=1,s=-s,o=a(o+180))}else o=e.track.metadata.rotation??0,s=e.track.metadata.flip?-1:1,l=1;let d=o?a(s===-1?o:-o):0,f=Math.round(Math.acos(s)*i),m=Math.round(Math.acos(l)*i),h=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,g=e.info.decoderConfig.colorSpace,_={id:L.Video,data:[{id:L.PixelWidth,data:e.info.width},{id:L.PixelHeight,data:e.info.height},h?{id:L.DisplayWidth,data:e.info.aspectRatio.num}:null,h?{id:L.DisplayHeight,data:e.info.aspectRatio.den}:null,h?{id:L.DisplayUnit,data:3}:null,e.info.alphaMode?{id:L.AlphaMode,data:1}:null,de(g)?null:{id:L.Colour,data:[{id:L.MatrixCoefficients,data:g?.matrix==null?2:ce[g.matrix]},{id:L.TransferCharacteristics,data:g?.transfer==null?2:oe[g.transfer]},{id:L.Primaries,data:g?.primaries==null?2:ie[g.primaries]},{id:L.Range,data:g?.fullRange==null?0:g.fullRange?2:1}]},d||f||m?{id:L.Projection,data:[{id:L.ProjectionType,data:0},f?{id:L.ProjectionPoseYaw,data:new na(f)}:null,m?{id:L.ProjectionPosePitch,data:new na(m)}:null,d?{id:L.ProjectionPoseRoll,data:new na((d+180)%360-180)}:null]}:null]};return r.push(_),r}audioSpecificTrackInfo(e){let t=P.includes(e.track.source._codec)?Gr(e.track.source._codec):null;return[{id:L.Audio,data:[{id:L.SamplingFrequency,data:new na(e.info.sampleRate)},{id:L.Channels,data:e.info.numberOfChannels},t?{id:L.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],t=(t,n)=>{e.push({id:L.SimpleTag,data:[{id:L.TagName,data:new aa(t)},typeof n==`string`?{id:L.TagString,data:new aa(n)}:{id:L.TagBinary,data:n}]})},n=this.output._metadataTags,r=/* @__PURE__ */ new Set;for(let{key:e,value:i}of lt(n))switch(e){case`title`:t(`TITLE`,i),r.add(`TITLE`);break;case`description`:t(`DESCRIPTION`,i),r.add(`DESCRIPTION`);break;case`artist`:t(`ARTIST`,i),r.add(`ARTIST`);break;case`album`:t(`ALBUM`,i),r.add(`ALBUM`);break;case`albumArtist`:t(`ALBUM_ARTIST`,i),r.add(`ALBUM_ARTIST`);break;case`genre`:t(`GENRE`,i),r.add(`GENRE`);break;case`beatsPerMinute`:t(`BPM`,i.toString()),r.add(`BPM`);break;case`comment`:t(`COMMENT`,i),r.add(`COMMENT`);break;case`lyrics`:t(`LYRICS`,i),r.add(`LYRICS`);break;case`date`:t(`DATE`,i.toISOString().slice(0,10)),r.add(`DATE`);break;case`trackNumber`:t(`PART_NUMBER`,n.tracksTotal===void 0?i.toString():`${i}/${n.tracksTotal}`),r.add(`PART_NUMBER`);break;case`discNumber`:t(`DISC`,n.discsTotal===void 0?i.toString():`${i}/${n.discsTotal}`),r.add(`DISC`);break;case`tracksTotal`:case`discsTotal`:break;case`images`:case`raw`:break;default:Ee(e)}if(n.raw)for(let e in n.raw){let i=n.raw[e];i==null||r.has(e)||(typeof i==`string`||i instanceof Uint8Array)&&t(e,i)}e.length!==0&&(this.tagsElement={id:L.Tags,data:[{id:L.Tag,data:[{id:L.Targets,data:[{id:L.TargetTypeValue,data:50},{id:L.TargetType,data:`MOVIE`}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],n=/* @__PURE__ */ new Set,r=e.images??[];for(let e of r){let r=e.name;r===void 0&&(r=(e.kind===`coverFront`?`cover`:e.kind===`coverBack`?`back`:`image`)+(ut(e.mimeType)??``));let i;for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(Math.random()*256));if(i!==0n&&!n.has(i))break}n.add(i),t.push({id:L.AttachedFile,data:[e.description===void 0?null:{id:L.FileDescription,data:new aa(e.description)},{id:L.FileName,data:new aa(r)},{id:L.FileMediaType,data:e.mimeType},{id:L.FileData,data:e.data},{id:L.FileUID,data:i}]})}for(let[n,i]of Object.entries(e.raw??{}))i instanceof Bt&&/^\d+$/.test(n)&&(r.find(e=>e.mimeType===i.mimeType&&pt(e.data,i.data))||t.push({id:L.AttachedFile,data:[i.description===void 0?null:{id:L.FileDescription,data:new aa(i.description)},{id:L.FileName,data:new aa(i.name??``)},{id:L.FileMediaType,data:i.mimeType??``},{id:L.FileData,data:i.data},{id:L.FileUID,data:BigInt(n)}]}));t.length!==0&&(this.attachmentsElement={id:L.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:L.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:L.Cues,data:[]}}get segmentDataOffset(){return n(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Da({isWebM:this.format instanceof em,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r.decoderConfig),n(r.decoderConfig.codedWidth!==void 0),n(r.decoderConfig.codedHeight!==void 0);let a=r.decoderConfig.displayAspectWidth,o=r.decoderConfig.displayAspectHeight,s=a===void 0||o===void 0?null:xt({num:a,den:o}),c={track:e,type:`video`,info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:r.decoderConfig,alphaMode:e.metadata.canBeTransparent||(t?!!t.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:r.decoderConfig.description??null,closed:!1};return e.source._codec===`vp9`?c.codecPrivate=new Uint8Array(Ir(c.info.decoderConfig.codec)):e.source._codec===`av1`?c.codecPrivate=new Uint8Array(Lr(c.info.decoderConfig.codec)):e.source._codec===`prores`&&(c.codecPrivate=T.encode(r.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=to(du.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Gt[e.samplingFrequencyIndex],r=Kt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Xt({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),o=!0}let s={track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:a.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ri(t),n(t),n(t.config);let i={track:e,type:`subtitle`,info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:T.encode(t.config.description),closed:!1};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n);r.info.alphaMode??=!!t.sideData.alpha;let i=t.data;if(e.source._codec===`prores`){if(i.byteLength<8)throw Error(`ProRes packet too small, expected at least 8 bytes.`);i=i.subarray(8)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=t.timestamp,s=t.duration;e.metadata.frameRate!==void 0&&(o=Le(o,e.metadata.frameRate),s=Le(s,e.metadata.frameRate));let c=r.info.alphaMode?t.sideData.alpha??null:null,l=this.createInternalChunk(i,o,s,t.type,c);e.source._codec===`vp9`&&this.fixVP9ColorSpace(r,l),r.chunkQueue.push(l),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=to(du.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=this.createInternalChunk(i,t.timestamp,t.duration,t.type);r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0);let i=t.text,a=Math.round(t.timestamp*1e3);Hu.lastIndex=0,i=i.replace(Hu,e=>{let t=Gu(e.slice(1,-1))-a;return`<${Ku(t)}>`});let o=T.encode(i),s=`${t.settings??``}\n${t.identifier??``}\n${t.notes??``}`,c=this.createInternalChunk(o,t.timestamp,t.duration,`key`,s.trim()?T.encode(s):null);r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.chunkQueue.length===0&&!r.closed)break outer;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<n&&(t=r,n=r.chunkQueue[0].timestamp)}if(!t)break;let r=t.chunkQueue.shift();this.writeBlock(t,r)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!==`key`||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new j(t.data);n.skipBits(2);let r=n.readBits(1),i=(n.readBits(1)<<1)+r;if(i===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;i>=2&&n.skipBits(1);let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];x(t.data,n.pos,n.pos+3,a)}createInternalChunk(e,t,n,r,i=null){return{data:e,type:r,timestamp:t,duration:n,additions:i}}writeBlock(e,t){this.segment||this.createSegment();let r=Math.round(1e3*t.timestamp),i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.chunkQueue[0];return r?r.type===`key`:n.closed}),a=!1;if(!this.currentCluster)a=!0;else{n(this.currentClusterStartMsTimestamp!==null),n(this.currentClusterMaxMsTimestamp!==null);let e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>Xf}a&&this.createNewCluster(r);let o=r-this.currentClusterStartMsTimestamp;if(o<Yf){if(!this.warnedAboutTooNegativeTimestamp){let e=this.format instanceof em?`WebM`:`Matroska`;A._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${e}.`),this.warnedAboutTooNegativeTimestamp=!0}return}let s=/* @__PURE__ */ new Uint8Array(4),c=new DataView(s.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,o,!1);let l=Math.round(1e3*t.duration);if(t.additions||e.type===`subtitle`){let n={id:L.BlockGroup,data:[{id:L.Block,data:[s,t.data]},t.type===`delta`?{id:L.ReferenceBlock,data:new ia(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:L.BlockAdditions,data:[{id:L.BlockMore,data:[{id:L.BlockAddID,data:1},{id:L.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:L.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(n)}else{c.setUint8(3,Number(t.type===`key`)<<7);let e={id:L.SimpleBlock,data:[s,t.data]};this.ebmlWriter.writeEBML(e)}this.startTimestamp=Math.min(this.startTimestamp,r),this.endTimestamp=Math.max(this.endTimestamp,r+l),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:L.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:L.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(n(this.currentCluster),!this.format._options.appendOnly){let e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){n(this.currentClusterStartMsTimestamp!==null);let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=/* @__PURE__ */ new Map;for(let[e,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(e);let r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(let[t,i]of r)n(this.cues),this.cues.data.push({id:L.CuePoint,data:[{id:L.CueTime,data:Math.max(0,t)},...i.map(t=>({id:L.CueTrackPositions,data:[{id:L.CueTrack,data:t.track.id},{id:L.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),n(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);let t=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new ra(t),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),n(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}},$f=class{constructor(e){
|
|
456
456
|
/*!
|
|
457
457
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
458
458
|
*
|
|
@@ -460,7 +460,7 @@ const Jf=-(2**15),Yf=2**15-1,Xf={video:1,audio:2,subtitle:17};var Zf=class exten
|
|
|
460
460
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
461
461
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
462
462
|
*/
|
|
463
|
-
this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),n=224|e.mpegVersionId<<3|e.layer<<1,r;r=e.mpegVersionId&2&&e.mpegVersionId&1?0:1;let i=-1,a=r*16*4+e.layer*16;for(let t=0;t<16;t++){let n=ai[a+t];if(oi(r,e.layer,1e3*n,e.sampleRate,0)>=155){i=t;break}}if(i===-1)throw Error(`No suitable bitrate found.`);let o=i<<4|e.frequencyIndex<<2|0,s=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=255,this.helper[1]=n,this.helper[2]=o,this.helper[3]=s,this.writer.write(this.helper.subarray(0,4));let c=ci(e.mpegVersionId,e.channel);this.writer.seek(t+c),this.writeU32(1483304551);let l=0;e.frameCount!==null&&(l|=fi.FrameCount),e.fileSize!==null&&(l|=fi.FileSize),e.toc!==null&&(l|=fi.Toc),this.writeU32(l),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??/* @__PURE__ */ new Uint8Array(100));let u=ai[a+i],d=oi(r,e.layer,1e3*u,e.sampleRate,0);this.writer.write(new Uint8Array(t+d-this.writer.getPos()))}}
|
|
463
|
+
this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),n=224|e.mpegVersionId<<3|e.layer<<1,r;r=e.mpegVersionId&2&&e.mpegVersionId&1?0:1;let i=-1,a=r*16*4+e.layer*16;for(let t=0;t<16;t++){let n=ai[a+t];if(oi(r,e.layer,1e3*n,e.sampleRate,0)>=155){i=t;break}}if(i===-1)throw Error(`No suitable bitrate found.`);let o=i<<4|e.frequencyIndex<<2|0,s=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=255,this.helper[1]=n,this.helper[2]=o,this.helper[3]=s,this.writer.write(this.helper.subarray(0,4));let c=ci(e.mpegVersionId,e.channel);this.writer.seek(t+c),this.writeU32(1483304551);let l=0;e.frameCount!==null&&(l|=fi.FrameCount),e.fileSize!==null&&(l|=fi.FileSize),e.toc!==null&&(l|=fi.Toc),this.writeU32(l),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??/* @__PURE__ */ new Uint8Array(100));let u=ai[a+i],d=oi(r,e.layer,1e3*u,e.sampleRate,0);this.writer.write(new Uint8Array(t+d-this.writer.getPos()))}},ep=class extends Iu{constructor(e,t){
|
|
464
464
|
/*!
|
|
465
465
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
466
466
|
*
|
|
@@ -468,7 +468,7 @@ this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new
|
|
|
468
468
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
469
469
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
470
470
|
*/
|
|
471
|
-
super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writeXingHeader=t._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new
|
|
471
|
+
super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writeXingHeader=t._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new $f(this.writer),Ht(this.output._metadataTags)||new Fu(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return`audio/mpeg`}async addEncodedVideoPacket(){throw Error(`MP3 does not support video.`)}async addEncodedAudioPacket(e,t){let n=await this.mutex.acquire();try{if(!this.xingFrameData&&this.writeXingHeader){let e=C(t.data);if(e.byteLength<4)throw Error(`Invalid MP3 header in sample.`);let n=e.getUint32(0,!1),r=li(n,null).header;if(!r)throw Error(`Invalid MP3 header in sample.`);let i=ci(r.mpegVersionId,r.channel);if(e.byteLength>=i+4){let t=e.getUint32(i,!1);if(t===1483304551||t===1231971951)return}this.xingFrameData={mpegVersionId:r.mpegVersionId,layer:r.layer,frequencyIndex:r.frequencyIndex,sampleRate:r.sampleRate,channel:r.channel,modeExtension:r.modeExtension,copyright:r.copyright,original:r.original,emphasis:r.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,t.type===`key`),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw Error(`MP3 does not support subtitles.`)}async finalize(){let e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw Error(`Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.`);let e=this.output.tracks[0];n(e?.isAudioTrack());let t=e.metadata.primingPacket;if(t){let e=C(t.data);if(e.byteLength<4)throw Error(`Invalid MP3 header in priming packet.`);let n=e.getUint32(0,!1),r=li(n,null).header;if(!r)throw Error(`Invalid MP3 header in priming packet.`);this.xingFrameData={mpegVersionId:r.mpegVersionId,layer:r.layer,frequencyIndex:r.frequencyIndex,sampleRate:r.sampleRate,channel:r.channel,modeExtension:r.modeExtension,copyright:r.copyright,original:r.original,emphasis:r.emphasis,frameCount:null,fileSize:null,toc:null}}else if(e.metadata.decoderConfig){let{sampleRate:t,numberOfChannels:n}=e.metadata.decoderConfig,r=[3,2,0],i=null,a=-1;for(let e=0;e<r.length;e++)if(a=ii.indexOf(t<<e),a!==-1){i=r[e];break}if(i===null)throw Error(`${t} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:i,layer:1,frequencyIndex:a,sampleRate:t,channel:n===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,frameCount:null,fileSize:null,toc:null}}else throw Error(`Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.`);this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}if(this.writeXingHeader){n(this.xingFrameData),n(this.xingFramePos!==null);let e=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){let t=/* @__PURE__ */ new Uint8Array(100);for(let n=0;n<100;n++){let r=Math.floor(this.framePositions.length*(n/100)),i=this.framePositions[r]-this.xingFramePos;t[n]=i/e*256}this.xingFrameData.toc=t}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=e,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(e,t)}}e()}},tp=class extends Iu{constructor(e,t){
|
|
472
472
|
/*!
|
|
473
473
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
474
474
|
*
|
|
@@ -476,7 +476,7 @@ super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.x
|
|
|
476
476
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
477
477
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
478
478
|
*/
|
|
479
|
-
super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=D(),this.pageBytes=new Uint8Array(
|
|
479
|
+
super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=D(),this.pageBytes=new Uint8Array(Wa),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0);for(let e of this.output.tracks)n(e.isAudioTrack()),e.metadata.decoderConfig&&this.getTrackData(e,{decoderConfig:e.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,Ua({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw Error(`Video tracks are not supported.`)}getTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;let i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(e=>e.serialNumber===i));n(e.source._codec===`vorbis`||e.source._codec===`opus`),ni(t,e.source._codec),n(t),n(t.decoderConfig);let a={track:e,serialNumber:i,internalSampleRate:e.source._codec===`opus`?Ur:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startTimestampInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(a,t),this.trackDatas.push(a),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}queueHeaderPackets(e,t){if(n(t.decoderConfig),e.track.source._codec===`vorbis`){n(t.decoderConfig.description);let r=S(t.decoderConfig.description);if(r[0]!==2)throw TypeError(`First byte of Vorbis decoder description must be 2.`);let i=1,a=()=>{let e=0;for(;;){let t=r[i++];if(t===void 0)throw TypeError(`Vorbis decoder description is too short.`);if(e+=t,t<255)return e}},o=a(),s=a();if(r.length-i<=0)throw TypeError(`Vorbis decoder description is too short.`);let c=r.subarray(i,i+=o);i+=s;let l=r.subarray(i),u=/* @__PURE__ */ new Uint8Array(7);u[0]=3,u[1]=118,u[2]=111,u[3]=114,u[4]=98,u[5]=105,u[6]=115;let d=er(u,this.output._metadataTags,!0);e.packetQueue.push({data:c,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:l,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});let f=C(c).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Xn(l).modeBlockflags}}else if(e.track.source._codec===`opus`){if(!t.decoderConfig.description)throw TypeError(`For Ogg, Opus decoder description is required.`);let n=S(t.decoderConfig.description),r=/* @__PURE__ */ new Uint8Array(8),i=C(r);i.setUint32(0,1332770163,!1),i.setUint32(4,1415669619,!1);let a=er(r,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:qn(n).preSkip}}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getTrackData(e,n);if(this.validateTimestamp(r.track,t.timestamp,t.type===`key`),r.startTimestampInSamples===null){let e=Math.round(t.timestamp*r.internalSampleRate),n=r.codecInfo.opusInfo?.preSkip??0;r.startTimestampInSamples=e>0?e+n:0,r.currentTimestampInSamples=r.startTimestampInSamples}let i=r.currentTimestampInSamples,{durationInSamples:a,vorbisBlockSize:o}=Ha(t.data,r.codecInfo,r.vorbisLastBlocksize);r.currentTimestampInSamples+=a,r.vorbisLastBlocksize=o;let s=t.duration>0?O(Math.round(t.duration*r.internalSampleRate),0,a):a,c=r.startTimestampInSamples>0&&r.audioPacketCount===1;r.audioPacketCount++,r.packetQueue.push({data:t.data,timestampInSamples:i,durationInSamples:a,trimmedDurationInSamples:s,forcePageFlush:c}),await this.interleavePages()}finally{r()}}addSubtitleCue(){throw Error(`Subtitle tracks are not supported.`)}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let e of this.trackDatas)for(;e.packetQueue.length>0;){let t=e.packetQueue.shift();if(this.writePacket(e,t,!1),t.forcePageFlush)break}this.bosPagesWritten=!0}outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length<=1&&!r.closed)break outer;r.packetQueue.length>0&&r.packetQueue[0].timestampInSamples<n&&(t=r,n=r.packetQueue[0].timestampInSamples)}if(!t)break;let r=t.packetQueue.shift(),i=t.packetQueue.length===0;this.writePacket(t,r,i)}e||await this.writer.flush()}writePacket(e,t,n){let r=t.timestampInSamples+(n?t.trimmedDurationInSamples:t.durationInSamples);if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=t.timestampInSamples),this.format._options.maximumPageDuration!==void 0){let t=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&r-e.currentPageStartTimestampInSamples>t&&this.writePage(e,!1)}let i=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);let r=Math.min(255,i);e.currentLacingValues.push(r),e.currentPageSize++,o+=r;let s=i<255;if(e.currentLacingValues.length===255){let r=t.data.subarray(a,o);if(a=o,e.currentPageData.push(r),e.currentPageSize+=r.length,this.writePage(e,n&&s),s)return}if(s)break;i-=255}let s=t.data.subarray(a);e.currentPageData.push(s),e.currentPageSize+=s.length,e.currentGranulePosition=r,(e.currentPageSize>=8192||t.forcePageFlush)&&this.writePage(e,n)}writePage(e,t){this.pageView.setUint32(0,1399285583,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),t&&(n|=4),this.pageView.setUint8(5,n);let r=e.currentLacingValues.every(e=>e===255)?-1:e.currentGranulePosition;je(this.pageView,6,r,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let i=27+e.currentLacingValues.length;for(let t of e.currentPageData)this.pageBytes.set(t,i),i+=t.length;let a=this.pageBytes.subarray(0,i),o=Va(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){let{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onPage(t,n,e.track.source)}}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0;await this.interleavePages(!0);for(let e of this.trackDatas)e.currentLacingValues.length>0&&this.writePage(e,!0);e()}};
|
|
480
480
|
/*!
|
|
481
481
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
482
482
|
*
|
|
@@ -484,7 +484,7 @@ super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=D(),this
|
|
|
484
484
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
485
485
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
486
486
|
*/
|
|
487
|
-
const
|
|
487
|
+
const np=new Uint8Array([9,240]),rp=new Uint8Array([70,1]);var ip=class extends Iu{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=/* @__PURE__ */ new Map,this.packetBuffer=/* @__PURE__ */ new Uint8Array(188),this.packetView=C(this.packetBuffer),this.allTracksKnown=D(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=/* @__PURE__ */ new Uint8Array(184),this.payloadBuffer=/* @__PURE__ */ new Uint8Array(184),this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,go(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ei(t,e.source._codec),n(t?.decoderConfig);let i=e.source._codec;n(i===`avc`||i===`hevc`);let a=i===`avc`?27:36,o={track:e,pid:256+this.trackDatas.length,streamType:a,streamId:224+this.videoTrackIndex++,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getAudioTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ni(t,e.source._codec),n(t?.decoderConfig);let i=e.source._codec;n(i===`aac`||i===`mp3`||i===`ac3`||i===`eac3`||i===`dts`);let a,o;switch(i){case`aac`:a=15,o=192+this.audioTrackIndex++;break;case`mp3`:a=3,o=192+this.audioTrackIndex++;break;case`ac3`:a=129,o=189;break;case`eac3`:a=135,o=189;break;case`dts`:a=130,o=189}let s={track:e,pid:256+this.trackDatas.length,streamType:a,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let i=this.prepareVideoPacket(r,t,n);t.type===`key`&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:i,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type===`key`})}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let i=this.prepareAudioPacket(r,t,n);t.type===`key`&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:i,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type===`key`})}finally{r()}}async addSubtitleCue(){throw Error(`MPEG-TS does not support subtitles.`)}prepareVideoPacket(e,t,n){let r=e.track.source._codec;if(e.inputIsAnnexB===null){let t=n?.decoderConfig?.description;if(e.inputIsAnnexB=!t,!e.inputIsAnnexB){let n=S(t);r===`avc`?e.avcDecoderConfig=yn(n):e.hevcDecoderConfig=Ln(n)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,r):this.prepareLengthPrefixedVideoPacket(e,t,r)}prepareAnnexBVideoPacket(e,t){let n=[];for(let r of sn(e)){let i=e.subarray(r.offset,r.offset+r.length);(t===`avc`?un(i[0])===on.AUD:En(i[0])===M.AUD_NUT)||n.push(i)}let r=t===`avc`?np:rp;return n.unshift(r),mn(n)}prepareLengthPrefixedVideoPacket(e,t,n){let r=t.data,i=n===`avc`?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(let e of cn(r,i)){let t=r.subarray(e.offset,e.offset+e.length);(n===`avc`?un(t[0])===on.AUD:En(t[0])===M.AUD_NUT)||a.push(t)}if(t.type===`key`){if(n===`avc`){let t=e.avcDecoderConfig;for(let e of t.pictureParameterSets)a.unshift(e);for(let e of t.sequenceParameterSets)a.unshift(e)}else{let t=e.hevcDecoderConfig;for(let e of t.arrays)if(e.nalUnitType===M.PPS_NUT)for(let t of e.nalUnits)a.unshift(t);for(let e of t.arrays)if(e.nalUnitType===M.SPS_NUT)for(let t of e.nalUnits)a.unshift(t);for(let e of t.arrays)if(e.nalUnitType===M.VPS_NUT)for(let t of e.nalUnits)a.unshift(t)}}let o=n===`avc`?np:rp;return a.unshift(o),mn(a)}prepareAudioPacket(e,t,r){let i=e.track.source._codec;if(i===`mp3`||i===`ac3`||i===`eac3`||i===`dts`)return t.data;if(e.inputIsAdts===null){let t=r?.decoderConfig?.description;if(e.inputIsAdts=!t,!e.inputIsAdts){let n=qt(S(t)),r=en(n);e.adtsHeader=r.header,e.adtsHeaderBitstream=r.bitstream}}if(e.inputIsAdts)return t.data;n(e.adtsHeader),n(e.adtsHeaderBitstream);let a=e.adtsHeader,o=t.data.byteLength+a.byteLength;tn(e.adtsHeaderBitstream,o);let s=new Uint8Array(o);return s.set(a,0),s.set(t.data,a.byteLength),s}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(e=>e.presentationTimestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t],e.packetQueue.push(r)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length===0&&!r.closed)break outer;r.packetQueue.length>0&&r.packetQueue[0].presentationTimestamp<n&&(t=r,n=r.packetQueue[0].presentationTimestamp)}if(!t)break;let r=t.packetQueue.shift();this.writePesPacket(t,r)}e||await this.writer.flush()}writeTables(){n(!this.tablesWritten),this.writePsiSection(0,sp),this.writePsiSection(4096,cp(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let n=0,r=!0;for(;n<t.length;){let i=184-!!r,a=t.length-n,o=Math.min(i,a),s;r?(s=this.payloadBuffer.subarray(0,1+o),s[0]=0,s.set(t.subarray(n,n+o),1)):s=t.subarray(n,n+o),this.writeTsPacket(e,r,null,s),n+=o,r=!1}}writePesPacket(e,t){let r=e.track.type===`video`,i=r?10:5,a=new Uint8Array(9+i),o=C(a),s=new j(a.subarray(9));ke(o,0,1,!1),a[3]=e.streamId;let c=e.track.type===`video`?0:Math.min(8+t.data.length,65535);o.setUint16(4,c,!1),o.setUint8(6,132),o.setUint8(7,r?192:128),o.setUint8(8,i);let l=Math.round(t.presentationTimestamp*mo),u=Pe(l,ho);if(s.pos=0,s.writeBits(4,r?3:2),s.writeBits(3,Math.floor(u/2**30)),s.writeBits(1,1),s.writeBits(15,Math.floor(u/2**15)%2**15),s.writeBits(1,1),s.writeBits(15,u%2**15),s.writeBits(1,1),r){n(t.decodeTimestamp!==null);let e=Math.round(t.decodeTimestamp*mo),r=Pe(e,ho);s.writeBits(4,1),s.writeBits(3,Math.floor(r/2**30)),s.writeBits(1,1),s.writeBits(15,Math.floor(r/2**15)%2**15),s.writeBits(1,1),s.writeBits(15,r%2**15),s.writeBits(1,1)}let d=a.length+t.data.length,f=0,p=!0;for(;f<d;){let n=p,r=d-f,i=p&&t.isKeyframe,o=p&&!e.firstPacketWritten,s=Math.max(0,184-r),c;c=i||o?Math.max(2,s):s;let l=null;if(c>0){let e=this.adaptationFieldBuffer;c===1?e[0]=0:(e[0]=c-1,e[1]=Number(o)<<7|Number(i)<<6,e.fill(255,2,c)),l=e.subarray(0,c)}let u=Math.min(184-c,r),m=this.payloadBuffer.subarray(0,u),h=0;if(f<a.length){let e=Math.min(a.length-f,u);m.set(a.subarray(f,f+e),0),h=e}let g=Math.max(0,f-a.length),_=g+(u-h);h<u&&m.set(t.data.subarray(g,_),h),this.writeTsPacket(e.pid,n,l,m),f+=u,p=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,n,r){let i=this.continuityCounters.get(e)??0,a=r.length>0,o=n?a?3:2:+!!a;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|i&15,a&&this.continuityCounters.set(e,i+1&15);let s=4;n&&(this.packetBuffer.set(n,s),s+=n.length),this.packetBuffer.set(r,s),s+=r.length,s<188&&this.packetBuffer.fill(255,s);let c=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),c)}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0,await this.flushTimestampQueue(e,!1);await this.interleavePackets(!0),e()}};const ap=/* @__PURE__ */ 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;ap[e]=t>>>0&4294967295}const op=e=>{let t=4294967295;for(let n=0;n<e.length;n++){let r=e[n];t=(t<<8^ap[t>>>24^r])>>>0}return t},sp=/* @__PURE__ */ new Uint8Array(16);{let e=C(sp);sp[0]=0,e.setUint16(1,45069,!1),e.setUint16(3,1,!1),sp[5]=193,sp[6]=0,sp[7]=0,e.setUint16(8,1,!1),e.setUint16(10,61440,!1),e.setUint32(12,op(sp.subarray(0,12)),!1)}const cp=e=>{let t=0;for(let n of e)t+=5,n.streamType===129?t+=ir.length:n.streamType===135&&(t+=ar.length);let n=9+t+4,r=new Uint8Array(3+n-4),i=C(r);r[0]=2,i.setUint16(1,45056|n&4095,!1),i.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let a=12;for(let t of e)r[a++]=t.streamType,i.setUint16(a,57344|t.pid&8191,!1),a+=2,t.streamType===129?(i.setUint16(a,61440|ir.length,!1),a+=2,r.set(ir,a),a+=ir.length):t.streamType===135?(i.setUint16(a,61440|ar.length,!1),a+=2,r.set(ar,a),a+=ar.length):(i.setUint16(a,61440,!1),a+=2);let o=op(r),s=new Uint8Array(r.length+4);return s.set(r,0),C(s).setUint32(r.length,o,!1),s};
|
|
488
488
|
/*!
|
|
489
489
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
490
490
|
*
|
|
@@ -492,7 +492,7 @@ const tp=new Uint8Array([9,240]),np=new Uint8Array([70,1]);var rp=class extends
|
|
|
492
492
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
493
493
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
494
494
|
*/
|
|
495
|
-
var
|
|
495
|
+
var lp=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(T.encode(e))}},up=class extends Iu{constructor(e,t){
|
|
496
496
|
/*!
|
|
497
497
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
498
498
|
*
|
|
@@ -500,7 +500,7 @@ var cp=class{constructor(e){this.writer=e,this.helper=/* @__PURE__ */ new Uint8A
|
|
|
500
500
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
501
501
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
502
502
|
*/
|
|
503
|
-
super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new
|
|
503
|
+
super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new lp(this.writer);let t=this.output.tracks[0];n(t?.isAudioTrack()),t.metadata.decoderConfig&&(ni({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.writeHeader(t,t.metadata.decoderConfig),this.sampleRate=t.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return`audio/wav`}async addEncodedVideoPacket(){throw Error(`WAVE does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{if(this.headerWritten||=(ni(r,e.source._codec),n(r),n(r.decoderConfig),this.writeHeader(e,r.decoderConfig),this.sampleRate=r.decoderConfig.sampleRate,!0),this.validateTimestamp(e,t.timestamp,t.type===`key`),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw Error(`WAVE does not support subtitles.`)}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,r=e.source._codec,i=Gr(r);n=i.dataType===`ulaw`?Za.MULAW:i.dataType===`alaw`?Za.ALAW:i.dataType===`float`?Za.IEEE_FLOAT:Za.PCM;let a=t.numberOfChannels,o=t.sampleRate,s=i.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?`RF64`:`RIFF`),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii(`WAVE`),this.isRf64&&(this.riffWriter.writeAscii(`ds64`),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii(`fmt `),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*s),this.riffWriter.writeU16(s),this.riffWriter.writeU16(8*i.sampleSize),!Ht(this.output._metadataTags)){let e=this.format._options.metadataFormat??`info`;e===`info`?this.writeInfoChunk(this.output._metadataTags):e===`id3`?this.writeId3Chunk(this.output._metadataTags):Ee(e)}if(this.riffWriter.writeAscii(`data`),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onHeader(e,t)}}writeInfoChunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii(`LIST`),this.riffWriter.writeU32(0),this.riffWriter.writeAscii(`INFO`);let n=/* @__PURE__ */ new Set,r=(e,t)=>{if(!ne(t)){A._warn(`Didn't write tag '${e}' because '${t}' is not ISO 8859-1-compatible.`);return}let r=t.length+1,i=new Uint8Array(r);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);this.riffWriter.writeAscii(e),this.riffWriter.writeU32(r),this.writer.write(i),r&1&&this.writer.write(/* @__PURE__ */ new Uint8Array(1)),n.add(e)};for(let{key:t,value:i}of lt(e))switch(t){case`title`:r(`INAM`,i),n.add(`INAM`);break;case`artist`:r(`IART`,i),n.add(`IART`);break;case`album`:r(`IPRD`,i),n.add(`IPRD`);break;case`trackNumber`:r(`ITRK`,e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`),n.add(`ITRK`);break;case`genre`:r(`IGNR`,i),n.add(`IGNR`);break;case`date`:r(`ICRD`,i.toISOString().slice(0,10)),n.add(`ICRD`);break;case`comment`:r(`ICMT`,i),n.add(`ICMT`);break;case`albumArtist`:case`discNumber`:case`tracksTotal`:case`discsTotal`:case`beatsPerMinute`:case`description`:case`lyrics`:case`images`:break;case`raw`:break;default:Ee(t)}if(e.raw)for(let t in e.raw){let i=e.raw[t];i==null||t.length!==4||n.has(t)||typeof i==`string`&&r(t,i)}let i=this.writer.getPos(),a=i-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(i),a&1&&this.writer.write(/* @__PURE__ */ new Uint8Array(1))}writeId3Chunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii(`ID3 `),this.riffWriter.writeU32(0);let n=new Fu(this.writer).writeId3V2Tag(e),r=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(n),this.writer.seek(r),n&1&&this.writer.write(/* @__PURE__ */ new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire();if(!this.headerWritten)throw Error(`Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.`);let t=this.writer.getPos();this.isRf64?(n(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),n(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),n(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(n(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),n(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}},dp=class{constructor(e){
|
|
504
504
|
/*!
|
|
505
505
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
506
506
|
*
|
|
@@ -508,7 +508,7 @@ super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleC
|
|
|
508
508
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
509
509
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
510
510
|
*/
|
|
511
|
-
this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){n(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>r<2?t[n*e+r]:0:e===4&&t===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;let t=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+t,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}n(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:`f32`}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(i,{planeIndex:0,format:`f32`});let a=e.timestamp-this.startTime,o=a+e.duration,s=Math.floor((a-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let r=t-this.bufferStartFrame;n(r<this.bufferCapacityInFrames);let o=(t/this.targetSampleRate-a)*this.sourceSampleRate,s=Math.floor(o),c=Math.ceil(o),l=o-s;for(let t=0;t<this.targetNumberOfChannels;t++){let n=0,a=0;s>=0&&s<e.numberOfFrames&&(n=this.channelMixer(i,s,t)),c>=0&&c<e.numberOfFrames&&(a=this.channelMixer(i,c,t));let o=n+l*(a-n),u=r*this.targetNumberOfChannels+t;this.outputBuffer[u]+=o}this.maxWrittenFrame=this.maxWrittenFrame===null?r:Math.max(this.maxWrittenFrame,r)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;n(this.startTime!==null);let e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let r=new
|
|
511
|
+
this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){n(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>r<2?t[n*e+r]:0:e===4&&t===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;let t=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+t,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}n(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:`f32`}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(i,{planeIndex:0,format:`f32`});let a=e.timestamp-this.startTime,o=a+e.duration,s=Math.floor((a-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let r=t-this.bufferStartFrame;n(r<this.bufferCapacityInFrames);let o=(t/this.targetSampleRate-a)*this.sourceSampleRate,s=Math.floor(o),c=Math.ceil(o),l=o-s;for(let t=0;t<this.targetNumberOfChannels;t++){let n=0,a=0;s>=0&&s<e.numberOfFrames&&(n=this.channelMixer(i,s,t)),c>=0&&c<e.numberOfFrames&&(a=this.channelMixer(i,c,t));let o=n+l*(a-n),u=r*this.targetNumberOfChannels+t;this.outputBuffer[u]+=o}this.maxWrittenFrame=this.maxWrittenFrame===null?r:Math.max(this.maxWrittenFrame,r)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;n(this.startTime!==null);let e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let r=new Mc({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(r),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}},fp=function(e,t,n){
|
|
512
512
|
/*!
|
|
513
513
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
514
514
|
*
|
|
@@ -516,7 +516,7 @@ this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,
|
|
|
516
516
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
517
517
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
518
518
|
*/
|
|
519
|
-
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},fp=(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}),pp=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},mp=class extends pp{constructor(e){if(super(),!N.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${N.join(`, `)}.`);this._codec=e}};const hp=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)};var gp=class extends mp{constructor(e){super(e)}add(e,t){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),hp(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},_p=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Ye,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,r){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,o=a.sizeChangeBehavior??`deny`,s=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(s=!0,o===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||s&&o!==`passThrough`){let r=a.transform?.width,i=a.transform?.height,c=a.transform?.fit??`fill`;s&&o!==`passThrough`&&(n(this.outputWidth),n(this.outputHeight),n(o!==`deny`),r=this.outputWidth,i=this.outputHeight,c=o);let l=await e.transform({width:r,height:i,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:c,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=l.displayWidth,this.outputHeight=l.displayHeight),t&&e.close(),e=l,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let c=a.transform?.frameRate;if(c!==void 0){let n=e.timestamp+e.duration,a=ze(e.timestamp,c);if(this.frameRateLastSample!==null){if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=n;return}await this.padFrameRate(a,r)}e===i&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/c),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=n}await this.processAndEncode(e,r)}finally{t&&e.close()}}async processAndEncode(e,t){let r=this.encodingConfig,i;if(r.transform?.process){let t=r.transform.process(e);if(k(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let n=[];try{for(let r of t)r instanceof fc?n.push(r):typeof VideoFrame<`u`&&r instanceof VideoFrame?n.push(new fc(r)):n.push(new fc(r,{timestamp:e.timestamp,duration:e.duration}))}catch(r){for(let t of n)t!==e&&t.close();for(let n of t)(n instanceof fc&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw r}i=n}else i=[e];try{for(let e of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let r=this.encodingConfig.keyFrameInterval??2,i=Math.floor(e.timestamp/r),a={...this.defaultEncodeOptions,...e.encodeOptions,...t},o={...a,keyFrame:a.keyFrame===void 0?r===0||i!==this.lastMultipleOfKeyFrameInterval:a.keyFrame};if(this.lastMultipleOfKeyFrameInterval=i,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,o)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{n(this.encoder);let t=e.toVideoFrame(),r=E(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),i=r===-1?null:this.preciseTimings[r];if(i&&i.microsecondTimestamp===t.timestamp?(i.timestamp!==e.timestamp&&(i.timestampIsValid=!1),i.duration!==e.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(r+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)try{this.encoder.encode(t,o)}finally{t.close()}else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(t,o)}finally{t.close()}}else{this.splitter||=new yp;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n);try{this.encoder.encode(e,o)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of i)t!==e&&t.close()}}async padFrameRate(e,t){let r=this.encodingConfig.transform.frameRate;n(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*r);for(let e=1;e<i;e++){let n={stack:[],error:void 0,hasError:!1};try{let i=dp(n,this.frameRateLastSample.clone(),!1);i.setTimestamp(this.frameRateLastTimestamp+e/r),i.setDuration(1/r),await this.processAndEncode(i,t)}catch(e){n.error=e,n.hasError=!0}finally{fp(n)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=sl(this.encodingConfig.quality,this.encodingConfig.bitrate);n(t!==void 0);let r=Wc({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),i=null,a;for(let e of r){let t=e.config;if(this.encodingConfig.onEncoderConfig?.(t),a=Sl.find(e=>e.supports(this.encodingConfig.codec,t)),a){i=e;break}if(typeof VideoEncoder<`u`){if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(t)).supported){i=e;break}}catch{}}}if(!i){if(typeof VideoEncoder>`u`)throw Error(it(`VideoEncoder`));let e=r[0].config,t=r.map(({config:e,quantizer:t})=>t===null?`${e.bitrate} bps`:`quantizer ${t}`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(` / `)}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??`no-preference`}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let o=i.config;i.quantizer===null?this.source._nominalBitrate=o.bitrate??null:this.defaultEncodeOptions=Qc(this.encodingConfig.codec,i.quantizer),a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof I))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);hp(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init()):(this.encoderConfig=o,this.createWebCodecsEncoders()),n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let e=this.encoderConfig;n(e);let t=[],r=[],i=0,a=0,o=(e,t)=>{if(at(e)){this.encodersReclaimed=!0;return}e.stack=t,this.setError(e)},s=(/* @__PURE__ */ Error(`Encoding error`)).stack;if(this.encoder=new VideoEncoder({output:(e,o)=>{if(!this.alphaEncoder){this.addPacket(e,null,o);return}let s=this.alphaFrameQueue.shift();n(s!==void 0),s?(this.alphaEncoder.encode(s,{...this.defaultEncodeOptions,keyFrame:e.type===`key`}),a++,s.close(),t.push({chunk:e,meta:o})):a===0?this.addPacket(e,null,o):(r.push(i+a),t.push({chunk:e,meta:o}))},error:e=>o(e,s)}),this.encoder.configure(e),this.encodingConfig.alpha===`keep`){let s=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.alphaEncoder=new VideoEncoder({output:(e,o)=>{a--;let s=t.shift();for(n(s!==void 0),this.addPacket(s.chunk,e,s.meta),i++;r.length>0&&r[0]===i;){r.shift();let e=t.shift();n(e!==void 0),this.addPacket(e.chunk,null,e.meta)}},error:e=>o(e,s)}),this.alphaEncoder.configure(e)}}addPacket(e,t,r){let i={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}let a=I.fromEncodedChunk(e,i),o=this.encoderConfig;n(o),r?.decoderConfig&&(r.decoderConfig.codec=Rr({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?S(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:o.codec.includes(`avc1.`)?1:o.codec.includes(`avc3.`)?3:null,avcCodecInfo:this.encodingConfig.codec===`avc`&&!r.decoderConfig.description?_n(a.data):null,hevcCodecInfo:this.encodingConfig.codec===`hevc`&&!r.decoderConfig.description?On(a.data):null,vp9CodecInfo:this.encodingConfig.codec===`vp9`?Vn(a.data):null,av1CodecInfo:this.encodingConfig.codec===`av1`?Wn(a.data):null,proresFormat:null}));let s=E(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),c=s===-1?null:this.preciseTimings[s],l=null;this.emittedEncoderPackets===0&&a.type===`delta`&&r?.decoderConfig&&(l=Zn(this.encodingConfig.codec,r.decoderConfig,a.data)),(c&&c.microsecondTimestamp===e.timestamp||l!==null)&&(a=a.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:l??void 0})),hp(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){n(this.encoder),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=ze(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Mt(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}};let vp=null;var yp=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!vp){let e=new Blob([`(${bp.toString()})()`],{type:`application/javascript`});vp=URL.createObjectURL(e)}this.worker=new Worker(vp),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=D();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=/* @__PURE__ */ Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const bp=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,S=a?512:o?2048:128;s===1?y.fill(S,x):new Uint16Array(y.buffer,x,2*_).fill(S);let C=a?`I420P10`:o?`I420P12`:`I420`,ee=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),te={format:C,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[y.buffer]};return{colorFrame:ee,alphaFrame:new VideoFrame(y,te)}}};var xp=class extends mp{constructor(e){Hc(e),super(e.codec),this._encoder=new _p(this,e)}add(e,t){if(!(e instanceof fc))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Sp=class extends mp{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);Hc(t),super(t.codec),this._encoder=new _p(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e))throw TypeError(`timestamp must be a finite number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new fc(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Cp=class extends mp{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`video`)throw TypeError(`track must be a video MediaStreamTrack.`);if(Hc(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.frameRate!=null&&(typeof n.frameRate!=`number`||n.frameRate<=0))throw TypeError(`options.frameRate, when provided, must be either a positive number or null.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);t={...t,latencyMode:`realtime`},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=D(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=n,this._encoder=new _p(this,t),this._track=e}async _start(){this._errorPromiseAccessed||A._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate===void 0?this._track.getSettings().frameRate??null:this._options.frameRate;this._abortController=new AbortController;let t=null,r=null,i=0,a=!1,o=null,s=0,c=()=>{if(n(e!==null),!this._lastVideoFrame)return;n(r!==null),n(t!==null);let a=performance.now();for(;a-r>1e3/e;){r+=1e3/e;let n=t+i/e,o=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*n,duration:1e6/e});u(o,a)}};e!==null&&(this._timerHandle=At(c,4));let l=t=>{if(e===null)u(t);else{let e=performance.now();this._lastVideoFrame?(c(),this._lastVideoFrame?.close(),this._lastVideoFrame=t):(u(t.clone(),e),r=e,this._lastVideoFrame=t)}},u=(e,n=performance.now())=>{if(a){e.close();return}i++;let r=e.timestamp/1e6;if(this._paused){if(t!==null){if(o!==null&&this._options.timestampBase!==`unix`){let e=r-o;s-=e}o=r}e.close();return}if(t===null){t=r;let e,i=this._options.timestampBase??`synced-zero`;if(i===`unix`)e=Date.now()/1e3;else if(i===`zero`)e=0;else{let t=this._connectedTrack.output;t._firstMediaStreamTimestamp===null?(t._firstMediaStreamTimestamp=n/1e3,e=0):e=n/1e3-t._firstMediaStreamTimestamp}s=e-t}if(o=r,this._encoder.getQueueSize()>=8){e.close();return}let c=new fc(e,{timestamp:r+s});this._encoder.add(c,!0).catch(e=>{a=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._workerTrackId!==null&&Ip({type:`stopTrack`,trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:l});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else if(await Fp())this._workerTrackId=jp++,Ip({type:`videoTrack`,trackId:this._workerTrackId,track:this._track}),this._workerListener=e=>{let t=e.data;t.type===`videoFrame`&&t.trackId===this._workerTrackId?l(t.videoFrame):t.type===`error`&&t.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(t.error)},Mp.addEventListener(`message`,this._workerListener);else if(e!==null){let e=document.createElement(`video`);e.style.position=`fixed`,e.style.left=`-10000px`,e.style.top=`-10000px`,e.style.width=`1px`,e.style.height=`1px`,e.style.opacity=`0`,e.style.pointerEvents=`none`,e.muted=!0,e.srcObject=new MediaStream([this._track]),document.body.appendChild(e),this._videoElement=e,e.addEventListener(`loadeddata`,()=>{if(a||!this._videoElement)return;let t=new VideoFrame(e,{timestamp:1e3*performance.now()});l(t),t.close()},{once:!0}),e.play().catch(e=>{a=!0,this._promiseWithResolvers.reject(e)})}else throw Error(`When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.`)}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&=(this._abortController.abort(),null),this._timerHandle&&jt(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&=(this._videoElement.srcObject=null,this._videoElement.remove(),null),this._workerTrackId!==null&&(n(this._workerListener),Ip({type:`stopTrack`,trackId:this._workerTrackId}),await new Promise(e=>{let t=r=>{let i=r.data;i.type===`trackStopped`&&i.trackId===this._workerTrackId&&(n(this._workerListener),Mp.removeEventListener(`message`,this._workerListener),Mp.removeEventListener(`message`,t),e())};Mp.addEventListener(`message`,t)}))}finally{await this._encoder.flushAndClose(e)}}},wp=class extends pp{constructor(e){if(super(),!F.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${F.join(`, `)}.`);this._codec=e}},Tp=class extends wp{constructor(e){super(e)}add(e,t){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Ep=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Ye,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new up({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Lc(e.format)!==n.transform.sampleFormat){let r=zc(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(k(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof jc))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);for(let e of t)await this.encodeSample(e,!0)}finally{for(let e of t)e instanceof jc&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new jc({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{n(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){n(this.outputSampleSize),n(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:i,sampleRate:a,timestamp:o}=e,s=2048,c=[];for(let t=0;t<i;t+=s){let n=Math.min(s,e.numberOfFrames-t),i=n*r*this.outputSampleSize,a=new ArrayBuffer(i),o=new DataView(a);c.push({frameCount:n,view:o})}let l=e.format===`s32`||e.format===`s32-planar`,u=l?`s32-planar`:`f32-planar`,d=l?1/2147483648:1,f=e.allocationSize({planeIndex:0,format:u}),p=l?new Int32Array(f/4):new Float32Array(f/4);for(let t=0;t<r;t++){e.copyTo(p,{planeIndex:t,format:u});for(let e=0;e<c.length;e++){let{frameCount:n,view:i}=c[e];for(let a=0;a<n;a++)this.writeOutputValue(i,(a*r+t)*this.outputSampleSize,p[e*s+a]*d)}}t&&e.close();let m={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let e=0;e<c.length;e++){let{frameCount:t,view:n}=c[e],r=n.buffer,i=e*s,l=new I(new Uint8Array(r),`key`,o+i/a,t/a);this.encodingConfig.onEncodedPacket?.(l,m),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,m)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,i=sl(this.encodingConfig.quality,this.encodingConfig.bitrate),a=qc({numberOfChannels:t,sampleRate:r,...this.encodingConfig,quality:i});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let o=Cl.find(e=>e.supports(this.encodingConfig.codec,a));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof I))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(P.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(it(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let t=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||qt(S(t.decoderConfig.description)).objectType===0,e){let e=Number(h(a.codec.split(`.`)));t.decoderConfig.description=Xt({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=I.fromEncodedChunk(e);n=n.clone({timestamp:Le(n.timestamp,a.sampleRate),duration:e.duration==null?void 0:Le(n.duration,a.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.setError(e)})},error:e=>{e.stack=t,this.setError(e)}}),this.encoder.configure(a)}n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:i}=Gr(e);switch(this.outputSampleSize=r,r){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,O(Math.round(n*128)+128,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,O(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=O(Math.round(n*32768),-32768,32767);e.setUint8(t,El(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=O(Math.round(n*32768),-32768,32767);e.setUint8(t,Ol(r))}:n(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,O(Math.round(n*32768)+32768,0,65535),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,O(Math.round(n*32768),-32768,32767),i):n(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>ke(e,t,O(Math.round(n*8388608)+8388608,0,16777215),i):t===`signed`?this.writeOutputValue=(e,t,n)=>Ae(e,t,O(Math.round(n*8388608),-8388608,8388607),i):n(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,O(Math.round(n*2147483648)+2147483648,0,4294967295),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,O(Math.round(n*2147483648),-2147483648,2147483647),i):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,i):n(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,i):n(!1);break;default:Ee(r),n(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Dp=class extends wp{constructor(e){Gc(e),super(e.codec),this._encoder=new Ep(this,e)}add(e){if(!(e instanceof jc))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Op=class extends wp{constructor(e,t={}){if(Gc(e),typeof t!=`object`||!t)throw TypeError(`options must be an object.`);if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw TypeError(`options.startTimestamp, when provided, must be a finite number.`);super(e.codec),this._encoder=new Ep(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=jc._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},kp=class extends wp{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`audio`)throw TypeError(`track must be an audio MediaStreamTrack.`);if(Gc(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=D(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=n,this._encoder=new Ep(this,t),this._track=e}async _start(){this._errorPromiseAccessed||A._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,n=null,r=0,i=i=>{if(t){i.close();return}let a=i.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!==`unix`){let e=a-n;r-=e}n=a}i.close();return}if(e===null){e=i.timestamp;let t,n=this._options.timestampBase??`synced-zero`;if(n===`unix`)t=Date.now()/1e3;else if(n===`zero`)t=0;else{let e=this._connectedTrack.output;e._firstMediaStreamTimestamp===null?(e._firstMediaStreamTimestamp=performance.now()/1e3,t=0):t=performance.now()/1e3-e._firstMediaStreamTimestamp}r=t-e}if(n=a,this._encoder.getQueueSize()>=8){i.close();return}i.setTimestamp(a+r),this._encoder.add(i,!0).catch(e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:e=>i(new jc(e))});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else{let e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});let t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state===`suspended`&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let n=0;this._scriptProcessorNode.onaudioprocess=e=>{let t=jc._fromAudioBuffer(e.inputBuffer,n);n+=e.inputBuffer.duration;for(let e of t)i(e)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&=(this._abortController.abort(),null),this._audioContext&&(n(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}};const Ap=()=>{let e=(e,t)=>{t?self.postMessage(e,{transfer:t}):self.postMessage(e)};e({type:`support`,supported:typeof MediaStreamTrackProcessor<`u`});let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;self.addEventListener(`message`,r=>{let i=r.data;switch(i.type){case`videoTrack`:{n.set(i.trackId,i.track);let r=new MediaStreamTrackProcessor({track:i.track}),a=new WritableStream({write:t=>{if(!n.has(i.trackId)){t.close();return}e({type:`videoFrame`,trackId:i.trackId,videoFrame:t},[t])}}),o=new AbortController;t.set(i.trackId,o),r.readable.pipeTo(a,{signal:o.signal}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e({type:`error`,trackId:i.trackId,error:t})})}break;case`stopTrack`:{let r=t.get(i.trackId);r&&(r.abort(),t.delete(i.trackId)),n.get(i.trackId)?.stop(),n.delete(i.trackId),e({type:`trackStopped`,trackId:i.trackId})}break;default:Ee(i)}})};let jp=0,Mp=null;const Np=()=>{let e=new Blob([`(${Ap.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);Mp=new Worker(t)};let Pp=null;const Fp=async()=>Pp===null?(Mp||Np(),new Promise(e=>{n(Mp);let t=n=>{let r=n.data;r.type===`support`&&(Pp=r.supported,Mp.removeEventListener(`message`,t),e(r.supported))};Mp.addEventListener(`message`,t)})):Pp,Ip=(e,t)=>{n(Mp),t?Mp.postMessage(e,t):Mp.postMessage(e)};var Lp=class extends pp{constructor(e){if(super(),!Dr.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Dr.join(`, `)}.`);this._codec=e}},Rp=class extends Lp{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new Hu({codec:e,output:(e,t)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,e,t).catch(e=>{this._setError(e)})}})}add(e){if(typeof e!=`string`)throw TypeError(`text must be a string.`);return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||=(this._error=e,!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};
|
|
519
|
+
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},pp=(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}),mp=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},hp=class extends mp{constructor(e){if(super(),!N.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${N.join(`, `)}.`);this._codec=e}};const gp=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)};var _p=class extends hp{constructor(e){super(e)}add(e,t){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),gp(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},vp=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Ye,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,r){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,o=a.sizeChangeBehavior??`deny`,s=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(s=!0,o===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||s&&o!==`passThrough`){let r=a.transform?.width,i=a.transform?.height,c=a.transform?.fit??`fill`;s&&o!==`passThrough`&&(n(this.outputWidth),n(this.outputHeight),n(o!==`deny`),r=this.outputWidth,i=this.outputHeight,c=o);let l=await e.transform({width:r,height:i,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:c,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=l.displayWidth,this.outputHeight=l.displayHeight),t&&e.close(),e=l,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let c=a.transform?.frameRate;if(c!==void 0){let n=e.timestamp+e.duration,a=ze(e.timestamp,c);if(this.frameRateLastSample!==null){if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=n;return}await this.padFrameRate(a,r)}e===i&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/c),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=n}await this.processAndEncode(e,r)}finally{t&&e.close()}}async processAndEncode(e,t){let r=this.encodingConfig,i;if(r.transform?.process){let t=r.transform.process(e);if(k(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let n=[];try{for(let r of t)r instanceof pc?n.push(r):typeof VideoFrame<`u`&&r instanceof VideoFrame?n.push(new pc(r)):n.push(new pc(r,{timestamp:e.timestamp,duration:e.duration}))}catch(r){for(let t of n)t!==e&&t.close();for(let n of t)(n instanceof pc&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw r}i=n}else i=[e];try{for(let e of i){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let r=this.encodingConfig.keyFrameInterval??2,i=Math.floor(e.timestamp/r),a={...this.defaultEncodeOptions,...e.encodeOptions,...t},o={...a,keyFrame:a.keyFrame===void 0?r===0||i!==this.lastMultipleOfKeyFrameInterval:a.keyFrame};if(this.lastMultipleOfKeyFrameInterval=i,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,o)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{n(this.encoder);let t=e.toVideoFrame(),r=E(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),i=r===-1?null:this.preciseTimings[r];if(i&&i.microsecondTimestamp===t.timestamp?(i.timestamp!==e.timestamp&&(i.timestampIsValid=!1),i.duration!==e.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(r+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)try{this.encoder.encode(t,o)}finally{t.close()}else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(t,o)}finally{t.close()}}else{this.splitter||=new Sp;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n);try{this.encoder.encode(e,o)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of i)t!==e&&t.close()}}async padFrameRate(e,t){let r=this.encodingConfig.transform.frameRate;n(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*r);for(let e=1;e<i;e++){let n={stack:[],error:void 0,hasError:!1};try{let i=fp(n,this.frameRateLastSample.clone(),!1);i.setTimestamp(this.frameRateLastTimestamp+e/r),i.setDuration(1/r),await this.processAndEncode(i,t)}catch(e){n.error=e,n.hasError=!0}finally{pp(n)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=cl(this.encodingConfig.quality,this.encodingConfig.bitrate);n(t!==void 0);let r=Gc({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),i=null,a;for(let e of r){let t=e.config;if(this.encodingConfig.onEncoderConfig?.(t),a=Cl.find(e=>e.supports(this.encodingConfig.codec,t)),a){i=e;break}if(typeof VideoEncoder<`u`){if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(t)).supported){i=e;break}}catch{}}}if(!i){if(typeof VideoEncoder>`u`)throw Error(it(`VideoEncoder`));let e=r[0].config,t=r.map(({config:e,quantizer:t})=>t===null?`${e.bitrate} bps`:`quantizer ${t}`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(` / `)}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??`no-preference`}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let o=i.config;i.quantizer===null?this.source._nominalBitrate=o.bitrate??null:this.defaultEncodeOptions=$c(this.encodingConfig.codec,i.quantizer),a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof I))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);gp(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init()):(this.encoderConfig=o,this.encodingConfig.codec===`avc`&&$e()&&(this.chunkTimestampsAreShiftedByDuration=await bp()),this.createWebCodecsEncoders()),n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let e=this.encoderConfig;n(e);let t=[],r=[],i=0,a=0,o=(e,t)=>{if(at(e)){this.encodersReclaimed=!0;return}e.stack=t,this.setError(e)},s=(/* @__PURE__ */ Error(`Encoding error`)).stack;if(this.encoder=new VideoEncoder({output:(e,o)=>{if(!this.alphaEncoder){this.addPacket(e,null,o);return}let s=this.alphaFrameQueue.shift();n(s!==void 0),s?(this.alphaEncoder.encode(s,{...this.defaultEncodeOptions,keyFrame:e.type===`key`}),a++,s.close(),t.push({chunk:e,meta:o})):a===0?this.addPacket(e,null,o):(r.push(i+a),t.push({chunk:e,meta:o}))},error:e=>o(e,s)}),this.encoder.configure(e),this.encodingConfig.alpha===`keep`){let s=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.alphaEncoder=new VideoEncoder({output:(e,o)=>{a--;let s=t.shift();for(n(s!==void 0),this.addPacket(s.chunk,e,s.meta),i++;r.length>0&&r[0]===i;){r.shift();let e=t.shift();n(e!==void 0),this.addPacket(e.chunk,null,e.meta)}},error:e=>o(e,s)}),this.alphaEncoder.configure(e)}}addPacket(e,t,r){let i={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}let a=I.fromEncodedChunk(e,i),o=this.encoderConfig;if(n(o),r?.decoderConfig&&(r.decoderConfig.codec=Rr({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?S(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:o.codec.includes(`avc1.`)?1:o.codec.includes(`avc3.`)?3:null,avcCodecInfo:this.encodingConfig.codec===`avc`&&!r.decoderConfig.description?_n(a.data):null,hevcCodecInfo:this.encodingConfig.codec===`hevc`&&!r.decoderConfig.description?On(a.data):null,vp9CodecInfo:this.encodingConfig.codec===`vp9`?Vn(a.data):null,av1CodecInfo:this.encodingConfig.codec===`av1`?Wn(a.data):null,proresFormat:null}),this.encodingConfig.codec===`avc`&&r.decoderConfig.description&&$e())){let e=yn(S(r.decoderConfig.description)),t=e?.sequenceParameterSets[0];if(t&&t[0]===t[1]){n(e),t=t.subarray(1);let i=e.pictureParameterSets[0];i&&=i.subarray(1);let a=vn({...e,sequenceParameterSets:[t],pictureParameterSets:i?[i]:[]});r.decoderConfig.description=a}}let s=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(s-=e.duration??0,a=a.clone({timestamp:s/1e6}));let c=E(this.preciseTimings,s,e=>e.microsecondTimestamp),l=c===-1?null:this.preciseTimings[c],u=null;this.emittedEncoderPackets===0&&a.type===`delta`&&r?.decoderConfig&&(u=Zn(this.encodingConfig.codec,r.decoderConfig,a.data)),(l&&l.microsecondTimestamp===s||u!==null)&&(a=a.clone({timestamp:l?.timestampIsValid?l.timestamp:void 0,duration:l?.durationIsValid?l.duration:void 0,type:u??void 0})),gp(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){n(this.encoder),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=ze(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Mt(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}};let yp=null;const bp=()=>yp??=(async()=>{let e=null,t=new VideoEncoder({output:t=>{e??=t.timestamp},error:()=>{}});try{t.configure({codec:`avc1.64001f`,width:1280,height:720});let e=new VideoFrame(/* @__PURE__ */ new Uint8Array(1382400),{format:`I420`,codedWidth:1280,codedHeight:720,timestamp:0,duration:500});t.encode(e,{keyFrame:!0}),e.close(),await t.flush()}catch{return!1}finally{t.state!==`closed`&&t.close()}return e===500})();let xp=null;var Sp=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */ new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!xp){let e=new Blob([`(${Cp.toString()})()`],{type:`application/javascript`});xp=URL.createObjectURL(e)}this.worker=new Worker(xp),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=D();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=/* @__PURE__ */ Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};const Cp=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,S=a?512:o?2048:128;s===1?y.fill(S,x):new Uint16Array(y.buffer,x,2*_).fill(S);let C=a?`I420P10`:o?`I420P12`:`I420`,ee=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),te={format:C,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[y.buffer]};return{colorFrame:ee,alphaFrame:new VideoFrame(y,te)}}};var wp=class extends hp{constructor(e){Uc(e),super(e.codec),this._encoder=new vp(this,e)}add(e,t){if(!(e instanceof pc))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Tp=class extends hp{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);Uc(t),super(t.codec),this._encoder=new vp(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e))throw TypeError(`timestamp must be a finite number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new pc(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Ep=class extends hp{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`video`)throw TypeError(`track must be a video MediaStreamTrack.`);if(Uc(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.frameRate!=null&&(typeof n.frameRate!=`number`||n.frameRate<=0))throw TypeError(`options.frameRate, when provided, must be either a positive number or null.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);t={...t,latencyMode:`realtime`},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=D(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=n,this._encoder=new vp(this,t),this._track=e}async _start(){this._errorPromiseAccessed||A._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate===void 0?this._track.getSettings().frameRate??null:this._options.frameRate;this._abortController=new AbortController;let t=null,r=null,i=0,a=!1,o=null,s=0,c=()=>{if(n(e!==null),!this._lastVideoFrame)return;n(r!==null),n(t!==null);let a=performance.now();for(;a-r>1e3/e;){r+=1e3/e;let n=t+i/e,o=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*n,duration:1e6/e});u(o,a)}};e!==null&&(this._timerHandle=At(c,4));let l=t=>{if(e===null)u(t);else{let e=performance.now();this._lastVideoFrame?(c(),this._lastVideoFrame?.close(),this._lastVideoFrame=t):(u(t.clone(),e),r=e,this._lastVideoFrame=t)}},u=(e,n=performance.now())=>{if(a){e.close();return}i++;let r=e.timestamp/1e6;if(this._paused){if(t!==null){if(o!==null&&this._options.timestampBase!==`unix`){let e=r-o;s-=e}o=r}e.close();return}if(t===null){t=r;let e,i=this._options.timestampBase??`synced-zero`;if(i===`unix`)e=Date.now()/1e3;else if(i===`zero`)e=0;else{let t=this._connectedTrack.output;t._firstMediaStreamTimestamp===null?(t._firstMediaStreamTimestamp=n/1e3,e=0):e=n/1e3-t._firstMediaStreamTimestamp}s=e-t}if(o=r,this._encoder.getQueueSize()>=8){e.close();return}let c=new pc(e,{timestamp:r+s});this._encoder.add(c,!0).catch(e=>{a=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._workerTrackId!==null&&zp({type:`stopTrack`,trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:l});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else if(await Rp())this._workerTrackId=Pp++,zp({type:`videoTrack`,trackId:this._workerTrackId,track:this._track}),this._workerListener=e=>{let t=e.data;t.type===`videoFrame`&&t.trackId===this._workerTrackId?l(t.videoFrame):t.type===`error`&&t.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(t.error)},Fp.addEventListener(`message`,this._workerListener);else if(e!==null){let e=document.createElement(`video`);e.style.position=`fixed`,e.style.left=`-10000px`,e.style.top=`-10000px`,e.style.width=`1px`,e.style.height=`1px`,e.style.opacity=`0`,e.style.pointerEvents=`none`,e.muted=!0,e.srcObject=new MediaStream([this._track]),document.body.appendChild(e),this._videoElement=e,e.addEventListener(`loadeddata`,()=>{if(a||!this._videoElement)return;let t=new VideoFrame(e,{timestamp:1e3*performance.now()});l(t),t.close()},{once:!0}),e.play().catch(e=>{a=!0,this._promiseWithResolvers.reject(e)})}else throw Error(`When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.`)}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&=(this._abortController.abort(),null),this._timerHandle&&jt(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&=(this._videoElement.srcObject=null,this._videoElement.remove(),null),this._workerTrackId!==null&&(n(this._workerListener),zp({type:`stopTrack`,trackId:this._workerTrackId}),await new Promise(e=>{let t=r=>{let i=r.data;i.type===`trackStopped`&&i.trackId===this._workerTrackId&&(n(this._workerListener),Fp.removeEventListener(`message`,this._workerListener),Fp.removeEventListener(`message`,t),e())};Fp.addEventListener(`message`,t)}))}finally{await this._encoder.flushAndClose(e)}}},Dp=class extends mp{constructor(e){if(super(),!F.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${F.join(`, `)}.`);this._codec=e}},Op=class extends Dp{constructor(e){super(e)}add(e,t){if(!(e instanceof I))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},kp=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Ye,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new dp({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Rc(e.format)!==n.transform.sampleFormat){let r=Bc(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(k(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof Mc))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);for(let e of t)await this.encodeSample(e,!0)}finally{for(let e of t)e instanceof Mc&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new Mc({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{n(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){n(this.outputSampleSize),n(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:i,sampleRate:a,timestamp:o}=e,s=2048,c=[];for(let t=0;t<i;t+=s){let n=Math.min(s,e.numberOfFrames-t),i=n*r*this.outputSampleSize,a=new ArrayBuffer(i),o=new DataView(a);c.push({frameCount:n,view:o})}let l=e.format===`s32`||e.format===`s32-planar`,u=l?`s32-planar`:`f32-planar`,d=l?1/2147483648:1,f=e.allocationSize({planeIndex:0,format:u}),p=l?new Int32Array(f/4):new Float32Array(f/4);for(let t=0;t<r;t++){e.copyTo(p,{planeIndex:t,format:u});for(let e=0;e<c.length;e++){let{frameCount:n,view:i}=c[e];for(let a=0;a<n;a++)this.writeOutputValue(i,(a*r+t)*this.outputSampleSize,p[e*s+a]*d)}}t&&e.close();let m={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let e=0;e<c.length;e++){let{frameCount:t,view:n}=c[e],r=n.buffer,i=e*s,l=new I(new Uint8Array(r),`key`,o+i/a,t/a);this.encodingConfig.onEncodedPacket?.(l,m),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,m)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,i=cl(this.encodingConfig.quality,this.encodingConfig.bitrate),a=Jc({numberOfChannels:t,sampleRate:r,...this.encodingConfig,quality:i});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let o=wl.find(e=>e.supports(this.encodingConfig.codec,a));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof I))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(P.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(it(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let t=(/* @__PURE__ */ Error(`Encoding error`)).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){if(t.decoderConfig.description&&t.decoderConfig.description.byteLength>0&&S(t.decoderConfig.description)[0]===3){let{decoderSpecificInfo:e}=Ci(du.tempFromBytes(S(t.decoderConfig.description)));t.decoderConfig.description=e??void 0}let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||qt(S(t.decoderConfig.description)).objectType===0,e){let e=Number(h(a.codec.split(`.`)));t.decoderConfig.description=Xt({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=I.fromEncodedChunk(e);n=n.clone({timestamp:Le(n.timestamp,a.sampleRate),duration:e.duration==null?void 0:Le(n.duration,a.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.setError(e)})},error:e=>{e.stack=t,this.setError(e)}}),this.encoder.configure(a)}n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:i}=Gr(e);switch(this.outputSampleSize=r,r){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,O(Math.round(n*128)+128,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,O(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=O(Math.round(n*32768),-32768,32767);e.setUint8(t,Dl(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=O(Math.round(n*32768),-32768,32767);e.setUint8(t,kl(r))}:n(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,O(Math.round(n*32768)+32768,0,65535),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,O(Math.round(n*32768),-32768,32767),i):n(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>ke(e,t,O(Math.round(n*8388608)+8388608,0,16777215),i):t===`signed`?this.writeOutputValue=(e,t,n)=>Ae(e,t,O(Math.round(n*8388608),-8388608,8388607),i):n(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,O(Math.round(n*2147483648)+2147483648,0,4294967295),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,O(Math.round(n*2147483648),-2147483648,2147483647),i):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,i):n(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,i):n(!1);break;default:Ee(r),n(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Ap=class extends Dp{constructor(e){Kc(e),super(e.codec),this._encoder=new kp(this,e)}add(e){if(!(e instanceof Mc))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},jp=class extends Dp{constructor(e,t={}){if(Kc(e),typeof t!=`object`||!t)throw TypeError(`options must be an object.`);if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw TypeError(`options.startTimestamp, when provided, must be a finite number.`);super(e.codec),this._encoder=new kp(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=Mc._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Mp=class extends Dp{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`audio`)throw TypeError(`track must be an audio MediaStreamTrack.`);if(Kc(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=D(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=n,this._encoder=new kp(this,t),this._track=e}async _start(){this._errorPromiseAccessed||A._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,n=null,r=0,i=i=>{if(t){i.close();return}let a=i.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!==`unix`){let e=a-n;r-=e}n=a}i.close();return}if(e===null){e=i.timestamp;let t,n=this._options.timestampBase??`synced-zero`;if(n===`unix`)t=Date.now()/1e3;else if(n===`zero`)t=0;else{let e=this._connectedTrack.output;e._firstMediaStreamTimestamp===null?(e._firstMediaStreamTimestamp=performance.now()/1e3,t=0):t=performance.now()/1e3-e._firstMediaStreamTimestamp}r=t-e}if(n=a,this._encoder.getQueueSize()>=8){i.close();return}i.setTimestamp(a+r),this._encoder.add(i,!0).catch(e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:e=>i(new Mc(e))});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else{let e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});let t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state===`suspended`&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let n=0;this._scriptProcessorNode.onaudioprocess=e=>{let t=Mc._fromAudioBuffer(e.inputBuffer,n);n+=e.inputBuffer.duration;for(let e of t)i(e)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&=(this._abortController.abort(),null),this._audioContext&&(n(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}};const Np=()=>{let e=(e,t)=>{t?self.postMessage(e,{transfer:t}):self.postMessage(e)};e({type:`support`,supported:typeof MediaStreamTrackProcessor<`u`});let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;self.addEventListener(`message`,r=>{let i=r.data;switch(i.type){case`videoTrack`:{n.set(i.trackId,i.track);let r=new MediaStreamTrackProcessor({track:i.track}),a=new WritableStream({write:t=>{if(!n.has(i.trackId)){t.close();return}e({type:`videoFrame`,trackId:i.trackId,videoFrame:t},[t])}}),o=new AbortController;t.set(i.trackId,o),r.readable.pipeTo(a,{signal:o.signal}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e({type:`error`,trackId:i.trackId,error:t})})}break;case`stopTrack`:{let r=t.get(i.trackId);r&&(r.abort(),t.delete(i.trackId)),n.get(i.trackId)?.stop(),n.delete(i.trackId),e({type:`trackStopped`,trackId:i.trackId})}break;default:Ee(i)}})};let Pp=0,Fp=null;const Ip=()=>{let e=new Blob([`(${Np.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);Fp=new Worker(t)};let Lp=null;const Rp=async()=>Lp===null?(Fp||Ip(),new Promise(e=>{n(Fp);let t=n=>{let r=n.data;r.type===`support`&&(Lp=r.supported,Fp.removeEventListener(`message`,t),e(r.supported))};Fp.addEventListener(`message`,t)})):Lp,zp=(e,t)=>{n(Fp),t?Fp.postMessage(e,t):Fp.postMessage(e)};var Bp=class extends mp{constructor(e){if(super(),!Dr.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Dr.join(`, `)}.`);this._codec=e}},Vp=class extends Bp{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new Uu({codec:e,output:(e,t)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,e,t).catch(e=>{this._setError(e)})}})}add(e){if(typeof e!=`string`)throw TypeError(`text must be a string.`);return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||=(this._error=e,!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};
|
|
520
520
|
/*!
|
|
521
521
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
522
522
|
*
|
|
@@ -524,7 +524,7 @@ if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object
|
|
|
524
524
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
525
525
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
526
526
|
*/
|
|
527
|
-
const zp=e=>e===`opus`?`Opus`:e;var Bp=class extends Fu{constructor(e,t){if(!(e._target instanceof Uf))throw TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:e})=>`playlist-${e}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(e=>e.isSingleFile?`segments-${e.playlist.n}${e.format.fileExtension}`:`segment-${e.playlist.n}-${e.n}${e.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(e=>`init-${e.n}${e.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),t=this.output.tracks.some(e=>e.metadata.isRelativeToUnixEpoch),r=this.output.tracks.some(e=>!e.metadata.isRelativeToUnixEpoch);if(t&&r)throw Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;let i=/* @__PURE__ */ new Map,a=[],o=!1,s=!1,c=!1;for(let e of this.output.tracks){e.type===`video`&&(o=!0);let t=/* @__PURE__ */ new Map;for(let n of this.output.tracks){if(e===n||!e.canBePairedWith(n))continue;if(e.type===n.type){s||=(A._warn(`Illegal pairing of two ${e.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),!0);continue}if(e.isVideoTrack()&&e.metadata.hasOnlyKeyPackets||n.isVideoTrack()&&n.metadata.hasOnlyKeyPackets){c||=(A._warn(`A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired.`),!0);continue}let r=t.get(n.source._codec);r||t.set(n.source._codec,r=[]),r.push(n)}for(let[,n]of t){let t=n.map(e=>e.id).join(`-`);a.find(e=>e.key===t)||a.push({name:n[0].type+`-`+(a.length+1),key:t,tracks:n,needsEmit:!1,firstNoUri:!1});let r=i.get(e);r||i.set(e,r=[]),r.push(t)}}let l=o?`video`:`audio`,u=[],d=[],f=[];for(let e of this.output.tracks){let t=i.get(e);if(t){if(n(t.length>0),e.type!==l)continue;for(let r of t){let o=a.find(e=>e.key===r);if(n(o),t.length===1&&o.tracks.length===1){let t=i.get(o.tracks[0]);if(n(t!==void 0),t.length===1){let r=a.find(e=>e.key===t[0]);if(r.tracks.length===1){n(r.tracks[0]===e),u.push({tracks:[e,o.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[e],linkedGroup:o}),o.needsEmit=!0}}else e.type===`video`?d.push(e):e.type===`audio`&&f.push(e)}let p=({metadata:e})=>{let t=``;return t+=`${e.languageCode??`und`}-`,t+=`${e.name??``}-`,t+=`${e.disposition?.default??!0}-`,t+=`${e.disposition?.primary??!1}-`,t+=`${e.disposition?.forced??!1}-`,t};if(d.length>0){if(new Set(d.map(p)).size>1){let e={key:d.map(e=>e.id).join(`-`),name:`video-`+(a.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[d[0]],linkedGroup:e})}else for(let e of d)u.push({tracks:[e],linkedGroup:null})}if(f.length>0){if(new Set(f.map(p)).size>1){let e={key:f.map(e=>e.id).join(`-`),name:`audio-`+(a.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[f[0]],linkedGroup:e})}else for(let e of f)u.push({tracks:[e],linkedGroup:null})}let m=e=>{let t=[],r=0,i=0,a=!1,o=null,s=-1/0;for(let n of e)n.isVideoTrack()?(r++,a||=(n.metadata.rotation??0)!==0||!!n.metadata.flip||!!n.metadata.transformationMatrix):n.isAudioTrack()&&i++,t.push(n.source._codec);for(let e of Nt(this.format._options.segmentFormat)){let n=e.getSupportedCodecs(),c=e.getSupportedTrackCounts();if(t.some(e=>!n.includes(e))||r<c.video.min||r>c.video.max||i<c.audio.min||i>c.audio.max)continue;let l=0;a&&e.supportsVideoTransformationMetadata&&l++,l>s&&(o=e,s=l)}return n(o),o},h=async e=>{if(e.some(e=>this.playlists.some(t=>t.tracks.includes(e))))throw Error(`Internal error: track is already registered in a playlist.`);let t=m(e),n=this.playlists.length+1,r=await this.getPlaylistPath({n,tracks:e,segmentFormat:t});Vp(r);let i={id:this.playlists.length+1,path:r,tracks:e,segmentFormat:t,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new me};return this.playlists.push(i),i};for(let e of a)if(e.needsEmit)for(let t=0;t<e.tracks.length;t++){let n=e.tracks[t],r=this.playlists.find(e=>e.tracks[0].id===n.id);r??=await h([n]),this.playlistDeclarations.push({playlist:r,groupId:e.name,noUri:e.firstNoUri&&t===0,references:[]})}for(let e of u){let t=this.playlists.find(t=>t.tracks[0].id===e.tracks[0].id);t??=await h(e.tracks),this.playlistDeclarations.push({playlist:t,groupId:null,noUri:!1,references:e.linkedGroup?this.playlistDeclarations.filter(t=>t.groupId===e.linkedGroup.name):[]})}for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}async getMimeType(){return Oo}allTracksAreKnown(e){for(let t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async onTrackClose(e){let t=this.trackDatas.find(t=>t.track===e);t&&(t.closed=!0);let r=this.playlists.find(t=>t.tracks.includes(e));n(r);let i=await r.mutex.acquire();try{await this.advancePlaylist(r)}finally{i()}}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r?.decoderConfig);let a=this.playlists.filter(t=>t.tracks.includes(e));return n(a.length===1),i={track:e,packets:[],playlist:a[0],closed:!1,info:{type:`video`,decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(i),i}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r?.decoderConfig);let a=this.playlists.filter(t=>t.tracks.includes(e));return n(a.length===1),i={track:e,packets:[],playlist:a[0],closed:!1,info:{type:`audio`,decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(i),i}async addEncodedVideoPacket(e,t,n){let r=this.getVideoTrackData(e,t,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addEncodedAudioPacket(e,t,n){let r=this.getAudioTrackData(e,t,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addSubtitleCue(e,t,n){throw Error(`Unreachable.`)}async advancePlaylist(e){if(n(!e.done),!this.allTracksAreKnown(e))return;let t=this.trackDatas.filter(t=>e.tracks.includes(t.track));if(e.currentSegmentStartTimestamp===null){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let r=t.find(e=>e.info.type===`video`),i=t.find(e=>e.info.type===`audio`);for(;;){let a=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,s=0;if(r&&(!r.closed||r.packets.length>0)){let e=r.packets.every(e=>e.timestamp<a),t=null,c=null;if(e){if(!r.closed)return}else for(let e=0;e<r.packets.length;e++){let n=r.packets[e];if(t!==null&&n.timestamp>a)break;e>0&&n.type===`key`&&(t=n,c=e)}if(c!==null){if(o=c,i){let e=i.packets.findIndex(e=>e.timestamp>=t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}else{if(!r.closed)return;o=r.packets.length;let e=bt(r.packets,e=>e.timestamp),t=r.packets[e];if(n(t),i){if(t.timestamp<a){let e=i.packets.findIndex(e=>e.timestamp>=a);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}else{let e=i.packets.findIndex(e=>e.timestamp>t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}}}else if(i&&(!i.closed||i.packets.length>0)){if(i.packets.every(e=>e.timestamp<a)){if(i.closed)s=i.packets.length;else return}else{let e=Ce(i.packets,e=>e.timestamp<=a);s=Math.max(e,1)}}if(o===0&&s===0){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let c=null,l,u;n(this.output._target instanceof Uf);let d=this.output._target;if(this.singleFilePerPlaylist){if(e.singleFile===null){let t={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Wp(e)};l=await this.getSegmentPath(t),Hp(l),u=gt(gt(d.rootPath,e.path),l);let n=await this.output._getTarget({path:u,isRoot:!1,mimeType:e.segmentFormat.mimeType}),a=null;if(e.segmentFormat._isFragmentedIsobmff()){a={output:new fm({format:e.segmentFormat,target:n}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},n.on(`write`,({end:e})=>{a.currentFileSize=Math.max(a.currentFileSize,e)});let t=a.output._muxer;t.minimumFragmentDuration=1/0;let o=t.formatOptions.onMoof;t.formatOptions.onMoof=(e,n,r)=>{a.firstMoofPosition=n,o?.(e,n,r),t.formatOptions.onMoof=o},r&&(a.videoSource=new gp(r.track.source._codec),a.output.addVideoTrack(a.videoSource,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),i&&(a.audioSource=new Tp(i.track.source._codec),a.output.addAudioTrack(a.audioSource,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),await a.output.start()}else n._start();e.singleFile={target:n,path:l,nextOffset:0,info:t,fragmentedIsobmffOutput:a}}else l=e.singleFile.path,u=gt(gt(d.rootPath,e.path),l)}else c={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Wp(e)},l=await this.getSegmentPath(c),Hp(l),u=gt(gt(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,m=-1/0,h=null,g=null,_=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,g=e.singleFile.fragmentedIsobmffOutput.videoSource,_=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new fm({format:e.segmentFormat,target:new Uf(u,async t=>{let n={...t,isRoot:!1};if(t.isRoot){if(e.singleFile){let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:e})=>f=Math.max(f,e)),t}{let e=await this.output._getTarget(n);return p=e,e.on(`write`,({end:e})=>f=Math.max(f,e)),e}}return this.output._getTarget(n)}),initTarget:async()=>{if(e.initSegment)return new Vf;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),t.on(`finalized`,()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),t}{let t=Wp(e),n=await this.getInitPath(t);Up(n),e.initSegment={path:n,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let r=gt(gt(d.rootPath,e.path),n),i=await this.output._getTarget({path:r,isRoot:!1,mimeType:e.segmentFormat.mimeType});return i.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),i.on(`finalized`,()=>{this.format._options.onInit?.(i,t)}),i}}}),r&&(g=new gp(r.track.source._codec),h.addVideoTrack(g,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),i&&(_=new Tp(i.track.source._codec),h.addAudioTrack(_,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),await h.start()),r){n(g);let e={decoderConfig:r.info.decoderConfig};for(let t=0;t<o;t++){let n=r.packets[t];await g.add(n,e),m=Math.max(m,n.timestamp+n.duration)}}if(i){n(_);let e={decoderConfig:i.info.decoderConfig};for(let t=0;t<s;t++){let n=i.packets[t];await _.add(n,e),m=Math.max(m,n.timestamp+n.duration)}}e.singleFile?.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),f=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await h.finalize()}catch(e){throw await h?.cancel(),e}c&&(n(p),this.format._options.onSegment?.(p,c)),o>0&&(n(r),r.packets.splice(0,o)),s>0&&(n(i),i.packets.splice(0,s));let v=1/0;r&&r.packets.length>0&&(v=r.packets[0].timestamp),i&&i.packets.length>0&&(v=Math.min(v,i.packets[0].timestamp));let y=v<1/0?v:m;n(Number.isFinite(y));let b=y-e.currentSegmentStartTimestamp;if(n(b>=0),e.writtenSegments.push({path:l,duration:b,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:c??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,b),e.currentSegmentStartTimestamp=y,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let t=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(n(t.info),this.format._options.onSegmentPopped?.(t.path,t.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){n(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let t=e.writtenSegments,n=0,r=0,i=0;for(let e=0;e<t.length;e++){i+=t[e].duration;let r=0,a=0;for(let i=e;i<t.length&&(r+=t[i].byteSize,a+=t[i].duration,a>=.5*this.globalTargetDuration&&a<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*r/a)),!(a>1.5*this.globalTargetDuration));i++);}if(n===0)for(let e of t){let t=e.duration||1;n=Math.max(n,8*e.byteSize/t)}for(let e of t)r+=8*e.byteSize;let a=r/(i||1);if(t.length===0)for(let t of e.tracks){let e=this.trackDatas.find(e=>e.track===t),r=t.source._nominalBitrate??t.metadata.bitrate??0;if(a+=t.source._nominalBitrate??t.metadata.averageBitrate??0,r===0){let n=new z(`medium`);if(t.isVideoTrack()){let i=e?.info.decoderConfig;r=n._toVideoBitrate(t.source._codec,i?.codedWidth??1920,i?.codedHeight??1080)}else t.isAudioTrack()&&(r=n._toAudioBitrate(t.source._codec)??0)}n+=r}e.peakBitrate=n,e.averageBitrate=a}async writePlaylist(e){n(this.output._target instanceof Uf);let t=this.output._target;this.updatePlaylistBitrates(e);let r=!1;for(let t of e.writtenSegments)r||=t.byteOffset!==null;let i=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,a=3;(i||r)&&(a=4),e.initSegment&&(a=5),e.initSegment&&!i&&(a=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,s=gt(t.rootPath,e.path),c=`#EXTM3U
|
|
527
|
+
const Hp=e=>e===`opus`?`Opus`:e;var Up=class extends Iu{constructor(e,t){if(!(e._target instanceof Wf))throw TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:e})=>`playlist-${e}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(e=>e.isSingleFile?`segments-${e.playlist.n}${e.format.fileExtension}`:`segment-${e.playlist.n}-${e.n}${e.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(e=>`init-${e.n}${e.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),t=this.output.tracks.some(e=>e.metadata.isRelativeToUnixEpoch),r=this.output.tracks.some(e=>!e.metadata.isRelativeToUnixEpoch);if(t&&r)throw Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;let i=/* @__PURE__ */ new Map,a=[],o=!1,s=!1,c=!1;for(let e of this.output.tracks){e.type===`video`&&(o=!0);let t=/* @__PURE__ */ new Map;for(let n of this.output.tracks){if(e===n||!e.canBePairedWith(n))continue;if(e.type===n.type){s||=(A._warn(`Illegal pairing of two ${e.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),!0);continue}if(e.isVideoTrack()&&e.metadata.hasOnlyKeyPackets||n.isVideoTrack()&&n.metadata.hasOnlyKeyPackets){c||=(A._warn(`A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired.`),!0);continue}let r=t.get(n.source._codec);r||t.set(n.source._codec,r=[]),r.push(n)}for(let[,n]of t){let t=n.map(e=>e.id).join(`-`);a.find(e=>e.key===t)||a.push({name:n[0].type+`-`+(a.length+1),key:t,tracks:n,needsEmit:!1,firstNoUri:!1});let r=i.get(e);r||i.set(e,r=[]),r.push(t)}}let l=o?`video`:`audio`,u=[],d=[],f=[];for(let e of this.output.tracks){let t=i.get(e);if(t){if(n(t.length>0),e.type!==l)continue;for(let r of t){let o=a.find(e=>e.key===r);if(n(o),t.length===1&&o.tracks.length===1){let t=i.get(o.tracks[0]);if(n(t!==void 0),t.length===1){let r=a.find(e=>e.key===t[0]);if(r.tracks.length===1){n(r.tracks[0]===e),u.push({tracks:[e,o.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[e],linkedGroup:o}),o.needsEmit=!0}}else e.type===`video`?d.push(e):e.type===`audio`&&f.push(e)}let p=({metadata:e})=>{let t=``;return t+=`${e.languageCode??`und`}-`,t+=`${e.name??``}-`,t+=`${e.disposition?.default??!0}-`,t+=`${e.disposition?.primary??!1}-`,t+=`${e.disposition?.forced??!1}-`,t};if(d.length>0){if(new Set(d.map(p)).size>1){let e={key:d.map(e=>e.id).join(`-`),name:`video-`+(a.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[d[0]],linkedGroup:e})}else for(let e of d)u.push({tracks:[e],linkedGroup:null})}if(f.length>0){if(new Set(f.map(p)).size>1){let e={key:f.map(e=>e.id).join(`-`),name:`audio-`+(a.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[f[0]],linkedGroup:e})}else for(let e of f)u.push({tracks:[e],linkedGroup:null})}let m=e=>{let t=[],r=0,i=0,a=!1,o=null,s=-1/0;for(let n of e)n.isVideoTrack()?(r++,a||=(n.metadata.rotation??0)!==0||!!n.metadata.flip||!!n.metadata.transformationMatrix):n.isAudioTrack()&&i++,t.push(n.source._codec);for(let e of Nt(this.format._options.segmentFormat)){let n=e.getSupportedCodecs(),c=e.getSupportedTrackCounts();if(t.some(e=>!n.includes(e))||r<c.video.min||r>c.video.max||i<c.audio.min||i>c.audio.max)continue;let l=0;a&&e.supportsVideoTransformationMetadata&&l++,l>s&&(o=e,s=l)}return n(o),o},h=async e=>{if(e.some(e=>this.playlists.some(t=>t.tracks.includes(e))))throw Error(`Internal error: track is already registered in a playlist.`);let t=m(e),n=this.playlists.length+1,r=await this.getPlaylistPath({n,tracks:e,segmentFormat:t});Wp(r);let i={id:this.playlists.length+1,path:r,tracks:e,segmentFormat:t,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new me};return this.playlists.push(i),i};for(let e of a)if(e.needsEmit)for(let t=0;t<e.tracks.length;t++){let n=e.tracks[t],r=this.playlists.find(e=>e.tracks[0].id===n.id);r??=await h([n]),this.playlistDeclarations.push({playlist:r,groupId:e.name,noUri:e.firstNoUri&&t===0,references:[]})}for(let e of u){let t=this.playlists.find(t=>t.tracks[0].id===e.tracks[0].id);t??=await h(e.tracks),this.playlistDeclarations.push({playlist:t,groupId:null,noUri:!1,references:e.linkedGroup?this.playlistDeclarations.filter(t=>t.groupId===e.linkedGroup.name):[]})}for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}async getMimeType(){return ko}allTracksAreKnown(e){for(let t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async onTrackClose(e){let t=this.trackDatas.find(t=>t.track===e);t&&(t.closed=!0);let r=this.playlists.find(t=>t.tracks.includes(e));n(r);let i=await r.mutex.acquire();try{await this.advancePlaylist(r)}finally{i()}}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ei(r,e.source._codec),n(r),n(r?.decoderConfig);let a=this.playlists.filter(t=>t.tracks.includes(e));return n(a.length===1),i={track:e,packets:[],playlist:a[0],closed:!1,info:{type:`video`,decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(i),i}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;ni(r,e.source._codec),n(r),n(r?.decoderConfig);let a=this.playlists.filter(t=>t.tracks.includes(e));return n(a.length===1),i={track:e,packets:[],playlist:a[0],closed:!1,info:{type:`audio`,decoderConfig:r.decoderConfig,primingPacket:t}},this.trackDatas.push(i),i}async addEncodedVideoPacket(e,t,n){let r=this.getVideoTrackData(e,t,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addEncodedAudioPacket(e,t,n){let r=this.getAudioTrackData(e,t,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addSubtitleCue(e,t,n){throw Error(`Unreachable.`)}async advancePlaylist(e){if(n(!e.done),!this.allTracksAreKnown(e))return;let t=this.trackDatas.filter(t=>e.tracks.includes(t.track));if(e.currentSegmentStartTimestamp===null){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let r=t.find(e=>e.info.type===`video`),i=t.find(e=>e.info.type===`audio`);for(;;){let a=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,s=0;if(r&&(!r.closed||r.packets.length>0)){let e=r.packets.every(e=>e.timestamp<a),t=null,c=null;if(e){if(!r.closed)return}else for(let e=0;e<r.packets.length;e++){let n=r.packets[e];if(t!==null&&n.timestamp>a)break;e>0&&n.type===`key`&&(t=n,c=e)}if(c!==null){if(o=c,i){let e=i.packets.findIndex(e=>e.timestamp>=t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}else{if(!r.closed)return;o=r.packets.length;let e=bt(r.packets,e=>e.timestamp),t=r.packets[e];if(n(t),i){if(t.timestamp<a){let e=i.packets.findIndex(e=>e.timestamp>=a);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}else{let e=i.packets.findIndex(e=>e.timestamp>t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}}}else if(i&&(!i.closed||i.packets.length>0)){if(i.packets.every(e=>e.timestamp<a)){if(i.closed)s=i.packets.length;else return}else{let e=Ce(i.packets,e=>e.timestamp<=a);s=Math.max(e,1)}}if(o===0&&s===0){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let c=null,l,u;n(this.output._target instanceof Wf);let d=this.output._target;if(this.singleFilePerPlaylist){if(e.singleFile===null){let t={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:qp(e)};l=await this.getSegmentPath(t),Gp(l),u=gt(gt(d.rootPath,e.path),l);let n=await this.output._getTarget({path:u,isRoot:!1,mimeType:e.segmentFormat.mimeType}),a=null;if(e.segmentFormat._isFragmentedIsobmff()){a={output:new hm({format:e.segmentFormat,target:n}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},n.on(`write`,({end:e})=>{a.currentFileSize=Math.max(a.currentFileSize,e)});let t=a.output._muxer;t.minimumFragmentDuration=1/0;let o=t.formatOptions.onMoof;t.formatOptions.onMoof=(e,n,r)=>{a.firstMoofPosition=n,o?.(e,n,r),t.formatOptions.onMoof=o},r&&(a.videoSource=new _p(r.track.source._codec),a.output.addVideoTrack(a.videoSource,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),i&&(a.audioSource=new Op(i.track.source._codec),a.output.addAudioTrack(a.audioSource,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),await a.output.start()}else n._start();e.singleFile={target:n,path:l,nextOffset:0,info:t,fragmentedIsobmffOutput:a}}else l=e.singleFile.path,u=gt(gt(d.rootPath,e.path),l)}else c={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:qp(e)},l=await this.getSegmentPath(c),Gp(l),u=gt(gt(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,m=-1/0,h=null,g=null,_=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,g=e.singleFile.fragmentedIsobmffOutput.videoSource,_=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new hm({format:e.segmentFormat,target:new Wf(u,async t=>{let n={...t,isRoot:!1};if(t.isRoot){if(e.singleFile){let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:e})=>f=Math.max(f,e)),t}{let e=await this.output._getTarget(n);return p=e,e.on(`write`,({end:e})=>f=Math.max(f,e)),e}}return this.output._getTarget(n)}),initTarget:async()=>{if(e.initSegment)return new Hf;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),t.on(`finalized`,()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),t}{let t=qp(e),n=await this.getInitPath(t);Kp(n),e.initSegment={path:n,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let r=gt(gt(d.rootPath,e.path),n),i=await this.output._getTarget({path:r,isRoot:!1,mimeType:e.segmentFormat.mimeType});return i.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),i.on(`finalized`,()=>{this.format._options.onInit?.(i,t)}),i}}}),r&&(g=new _p(r.track.source._codec),h.addVideoTrack(g,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),i&&(_=new Op(i.track.source._codec),h.addAudioTrack(_,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),await h.start()),r){n(g);let e={decoderConfig:r.info.decoderConfig};for(let t=0;t<o;t++){let n=r.packets[t];await g.add(n,e),m=Math.max(m,n.timestamp+n.duration)}}if(i){n(_);let e={decoderConfig:i.info.decoderConfig};for(let t=0;t<s;t++){let n=i.packets[t];await _.add(n,e),m=Math.max(m,n.timestamp+n.duration)}}e.singleFile?.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),f=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await h.finalize()}catch(e){throw await h?.cancel(),e}c&&(n(p),this.format._options.onSegment?.(p,c)),o>0&&(n(r),r.packets.splice(0,o)),s>0&&(n(i),i.packets.splice(0,s));let v=1/0;r&&r.packets.length>0&&(v=r.packets[0].timestamp),i&&i.packets.length>0&&(v=Math.min(v,i.packets[0].timestamp));let y=v<1/0?v:m;n(Number.isFinite(y));let b=y-e.currentSegmentStartTimestamp;if(n(b>=0),e.writtenSegments.push({path:l,duration:b,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:c??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,b),e.currentSegmentStartTimestamp=y,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let t=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(n(t.info),this.format._options.onSegmentPopped?.(t.path,t.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){n(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let t=e.writtenSegments,n=0,r=0,i=0;for(let e=0;e<t.length;e++){i+=t[e].duration;let r=0,a=0;for(let i=e;i<t.length&&(r+=t[i].byteSize,a+=t[i].duration,a>=.5*this.globalTargetDuration&&a<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*r/a)),!(a>1.5*this.globalTargetDuration));i++);}if(n===0)for(let e of t){let t=e.duration||1;n=Math.max(n,8*e.byteSize/t)}for(let e of t)r+=8*e.byteSize;let a=r/(i||1);if(t.length===0)for(let t of e.tracks){let e=this.trackDatas.find(e=>e.track===t),r=t.source._nominalBitrate??t.metadata.bitrate??0;if(a+=t.source._nominalBitrate??t.metadata.averageBitrate??0,r===0){let n=new z(`medium`);if(t.isVideoTrack()){let i=e?.info.decoderConfig;r=n._toVideoBitrate(t.source._codec,i?.codedWidth??1920,i?.codedHeight??1080)}else t.isAudioTrack()&&(r=n._toAudioBitrate(t.source._codec)??0)}n+=r}e.peakBitrate=n,e.averageBitrate=a}async writePlaylist(e){n(this.output._target instanceof Wf);let t=this.output._target;this.updatePlaylistBitrates(e);let r=!1;for(let t of e.writtenSegments)r||=t.byteOffset!==null;let i=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,a=3;(i||r)&&(a=4),e.initSegment&&(a=5),e.initSegment&&!i&&(a=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,s=gt(t.rootPath,e.path),c=`#EXTM3U
|
|
528
528
|
#EXT-X-VERSION:${a}\n`+(this.isLive?``:`#EXT-X-PLAYLIST-TYPE:VOD
|
|
529
529
|
`)+`#EXT-X-TARGETDURATION:${Math.ceil(o)}\n`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}\n`:``)+`#EXT-X-INDEPENDENT-SEGMENTS
|
|
530
530
|
`+(i?`#EXT-X-I-FRAMES-ONLY
|
|
@@ -532,13 +532,13 @@ const zp=e=>e===`opus`?`Opus`:e;var Bp=class extends Fu{constructor(e,t){if(!(e.
|
|
|
532
532
|
`:``)+`
|
|
533
533
|
`+e.writtenSegments.map(e=>`#EXTINF:${+e.duration.toFixed(12)},\n`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${(/* @__PURE__ */ new Date(1e3*e.timestamp)).toISOString()}\n`:``)+(e.byteOffset===null?``:`#EXT-X-BYTERANGE:${e.byteSize}@${e.byteOffset}\n`)+`${e.path}\n`).join(``)+(e.done?(e.writtenSegments.length>0?`
|
|
534
534
|
`:``)+`#EXT-X-ENDLIST
|
|
535
|
-
`:``);this.format._options.onPlaylist?.(c,
|
|
536
|
-
`,r=!1,i=null,a=0,o=!1;for(let e of this.playlistDeclarations)if(e.groupId===null){let i=e.playlist.tracks[0].isVideoTrack()&&e.playlist.tracks[0].metadata.hasOnlyKeyPackets,a=[];for(let t of e.playlist.tracks){let e=this.trackDatas.find(e=>e.track===t)?.info.decoderConfig.codec??t.source._codec;a.push(
|
|
535
|
+
`:``);this.format._options.onPlaylist?.(c,qp(e));let l=new Mf(await this.output._getTarget({path:s,isRoot:!1,mimeType:ko}),!0);l.start(),l.write(T.encode(c)),await l.flush(),await l.finalize()}async writeMasterPlaylist(){n(this.output._target instanceof Wf);let e=this.output._target,t=`#EXTM3U
|
|
536
|
+
`,r=!1,i=null,a=0,o=!1;for(let e of this.playlistDeclarations)if(e.groupId===null){let i=e.playlist.tracks[0].isVideoTrack()&&e.playlist.tracks[0].metadata.hasOnlyKeyPackets,a=[];for(let t of e.playlist.tracks){let e=this.trackDatas.find(e=>e.track===t)?.info.decoderConfig.codec??t.source._codec;a.push(Hp(e))}let o=0,s=0;if(e.references.length>0){let t=e.references[0].playlist.tracks[0],r=this.trackDatas.find(e=>e.track===t)?.info.decoderConfig.codec??t.source._codec;a.push(Hp(r));for(let t of e.references)n(t.playlist.peakBitrate!==null),o=Math.max(o,t.playlist.peakBitrate),s=Math.max(s,t.playlist.averageBitrate??0)}n(e.playlist.peakBitrate!==null);let c=e.playlist.peakBitrate+o,l=(e.playlist.averageBitrate??0)+s;r||=(t+=`
|
|
537
537
|
`,!0),t+=i?`#EXT-X-I-FRAME-STREAM-INF:`:`#EXT-X-STREAM-INF:`,t+=`BANDWIDTH=${Math.ceil(c)}`,l>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(l)}`),t+=`,CODECS="${a.join(`,`)}"`;let u=e.playlist.tracks.find(e=>e.isVideoTrack());if(u?.isVideoTrack()){let e=this.trackDatas.find(e=>e.track===u)?.info.decoderConfig;if(e){let n=e.displayAspectWidth??e.codedWidth,r=e.displayAspectHeight??e.codedHeight;n!==void 0&&r!==void 0&&(u.metadata.rotation!==void 0&&u.metadata.rotation%180==90&&([n,r]=[r,n]),t+=`,RESOLUTION=${n}x${r}`)}!i&&u.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+u.metadata.frameRate.toFixed(3)}`)}if(!i){let r=/* @__PURE__ */ new Map;for(let t of e.references){n(t.groupId!==null);let e=t.playlist.tracks[0].type;r.set(e,t.groupId)}for(let[e,n]of r)t+=`,${e.toUpperCase()}="${n}"`}i?(t+=`,URI="${e.playlist.path}"`,t+=`
|
|
538
538
|
`):(t+=`
|
|
539
539
|
`,t+=`${e.playlist.path}\n`)}else{n(e.playlist.tracks.length===1);let r=e.playlist.tracks[0],s=r.type,c=r.metadata.name??null,l=r.metadata.languageCode,u=r.metadata.disposition;(i===null||e.groupId!==i)&&(a=0,t+=`
|
|
540
540
|
`,o=!1),i=e.groupId,a++,t+=`#EXT-X-MEDIA:TYPE=${s.toUpperCase()},GROUP-ID="${e.groupId}"`,c!==null&&/[\n\r"]/.test(c)&&(A._warn(`Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes.`),c=null),c??=`${l??e.groupId}-${a}`,t+=`,NAME="${c}"`,l!==void 0&&(t+=`,LANGUAGE="${l}"`);let d=u?.primary??!1,f=u?.default??!0,p=u?.forced??!1;if(d&&!o&&(t+=`,DEFAULT=YES`,o=!0),(d||f)&&(t+=`,AUTOSELECT=YES`),p&&(t+=`,FORCED=YES`),s===`audio`){let e=this.trackDatas.find(e=>e.track===r)?.info.decoderConfig;e&&(t+=`,CHANNELS="${e.numberOfChannels}"`)}e.noUri||(t+=`,URI="${e.playlist.path}"`),t+=`
|
|
541
|
-
`}this.format._options.onMaster?.(t);let s=await this.mutex.acquire();try{let n;this.numWrittenMasterPlaylists===0?n=await this.output._getRootWriter(!0):(n=new
|
|
541
|
+
`}this.format._options.onMaster?.(t);let s=await this.mutex.acquire();try{let n;this.numWrittenMasterPlaylists===0?n=await this.output._getRootWriter(!0):(n=new Mf(await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:ko}),!0),n.start()),n.write(T.encode(t)),await n.flush(),await n.finalize(),this.numWrittenMasterPlaylists++}finally{s()}}async tryWriteMasterPlaylist(){n(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(e=>e.mutex.acquire()))).forEach(e=>e());for(let e of this.trackDatas)e.closed=!0;await Promise.all(this.playlists.map(e=>e.done?Promise.resolve():this.advancePlaylist(e))),this.isLive||await this.writeMasterPlaylist()}};const Wp=e=>{if(typeof e!=`string`)throw TypeError(`options.getPlaylistPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Playlist paths cannot contain line feed, carriage return, or double quote characters.`)},Gp=e=>{if(typeof e!=`string`)throw TypeError(`options.getSegmentPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Segment paths cannot contain line feed or carriage return characters.`)},Kp=e=>{if(typeof e!=`string`)throw TypeError(`options.getInitPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Init paths cannot contain line feed, carriage return, or double quote characters.`)},qp=e=>({n:e.id,tracks:e.tracks,segmentFormat:e.segmentFormat});
|
|
542
542
|
/*!
|
|
543
543
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
544
544
|
*
|
|
@@ -546,7 +546,7 @@ const zp=e=>e===`opus`?`Opus`:e;var Bp=class extends Fu{constructor(e,t){if(!(e.
|
|
|
546
546
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
547
547
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
548
548
|
*/
|
|
549
|
-
var Gp=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>N.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>F.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Dr.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Kp=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!ht(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new qf(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},qp=class extends Kp{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...N,...Er,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dr]}_codecUnsupportedHint(e){return new Yp().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Jp=class extends Kp{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...N,...Er,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dr]}},Yp=class extends Kp{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...N,...F]}_codecUnsupportedHint(e){return new qp().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Xp=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);if(e.minimumClusterDuration!==void 0&&(!ht(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw TypeError(`options.minimumClusterDuration, when provided, must be a non-negative number.`);if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!=`function`)throw TypeError(`options.onEbmlHeader, when provided, must be a function.`);if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);if(e.onCluster!==void 0&&typeof e.onCluster!=`function`)throw TypeError(`options.onCluster, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Zf(e,this)}get _name(){return`Matroska`}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return`.mkv`}get mimeType(){return`video/x-matroska`}getSupportedCodecs(){return[...N,...Er,...P.filter(e=>![`pcm-s8`,`pcm-f32be`,`pcm-f64be`,`ulaw`,`alaw`].includes(e)),...Dr]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},Zp=class extends Xp{constructor(e){super(e)}getSupportedCodecs(){return[...N.filter(e=>[`vp8`,`vp9`,`av1`].includes(e)),...F.filter(e=>[`opus`,`vorbis`].includes(e)),...Dr]}get _name(){return`WebM`}get fileExtension(){return`.webm`}get mimeType(){return`video/webm`}_codecUnsupportedHint(e){return new Xp().getSupportedCodecs().includes(e)?` Switching to MKV will grant support for this codec.`:``}},Qp=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.xingHeader!==void 0&&typeof e.xingHeader!=`boolean`)throw TypeError(`options.xingHeader, when provided, must be a boolean.`);if(e.onXingFrame!==void 0&&typeof e.onXingFrame!=`function`)throw TypeError(`options.onXingFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new $f(e,this)}get _name(){return`MP3`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.mp3`}get mimeType(){return`audio/mpeg`}getSupportedCodecs(){return[`mp3`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},$p=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.large!==void 0&&typeof e.large!=`boolean`)throw TypeError(`options.large, when provided, must be a boolean.`);if(e.metadataFormat!==void 0&&![`info`,`id3`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'info' or 'id3'.`);if(e.onHeader!==void 0&&typeof e.onHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new lp(e,this)}get _name(){return`WAVE`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.wav`}get mimeType(){return`audio/wav`}getSupportedCodecs(){return[...P.filter(e=>[`pcm-s16`,`pcm-s24`,`pcm-s32`,`pcm-f32`,`pcm-f64`,`pcm-u8`,`ulaw`,`alaw`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},em=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.maximumPageDuration!==void 0&&(!ht(e.maximumPageDuration)||e.maximumPageDuration<=0))throw TypeError(`options.maximumPageDuration, when provided, must be a positive number.`);if(e.onPage!==void 0&&typeof e.onPage!=`function`)throw TypeError(`options.onPage, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new ep(e,this)}get _name(){return`Ogg`}getSupportedTrackCounts(){let e=2**32;return{video:{min:0,max:0},audio:{min:0,max:e},subtitle:{min:0,max:0},total:{min:0,max:e}}}get fileExtension(){return`.ogg`}get mimeType(){return`application/ogg`}getSupportedCodecs(){return[...F.filter(e=>[`vorbis`,`opus`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`none`}},tm=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onFrame!==void 0&&typeof e.onFrame!=`function`)throw TypeError(`options.onFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Iu(e,this)}get _name(){return`ADTS`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.aac`}get mimeType(){return`audio/aac`}getSupportedCodecs(){return[`aac`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},nm=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);super(),this._options=e}_createMuxer(e){return new Ru(e,this)}get _name(){return`FLAC`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.flac`}get mimeType(){return`audio/flac`}getSupportedCodecs(){return[`flac`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},rm=class extends Gp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onPacket!==void 0&&typeof e.onPacket!=`function`)throw TypeError(`options.onPacket, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new rp(e,this)}get _name(){return`MPEG-TS`}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return`.ts`}get mimeType(){return`video/MP2T`}getSupportedCodecs(){return[...N.filter(e=>[`avc`,`hevc`].includes(e)),...F.filter(e=>[`aac`,`mp3`,`ac3`,`eac3`,`dts`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},im=class extends Gp{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.segmentFormat instanceof Gp)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(e=>e instanceof Gp)))throw TypeError(`options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.`);if(e.targetDuration!==void 0&&(typeof e.targetDuration!=`number`||e.targetDuration<=0))throw TypeError(`options.targetDuration, when provided, must be a positive number.`);if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!=`boolean`)throw TypeError(`options.singleFilePerPlaylist, when provided, must be a boolean.`);if(e.live!==void 0&&typeof e.live!=`boolean`)throw TypeError(`options.live, when provided, must be a boolean.`);if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!=`number`||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw TypeError(`options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.`);if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!=`function`)throw TypeError(`options.getPlaylistPath, when provided, must be a function.`);if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!=`function`)throw TypeError(`options.getSegmentPath, when provided, must be a function.`);if(e.getInitPath!==void 0&&typeof e.getInitPath!=`function`)throw TypeError(`options.getInitPath, when provided, must be a function.`);if(e.onMaster!==void 0&&typeof e.onMaster!=`function`)throw TypeError(`options.onMaster, when provided, must be a function.`);if(e.onPlaylist!==void 0&&typeof e.onPlaylist!=`function`)throw TypeError(`options.onPlaylist, when provided, must be a function.`);if(e.onSegment!==void 0&&typeof e.onSegment!=`function`)throw TypeError(`options.onSegment, when provided, must be a function.`);if(e.onInit!==void 0&&typeof e.onInit!=`function`)throw TypeError(`options.onInit, when provided, must be a function.`);if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!=`function`)throw TypeError(`options.onSegmentPopped, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Bp(e,this)}get _name(){return`HTTP Live Streaming (HLS)`}get fileExtension(){return`.m3u8`}get mimeType(){return Oo}getSupportedCodecs(){return[...new Set(Nt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,n=!1;for(let r of Nt(this._options.segmentFormat)){let i=r.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0,n||=i.subtitle.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Nt(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let e=Nt(this._options.segmentFormat);return e.some(e=>e.negativeTimestampSupport===`none`)?`none`:e.some(e=>e.negativeTimestampSupport===`prefer-non-negative`)?`prefer-non-negative`:e.some(e=>e.negativeTimestampSupport===`full`)?`full`:null}_codecUnsupportedHint(e){return` Using different segment formats may grant support for this codec.`}};
|
|
549
|
+
var Jp=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>N.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>F.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Dr.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Yp=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!ht(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new Jf(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Xp=class extends Yp{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...N,...Er,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dr]}_codecUnsupportedHint(e){return new Qp().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Zp=class extends Yp{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...N,...Er,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dr]}},Qp=class extends Yp{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...N,...F]}_codecUnsupportedHint(e){return new Xp().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},$p=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);if(e.minimumClusterDuration!==void 0&&(!ht(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw TypeError(`options.minimumClusterDuration, when provided, must be a non-negative number.`);if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!=`function`)throw TypeError(`options.onEbmlHeader, when provided, must be a function.`);if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);if(e.onCluster!==void 0&&typeof e.onCluster!=`function`)throw TypeError(`options.onCluster, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Qf(e,this)}get _name(){return`Matroska`}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return`.mkv`}get mimeType(){return`video/x-matroska`}getSupportedCodecs(){return[...N,...Er,...P.filter(e=>![`pcm-s8`,`pcm-f32be`,`pcm-f64be`,`ulaw`,`alaw`].includes(e)),...Dr]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},em=class extends $p{constructor(e){super(e)}getSupportedCodecs(){return[...N.filter(e=>[`vp8`,`vp9`,`av1`].includes(e)),...F.filter(e=>[`opus`,`vorbis`].includes(e)),...Dr]}get _name(){return`WebM`}get fileExtension(){return`.webm`}get mimeType(){return`video/webm`}_codecUnsupportedHint(e){return new $p().getSupportedCodecs().includes(e)?` Switching to MKV will grant support for this codec.`:``}},tm=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.xingHeader!==void 0&&typeof e.xingHeader!=`boolean`)throw TypeError(`options.xingHeader, when provided, must be a boolean.`);if(e.onXingFrame!==void 0&&typeof e.onXingFrame!=`function`)throw TypeError(`options.onXingFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new ep(e,this)}get _name(){return`MP3`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.mp3`}get mimeType(){return`audio/mpeg`}getSupportedCodecs(){return[`mp3`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},nm=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.large!==void 0&&typeof e.large!=`boolean`)throw TypeError(`options.large, when provided, must be a boolean.`);if(e.metadataFormat!==void 0&&![`info`,`id3`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'info' or 'id3'.`);if(e.onHeader!==void 0&&typeof e.onHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new up(e,this)}get _name(){return`WAVE`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.wav`}get mimeType(){return`audio/wav`}getSupportedCodecs(){return[...P.filter(e=>[`pcm-s16`,`pcm-s24`,`pcm-s32`,`pcm-f32`,`pcm-f64`,`pcm-u8`,`ulaw`,`alaw`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},rm=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.maximumPageDuration!==void 0&&(!ht(e.maximumPageDuration)||e.maximumPageDuration<=0))throw TypeError(`options.maximumPageDuration, when provided, must be a positive number.`);if(e.onPage!==void 0&&typeof e.onPage!=`function`)throw TypeError(`options.onPage, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new tp(e,this)}get _name(){return`Ogg`}getSupportedTrackCounts(){let e=2**32;return{video:{min:0,max:0},audio:{min:0,max:e},subtitle:{min:0,max:0},total:{min:0,max:e}}}get fileExtension(){return`.ogg`}get mimeType(){return`application/ogg`}getSupportedCodecs(){return[...F.filter(e=>[`vorbis`,`opus`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`none`}},im=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onFrame!==void 0&&typeof e.onFrame!=`function`)throw TypeError(`options.onFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Lu(e,this)}get _name(){return`ADTS`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.aac`}get mimeType(){return`audio/aac`}getSupportedCodecs(){return[`aac`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},am=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);super(),this._options=e}_createMuxer(e){return new zu(e,this)}get _name(){return`FLAC`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.flac`}get mimeType(){return`audio/flac`}getSupportedCodecs(){return[`flac`]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},om=class extends Jp{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onPacket!==void 0&&typeof e.onPacket!=`function`)throw TypeError(`options.onPacket, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new ip(e,this)}get _name(){return`MPEG-TS`}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return`.ts`}get mimeType(){return`video/MP2T`}getSupportedCodecs(){return[...N.filter(e=>[`avc`,`hevc`].includes(e)),...F.filter(e=>[`aac`,`mp3`,`ac3`,`eac3`,`dts`].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`prefer-non-negative`}},sm=class extends Jp{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.segmentFormat instanceof Jp)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(e=>e instanceof Jp)))throw TypeError(`options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.`);if(e.targetDuration!==void 0&&(typeof e.targetDuration!=`number`||e.targetDuration<=0))throw TypeError(`options.targetDuration, when provided, must be a positive number.`);if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!=`boolean`)throw TypeError(`options.singleFilePerPlaylist, when provided, must be a boolean.`);if(e.live!==void 0&&typeof e.live!=`boolean`)throw TypeError(`options.live, when provided, must be a boolean.`);if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!=`number`||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw TypeError(`options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.`);if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!=`function`)throw TypeError(`options.getPlaylistPath, when provided, must be a function.`);if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!=`function`)throw TypeError(`options.getSegmentPath, when provided, must be a function.`);if(e.getInitPath!==void 0&&typeof e.getInitPath!=`function`)throw TypeError(`options.getInitPath, when provided, must be a function.`);if(e.onMaster!==void 0&&typeof e.onMaster!=`function`)throw TypeError(`options.onMaster, when provided, must be a function.`);if(e.onPlaylist!==void 0&&typeof e.onPlaylist!=`function`)throw TypeError(`options.onPlaylist, when provided, must be a function.`);if(e.onSegment!==void 0&&typeof e.onSegment!=`function`)throw TypeError(`options.onSegment, when provided, must be a function.`);if(e.onInit!==void 0&&typeof e.onInit!=`function`)throw TypeError(`options.onInit, when provided, must be a function.`);if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!=`function`)throw TypeError(`options.onSegmentPopped, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Up(e,this)}get _name(){return`HTTP Live Streaming (HLS)`}get fileExtension(){return`.m3u8`}get mimeType(){return ko}getSupportedCodecs(){return[...new Set(Nt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,n=!1;for(let r of Nt(this._options.segmentFormat)){let i=r.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0,n||=i.subtitle.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Nt(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let e=Nt(this._options.segmentFormat);return e.some(e=>e.negativeTimestampSupport===`none`)?`none`:e.some(e=>e.negativeTimestampSupport===`prefer-non-negative`)?`prefer-non-negative`:e.some(e=>e.negativeTimestampSupport===`full`)?`full`:null}_codecUnsupportedHint(e){return` Using different segment formats may grant support for this codec.`}};
|
|
550
550
|
/*!
|
|
551
551
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
552
552
|
*
|
|
@@ -554,7 +554,7 @@ var Gp=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransf
|
|
|
554
554
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
555
555
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
556
556
|
*/
|
|
557
|
-
const am=[`video`,`audio`,`subtitle`];var om=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=Nt(this.metadata.group),r=Nt(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},sm=class extends om{constructor(e,t,n,r){super(e,t,`video`,n,r)}},cm=class extends om{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},lm=class extends om{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},um=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}};const dm=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ue(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Wt(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof um)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof um))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)};var fm=class extends Pt{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(k(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new um,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new me,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Gp))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Nf||e.target instanceof Uf))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Nf&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Nf)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Nf&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){n(this._target instanceof Uf);let t=this._target.getTarget(e),r=e=>{if(!(e instanceof Nf))throw TypeError(`getTarget must return a Target.`);return e};return k(t)?t.then(r):r(t)}async _getTarget(e){n(this._target instanceof Uf);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(n(this._initTarget!==null),this._initTarget instanceof Nf)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Nf)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return k(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new jf(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof mp))throw TypeError(`source must be a VideoSource.`);if(dm(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!=`boolean`)throw TypeError(`metadata.hasOnlyKeyPackets, when provided, must be a boolean.`);if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!=`boolean`)throw TypeError(`metadata.canBeTransparent, when provided, must be a boolean.`);if(t.decoderConfig!==void 0&&ei({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof I))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new sm(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof wp))throw TypeError(`source must be an AudioSource.`);if(dm(t),t.decoderConfig!==void 0&&ni({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof I))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new cm(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Lp))throw TypeError(`source must be a SubtitleSource.`);dm(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new lm(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Vt(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of am)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of am){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(A._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&A._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(A._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},pm=function(e,t,n){
|
|
557
|
+
const cm=[`video`,`audio`,`subtitle`];var lm=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=Nt(this.metadata.group),r=Nt(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},um=class extends lm{constructor(e,t,n,r){super(e,t,`video`,n,r)}},dm=class extends lm{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},fm=class extends lm{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},pm=class e{constructor(){this._pairedGroups=/* @__PURE__ */ new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}};const mm=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ue(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Wt(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof pm)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof pm))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)};var hm=class extends Pt{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(k(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new pm,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */ new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new me,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Jp))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Pf||e.target instanceof Wf))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Pf&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Pf)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Pf&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){n(this._target instanceof Wf);let t=this._target.getTarget(e),r=e=>{if(!(e instanceof Pf))throw TypeError(`getTarget must return a Target.`);return e};return k(t)?t.then(r):r(t)}async _getTarget(e){n(this._target instanceof Wf);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(n(this._initTarget!==null),this._initTarget instanceof Pf)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Pf)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return k(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Mf(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof hp))throw TypeError(`source must be a VideoSource.`);if(mm(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!=`boolean`)throw TypeError(`metadata.hasOnlyKeyPackets, when provided, must be a boolean.`);if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!=`boolean`)throw TypeError(`metadata.canBeTransparent, when provided, must be a boolean.`);if(t.decoderConfig!==void 0&&ei({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof I))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new um(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Dp))throw TypeError(`source must be an AudioSource.`);if(mm(t),t.decoderConfig!==void 0&&ni({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof I))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new dm(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Bp))throw TypeError(`source must be a SubtitleSource.`);mm(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new fm(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Vt(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of cm)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of cm){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(A._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&A._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(A._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},gm=function(e,t,n){
|
|
558
558
|
/*!
|
|
559
559
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
560
560
|
*
|
|
@@ -562,7 +562,7 @@ const am=[`video`,`audio`,`subtitle`];var om=class e{constructor(e,t,n,r,i){this
|
|
|
562
562
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
563
563
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
564
564
|
*/
|
|
565
|
-
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},mm=(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});const hm=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!N.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${N.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`options.video.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.video.quality and options.video.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.flip!==void 0&&typeof e.flip!=`boolean`)throw TypeError(`options.video.flip, when provided, must be a boolean.`);if(e?.allowTransformationMetadata!==void 0&&typeof e.allowTransformationMetadata!=`boolean`)throw TypeError(`options.video.allowTransformationMetadata, when provided, must be a boolean.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&xc(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e?.group!==void 0&&!(e.group instanceof um||Array.isArray(e.group)&&e.group.every(e=>e instanceof um)))throw TypeError(`options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},gm=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!F.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${F.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`options.audio.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.audio.quality and options.audio.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.sampleFormat))throw TypeError(`options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`);if(e?.group!==void 0&&!(e.group instanceof um||Array.isArray(e.group)&&e.group.every(e=>e instanceof um)))throw TypeError(`options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},_m=48e3;var vm=class e{get state(){return this._state}static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._state=`idle`,this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=/* @__PURE__ */ new Map,this._copyStartPackets=/* @__PURE__ */ new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new bm(this),this._totalDuration=null,this._maxTimestamps=/* @__PURE__ */ new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this._lastProcessedTime=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof ou))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof fm))throw TypeError(`options.output must be an Output.`);if(e.tracks!==void 0&&e.tracks!==`all`&&e.tracks!==`primary`)throw TypeError(`options.tracks, when provided, must be either 'all' or 'primary'.`);if(e.composable!==void 0&&typeof e.composable!=`boolean`)throw TypeError(`options.composable, when provided, must be a boolean.`);if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!=`object`)throw TypeError(`options.copy, when provided, must be an object or false.`);if(e.copy.mode!==void 0&&![`forced`,`preferred`].includes(e.copy.mode))throw TypeError(`options.copy.mode, when provided, must be 'forced' or 'preferred'.`);if(e.copy.shiftTolerance!==void 0&&(!ht(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw TypeError(`options.copy.shiftTolerance, when provided, must be a non-negative number.`);if(e.copy.boundaryPolicy!==void 0&&![`expand`,`shrink`].includes(e.copy.boundaryPolicy))throw TypeError(`options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.`);if(e.copy.boundaryTolerance!==void 0&&(!ht(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw TypeError(`options.copy.boundaryTolerance, when provided, must be a non-negative number.`)}let t=e.composable??!1;if(t){if(e.tags!==void 0)throw TypeError(`options.tags cannot be set by a composable conversion; set metadata directly on the output instead.`);if(e.output.state!==`pending`)throw TypeError(`options.output must not have been started yet.`)}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(e.video!==void 0&&typeof e.video!=`function`){if(Array.isArray(e.video))for(let t of e.video)hm(t);else hm(e.video)}if(e.audio!==void 0&&typeof e.audio!=`function`){if(Array.isArray(e.audio))for(let t of e.audio)gm(t);else gm(e.audio)}if(e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!ht(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&Vt(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??`preferred`,this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?`expand`:e.copy?.boundaryPolicy??`expand`,this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){let e=await this.input.getFormat(),t,r=this._options.tracks;r===void 0&&(r=e.name.includes(`(HLS)`)?`primary`:`all`),r===`all`?t=await this.input.getTracks():r===`primary`?t=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>e!==null):(Ee(r),n(!1));let i=this.output.format.getSupportedTrackCounts(),a=1,o=1,s=[],c=[];for(let e of t){let t;if(e.isVideoTrack()){if(this._options.video){if(typeof this._options.video==`function`){let n=await this._options.video(e,a)??{};if(Array.isArray(n))for(let e of n)hm(e);else hm(n);t=Array.isArray(n)?n:[n],a++}else t=Array.isArray(this._options.video)?this._options.video:[this._options.video]}else t=[{}]}else if(e.isAudioTrack()){if(this._options.audio){if(typeof this._options.audio==`function`){let n=await this._options.audio(e,o)??{};if(Array.isArray(n))for(let e of n)gm(e);else gm(n);t=Array.isArray(n)?n:[n],o++}else t=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio]}else t=[{}]}else n(!1);let r=t.filter(e=>e.discard);for(let t of r)this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:t});if(t.length===r.length){t.length===0&&this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:{}});continue}let i=t.filter(e=>!e.discard);s.push(e),c.push(i)}this._startTimestamp=this._options.trim?.start===void 0?Math.max(await this.input.getFirstTimestamp(s),0):this._options.trim.start,this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let e=0;e<s.length;e++){let t=s[e],r=c[e];for(let e of r){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:t,reason:`max_track_count_reached`,trackOptions:e});continue}if(this.output.tracks.reduce((e,n)=>e+ +(n.type===t.type),0)===i[t.type].max){this.discardedTracks.push({track:t,reason:`max_track_count_of_type_reached`,trackOptions:e});continue}let r=this._nextOutputTrackId++;t.isVideoTrack()?await this._processVideoTrack(t,e,r):t.isAudioTrack()?await this._processAudioTrack(t,e,r):n(!1)}}for(let e=0;e<this.utilizedTracks.length-1;e++)for(let t=e+1;t<this.utilizedTracks.length;t++){let r=this.utilizedTracks[e],i=this.utilizedTracks[t],a=this._outputOwnTrackGroups[e],o=this._outputOwnTrackGroups[t];n(a!==void 0),n(o!==void 0),a&&o&&r.canBePairedWith(i)&&a.pairWith(o)}if(!this._composable){let t=await this.input.getMetadataTags(),n;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(t):this._options.tags;Vt(e),n=e}else n=t;let r=e.mimeType===this.output.format.mimeType;t.raw===n.raw&&!r&&delete n.raw,this.output.setMetadataTags(n)}if(this.isValid=this._composable?!0:this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||(e.length>0&&e.push(`
|
|
565
|
+
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},_m=(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});const vm=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!N.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${N.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`options.video.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.video.quality and options.video.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.flip!==void 0&&typeof e.flip!=`boolean`)throw TypeError(`options.video.flip, when provided, must be a boolean.`);if(e?.allowTransformationMetadata!==void 0&&typeof e.allowTransformationMetadata!=`boolean`)throw TypeError(`options.video.allowTransformationMetadata, when provided, must be a boolean.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&Sc(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e?.group!==void 0&&!(e.group instanceof pm||Array.isArray(e.group)&&e.group.every(e=>e instanceof pm)))throw TypeError(`options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},ym=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!F.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${F.join(`, `)}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof z))throw TypeError(`options.audio.quality, when provided, must be a Quality.`);if(e?.quality!==void 0&&t!==void 0)throw TypeError(`options.audio.quality and options.audio.bitrate cannot both be provided.`);if(t!==void 0&&!(t instanceof z)&&(!Number.isInteger(t)||t<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.sampleFormat))throw TypeError(`options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`);if(e?.group!==void 0&&!(e.group instanceof pm||Array.isArray(e.group)&&e.group.every(e=>e instanceof pm)))throw TypeError(`options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},bm=48e3;var xm=class e{get state(){return this._state}static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._state=`idle`,this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=/* @__PURE__ */ new Map,this._copyStartPackets=/* @__PURE__ */ new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new Cm(this),this._totalDuration=null,this._maxTimestamps=/* @__PURE__ */ new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this._lastProcessedTime=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof su))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof hm))throw TypeError(`options.output must be an Output.`);if(e.tracks!==void 0&&e.tracks!==`all`&&e.tracks!==`primary`)throw TypeError(`options.tracks, when provided, must be either 'all' or 'primary'.`);if(e.composable!==void 0&&typeof e.composable!=`boolean`)throw TypeError(`options.composable, when provided, must be a boolean.`);if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!=`object`)throw TypeError(`options.copy, when provided, must be an object or false.`);if(e.copy.mode!==void 0&&![`forced`,`preferred`].includes(e.copy.mode))throw TypeError(`options.copy.mode, when provided, must be 'forced' or 'preferred'.`);if(e.copy.shiftTolerance!==void 0&&(!ht(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw TypeError(`options.copy.shiftTolerance, when provided, must be a non-negative number.`);if(e.copy.boundaryPolicy!==void 0&&![`expand`,`shrink`].includes(e.copy.boundaryPolicy))throw TypeError(`options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.`);if(e.copy.boundaryTolerance!==void 0&&(!ht(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw TypeError(`options.copy.boundaryTolerance, when provided, must be a non-negative number.`)}let t=e.composable??!1;if(t){if(e.tags!==void 0)throw TypeError(`options.tags cannot be set by a composable conversion; set metadata directly on the output instead.`);if(e.output.state!==`pending`)throw TypeError(`options.output must not have been started yet.`)}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(e.video!==void 0&&typeof e.video!=`function`){if(Array.isArray(e.video))for(let t of e.video)vm(t);else vm(e.video)}if(e.audio!==void 0&&typeof e.audio!=`function`){if(Array.isArray(e.audio))for(let t of e.audio)ym(t);else ym(e.audio)}if(e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!ht(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&Vt(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??`preferred`,this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?`expand`:e.copy?.boundaryPolicy??`expand`,this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){let e=await this.input.getFormat(),t,r=this._options.tracks;r===void 0&&(r=e.name.includes(`(HLS)`)?`primary`:`all`),r===`all`?t=await this.input.getTracks():r===`primary`?t=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>e!==null):(Ee(r),n(!1));let i=this.output.format.getSupportedTrackCounts(),a=1,o=1,s=[],c=[];for(let e of t){let t;if(e.isVideoTrack()){if(this._options.video){if(typeof this._options.video==`function`){let n=await this._options.video(e,a)??{};if(Array.isArray(n))for(let e of n)vm(e);else vm(n);t=Array.isArray(n)?n:[n],a++}else t=Array.isArray(this._options.video)?this._options.video:[this._options.video]}else t=[{}]}else if(e.isAudioTrack()){if(this._options.audio){if(typeof this._options.audio==`function`){let n=await this._options.audio(e,o)??{};if(Array.isArray(n))for(let e of n)ym(e);else ym(n);t=Array.isArray(n)?n:[n],o++}else t=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio]}else t=[{}]}else n(!1);let r=t.filter(e=>e.discard);for(let t of r)this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:t});if(t.length===r.length){t.length===0&&this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:{}});continue}let i=t.filter(e=>!e.discard);s.push(e),c.push(i)}this._startTimestamp=this._options.trim?.start===void 0?Math.max(await this.input.getFirstTimestamp(s),0):this._options.trim.start,this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let e=0;e<s.length;e++){let t=s[e],r=c[e];for(let e of r){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:t,reason:`max_track_count_reached`,trackOptions:e});continue}if(this.output.tracks.reduce((e,n)=>e+ +(n.type===t.type),0)===i[t.type].max){this.discardedTracks.push({track:t,reason:`max_track_count_of_type_reached`,trackOptions:e});continue}let r=this._nextOutputTrackId++;t.isVideoTrack()?await this._processVideoTrack(t,e,r):t.isAudioTrack()?await this._processAudioTrack(t,e,r):n(!1)}}for(let e=0;e<this.utilizedTracks.length-1;e++)for(let t=e+1;t<this.utilizedTracks.length;t++){let r=this.utilizedTracks[e],i=this.utilizedTracks[t],a=this._outputOwnTrackGroups[e],o=this._outputOwnTrackGroups[t];n(a!==void 0),n(o!==void 0),a&&o&&r.canBePairedWith(i)&&a.pairWith(o)}if(!this._composable){let t=await this.input.getMetadataTags(),n;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(t):this._options.tags;Vt(e),n=e}else n=t;let r=e.mimeType===this.output.format.mimeType;t.raw===n.raw&&!r&&delete n.raw,this.output.setMetadataTags(n)}if(this.isValid=this._composable?!0:this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||(e.length>0&&e.push(`
|
|
566
566
|
|
|
567
567
|
`),e.push(this._getInvalidityExplanation().join(``))),e.length>0&&A._warn(...e)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push(`Due to missing tracks, this conversion cannot be executed.`);else{let t=this.discardedTracks.every(e=>e.reason===`discarded_by_user`||e.reason===`no_encodable_target_codec`)&&this.discardedTracks.some(e=>e.reason===`no_encodable_target_codec`);if(e.push(`Due to discarded tracks, this conversion cannot be executed.`),t){let t=this.discardedTracks.flatMap(e=>{if(e.reason===`discarded_by_user`)return[];let t;return t=e.track.type===`video`?this.output.format.getSupportedVideoCodecs():e.track.type===`audio`?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs(),t.filter(t=>!e.trackOptions.codec||t===e.trackOptions.codec)}),n=[...new Set(t)];n.length===1?e.push(`\nTracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):e.push(`
|
|
568
568
|
Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(e=>`'${e}'`).join(`, `)} with the provided parameters.`),n.includes(`mp3`)&&e.push(`
|
|
@@ -571,7 +571,7 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
|
|
|
571
571
|
The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes(`flac`)&&e.push(`
|
|
572
572
|
The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
|
|
573
573
|
Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.until!==void 0&&(typeof e.until!=`number`||Number.isNaN(e.until)))throw TypeError(`options.until, when provided, must be a number.`);if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw TypeError(`options.pauseSignal, when provided, must be an AbortSignal.`);if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
|
|
574
|
-
`+this._getInvalidityExplanation().join(``));if(this._state===`executing`)throw Error(`Cannot call execute() while a previous call to execute() is still running.`);if(this._state===`canceled`)throw new ym;if(this._state===`done`)return;if(this._composable&&this.output.state===`pending`)throw Error(`A composable conversion requires the output to be started. Call start() on the output before executing the conversion.`);this._state=`executing`,this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{this._state===`executing`&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener(`abort`,t);for(let e of this._trackPumps)e.done||(e.resolvers=D());if(this._executed)for(let e of this._trackPumps)e.wake?.();else{this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async e=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let e of this._trackPumps)e.start()}try{await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){throw this._state!==`canceled`&&this.cancel(),e}finally{e.pauseSignal?.removeEventListener(`abort`,t)}if(this._state===`canceled`)throw new ym;let n=this._trackPumps.every(e=>e.done);this._state=n?`done`:`idle`,n&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!==`done`){if(this._state===`canceled`){A._warn(`Conversion already canceled.`);return}this._state=`canceled`;for(let e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let a,o=await e.getRotation(),s=await e.getFlip(),{rotation:c,flip:l}=m(o,s,t.rotate??0,t.flip??!1),u=c,d=l,f=t.rotate||t.flip?null:await e.getTransformationMatrix(),p=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),h=await e.getSquarePixelWidth(),g=await e.getSquarePixelHeight(),[_,v]=c%180==0?[h,g]:[g,h],y=t.crop;y&&=bc(y,_,v);let[b,x]=y?[y.width,y.height]:[_,v],S=b,C=x,ee=S/C;t.width!==void 0&&t.height===void 0?(S=Ft(t.width),C=Ft(Math.round(S/ee))):t.width===void 0&&t.height!==void 0?(C=Ft(t.height),S=Ft(Math.round(C*ee))):t.width!==void 0&&t.height!==void 0&&(S=Ft(t.width),C=Ft(t.height));let te=this.output.format.getSupportedVideoCodecs(),w=t.alpha??`discard`,T=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!te.includes(i)||t.codec&&t.codec!==i||S!==b||C!==x||c!==0&&!p||l&&!p||!!y,ne=null;if(!T){let t=new Nl(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});if(n&&n.timestamp<this._startTimestamp&&n.timestamp+n.duration<=this._startTimestamp&&this._copyBoundaryPolicy===`shrink`&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0})),ne=n,n){let e=this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp,this._startTimestamp):n.timestamp;if((this._copyBoundaryPolicy===`shrink`?e-this._startTimestamp:Math.max(this._startTimestamp-e,0))>this._copyBoundaryTolerance)T=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)e+this._timestampOffset!==0&&(T=!0);else{let t=O(this._startTimestamp-e,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);e+t===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+t,this._timestampOffsetAdjusted=!0):T=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&e<this._startTimestamp){let t=Math.min(this._startTimestamp-e,this._copyTimestampShiftTolerance);e+t>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+t):T=!0}}}if(T&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(T){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(te=te.filter(e=>e===t.codec));let i=sl(t.quality,t.bitrate)??new z(`high`),o=await pl(te,{width:t.process&&t.processedWidth?t.processedWidth:S,height:t.process&&t.processedHeight?t.processedHeight:C,quality:i});if(!o){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let s={codec:o,quality:i,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:w,hardwareAcceleration:t.hardwareAcceleration,transform:{}};n(s.transform);let m=S!==b||C!==x||c!==0&&(!p||t.process!==void 0)||l&&(!p||t.process!==void 0)||!!y||h!==await e.getCodedWidth()||g!==await e.getCodedHeight();if(!m){let t={stack:[],error:void 0,hasError:!1};try{let n=new fm({format:new qp,target:new Vf}),r=new xp(s);n.addVideoTrack(r),await n.start();let i=pm(t,await new Vl(e).getSample(await e.getFirstTimestamp()),!1);if(i)try{await r.add(i),i.close(),await n.finalize()}catch(e){A._warn(`An error occurred when probing encoder support. Falling back to rerender path.`,e),n.cancel(),m=!0,s.transform.force=!0}else await n.cancel()}catch(e){t.error=e,t.hasError=!0}finally{mm(t)}}t.frameRate&&(s.transform.frameRate=t.frameRate),t.process&&(s.transform.process=t.process),m&&(u=0,d=!1,f=null,s.transform.width=S,s.transform.height=C,s.transform.fit=t.fit??`fill`,s.transform.rotate=t.rotate,s.transform.flip=t.flip,s.transform.crop=y,s.transform.alpha=w);let _=null;s.onEncodedSample=e=>{_=e.timestamp};let v=new xp(s);a=v,this._registerTrackPump(async t=>{let n=new Vl(e);for await(let e of n.samples(this._startTimestamp,this._endTimestamp)){let n={stack:[],error:void 0,hasError:!1};try{let i=pm(n,e,!1);if(this._state===`canceled`)break;let a=Math.max(this._startTimestamp,i.timestamp),o=Math.min(this._endTimestamp,i.timestamp+i.duration);if(a>=o)continue;i.setTimestamp(a+this._timestampOffset),i.setDuration(o-a),this._updateProgress(r,i.timestamp+i.duration),await v.add(i),i.close(),_!==null&&(this._synchronizer.shouldWait(r,_)&&await this._synchronizer.wait(_),await this._checkpoint(t,_))}catch(e){n.error=e,n.hasError=!0}finally{mm(n)}}v.close(),this._closeTrack(r)})}else{let t=new gp(i);a=t,this._registerTrackPump(async n=>{let i=new Nl(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(ne)for await(let e of i.packets(ne,void 0,{verifyKeyPackets:!0})){if(this._state===`canceled`)break;if(e.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy===`shrink`)break;{let t=e,n=!1;for(let e=0;e<6;e++){let e=await i.getNextPacket(t,{metadataOnly:!0});if(!e)break;if(e.timestamp<this._endTimestamp){n=!0;break}t=e}if(!n)break}}let s=e.timestamp,c=e.timestamp+e.duration;this._copyBoundaryPolicy===`shrink`&&(s=Math.max(s,this._startTimestamp),c=Math.min(c,this._endTimestamp),c=Math.max(c,s)),s+=this._timestampOffset,c+=this._timestampOffset;let l=e.type;l===`key`&&o!==null&&s<o&&(l=`delta`),o=Math.max(o??-1/0,s);let u=e.clone({timestamp:s,duration:c-s,sideData:w===`discard`?{}:e.sideData,type:l});this._updateProgress(r,u.timestamp+u.duration),await t.add(u,a),this._synchronizer.shouldWait(r,u.timestamp)&&await this._synchronizer.wait(u.timestamp),await this._checkpoint(n,u.timestamp)}t.close(),this._closeTrack(r)})}let re=null;!t.group&&!this._composable&&(re=new um);let ie=await e.getLanguageCode(),ae=await e.getName(),oe=await e.getDisposition(),se=T?null:await e.getBitrate(),ce=T?null:await e.getAverageBitrate(),le=w===`keep`&&await e.canBeTransparent();this.output.addVideoTrack(a,{frameRate:t.frameRate,languageCode:Ue(ie)?ie:void 0,name:ae??void 0,disposition:oe,rotation:u,flip:d,transformationMatrix:f??void 0,canBeTransparent:le,group:re??t.group,bitrate:se??void 0,averageBitrate:ce??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(re)}async _processAudioTrack(e,t,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let a,o=await e.getNumberOfChannels(),s=await e.getSampleRate(),c=t.numberOfChannels??o,l=t.sampleRate??s,u=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||c!==o||l!==s||!u.includes(i)||!!t.codec&&t.codec!==i||t.process!==void 0||t.sampleFormat!==void 0,f=null;if(!d){let t=new Nl(e),n=await t.getKeyPacket(this._startTimestamp)??await t.getFirstKeyPacket();n&&(this._copyBoundaryPolicy===`shrink`&&n.timestamp<this._startTimestamp||this._copyBoundaryPolicy===`expand`&&n.timestamp+n.duration<=this._startTimestamp)&&(n=await t.getNextKeyPacket(n));let r=Er.includes(i)&&i!==`flac`;if(n&&this._copyBoundaryPolicy===`expand`&&r){let r=await t.getKeyPacket(n.timestamp-1/await e.getTimeResolution());r&&(n=r)}if(f=n,n){if((this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-n.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)n.timestamp+this._timestampOffset!==0&&(d=!0);else{let e=O(this._startTimestamp-n.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);n.timestamp+e===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+e,this._timestampOffsetAdjusted=!0):d=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&n.timestamp<this._startTimestamp){let e=Math.min(this._startTimestamp-n.timestamp,this._copyTimestampShiftTolerance);n.timestamp+e>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+e):d=!0}}}if(d&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(d){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}let i=null;t.codec&&(u=u.filter(e=>e===t.codec));let d=sl(t.quality,t.bitrate)??new z(`high`),f=await dl(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:l,quality:d});if(!f.some(e=>Er.includes(e))&&u.some(e=>Er.includes(e))&&(c!==2||l!==_m)){let e=(await dl(u,{numberOfChannels:2,sampleRate:_m,quality:d})).find(e=>Er.includes(e));e&&(i=e,c=2,l=_m)}else i=f[0]??null;if(i===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let p={codec:i,quality:d,transform:{sampleFormat:t.sampleFormat,process:t.process}};n(p.transform),c!==o&&(p.transform.numberOfChannels=c),l!==s&&(p.transform.sampleRate=l);let m=null;p.onEncodedSample=e=>{m=e.timestamp};let h=new Dp(p);a=h,this._registerTrackPump(async t=>{let n=null,i=new Gl(e);for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let i={stack:[],error:void 0,hasError:!1};try{let a=pm(i,e,!1);if(this._state===`canceled`)break;let c=0,l=a.numberOfFrames;if(a.timestamp<this._startTimestamp&&(c=Math.round((this._startTimestamp-a.timestamp)*a.sampleRate)),a.timestamp+a.duration>this._endTimestamp&&(l=Math.round((this._endTimestamp-a.timestamp)*a.sampleRate)),c>=l){a.close();continue}let u;if(c>0||l<a.numberOfFrames){let e=a.trim(c,l);if(a.close(),u=e,e.numberOfFrames===0){e.close();continue}}else u=a;let d=pm(i,u,!1);if(d.setTimestamp(d.timestamp+this._timestampOffset),n===null&&(n=d.timestamp>0&&!this.output.format.supportsTimestampedMediaData),n){let e={stack:[],error:void 0,hasError:!1};try{let i=d.timestamp,c=Math.round(i*s),l=Mc(a.format),u=new Uint8Array(l*c*o);(a.format===`u8`||a.format===`u8-planar`)&&u.fill(128);let f=pm(e,new jc({data:u,format:a.format,numberOfChannels:o,sampleRate:s,timestamp:0}),!1);await this._registerAudioSample(t,f,h,r,()=>m),n=!1}catch(t){e.error=t,e.hasError=!0}finally{mm(e)}}await this._registerAudioSample(t,d,h,r,()=>m)}catch(e){i.error=e,i.hasError=!0}finally{mm(i)}}h.close(),this._closeTrack(r)})}else{let t=new Tp(i);a=t,this._registerTrackPump(async n=>{let i=new Nl(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(f)for await(let e of i.packets(f)){if(this._state===`canceled`||e.timestamp>=this._endTimestamp||this._copyBoundaryPolicy===`shrink`&&e.timestamp+e.duration>this._endTimestamp)break;let i=e.timestamp+this._timestampOffset;if(o!==null&&i<o)continue;o=i;let s=e.clone({timestamp:i,duration:e.duration});this._updateProgress(r,s.timestamp+s.duration),await t.add(s,a),this._synchronizer.shouldWait(r,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(n,s.timestamp)}t.close(),this._closeTrack(r)})}let p=null;!t.group&&!this._composable&&(p=new um);let m=await e.getLanguageCode(),h=await e.getName(),g=await e.getDisposition(),_=d?null:await e.getBitrate(),v=d?null:await e.getAverageBitrate();this.output.addAudioTrack(a,{languageCode:Ue(m)?m:void 0,name:h??void 0,disposition:g,group:p??t.group,bitrate:_??void 0,averageBitrate:v??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _registerAudioSample(e,t,n,r,i){this._updateProgress(r,t.timestamp+t.duration),await n.add(t),t.close();let a=i();a!==null&&(this._synchronizer.shouldWait(r,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){let t={done:!1,resolvers:D(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!==`canceled`&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:n}=D();e.wake=n,await t}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;n(this._totalDuration!==null);let e=Math.min(...this._maxTimestamps.values()),t=O(e/this._totalDuration,0,1);this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,this.onProgress?.(t,e))}},ym=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},bm=class{constructor(e){this.maxTimestamps=/* @__PURE__ */ new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){let r=this.maxTimestamps.get(e);n(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r));let i=this.computeMinAndMaybeResolve();return this.conversion._state===`canceled`||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-i>1}wait(e){let{promise:t,resolve:n}=D();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<1&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};
|
|
574
|
+
`+this._getInvalidityExplanation().join(``));if(this._state===`executing`)throw Error(`Cannot call execute() while a previous call to execute() is still running.`);if(this._state===`canceled`)throw new Sm;if(this._state===`done`)return;if(this._composable&&this.output.state===`pending`)throw Error(`A composable conversion requires the output to be started. Call start() on the output before executing the conversion.`);this._state=`executing`,this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{this._state===`executing`&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener(`abort`,t);for(let e of this._trackPumps)e.done||(e.resolvers=D());if(this._executed)for(let e of this._trackPumps)e.wake?.();else{this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async e=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let e of this._trackPumps)e.start()}try{await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){throw this._state!==`canceled`&&this.cancel(),e}finally{e.pauseSignal?.removeEventListener(`abort`,t)}if(this._state===`canceled`)throw new Sm;let n=this._trackPumps.every(e=>e.done);this._state=n?`done`:`idle`,n&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!==`done`){if(this._state===`canceled`){A._warn(`Conversion already canceled.`);return}this._state=`canceled`;for(let e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let a,o=await e.getRotation(),s=await e.getFlip(),{rotation:c,flip:l}=m(o,s,t.rotate??0,t.flip??!1),u=c,d=l,f=t.rotate||t.flip?null:await e.getTransformationMatrix(),p=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),h=await e.getSquarePixelWidth(),g=await e.getSquarePixelHeight(),[_,v]=c%180==0?[h,g]:[g,h],y=t.crop;y&&=xc(y,_,v);let[b,x]=y?[y.width,y.height]:[_,v],S=b,C=x,ee=S/C;t.width!==void 0&&t.height===void 0?(S=Ft(t.width),C=Ft(Math.round(S/ee))):t.width===void 0&&t.height!==void 0?(C=Ft(t.height),S=Ft(Math.round(C*ee))):t.width!==void 0&&t.height!==void 0&&(S=Ft(t.width),C=Ft(t.height));let te=this.output.format.getSupportedVideoCodecs(),w=t.alpha??`discard`,T=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!te.includes(i)||t.codec&&t.codec!==i||S!==b||C!==x||c!==0&&!p||l&&!p||!!y,ne=null;if(!T){let t=new Pl(e),n=await t.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await t.getFirstKeyPacket({verifyKeyPackets:!0});if(n&&n.timestamp<this._startTimestamp&&n.timestamp+n.duration<=this._startTimestamp&&this._copyBoundaryPolicy===`shrink`&&(n=await t.getNextKeyPacket(n,{verifyKeyPackets:!0})),ne=n,n){let e=this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp,this._startTimestamp):n.timestamp;if((this._copyBoundaryPolicy===`shrink`?e-this._startTimestamp:Math.max(this._startTimestamp-e,0))>this._copyBoundaryTolerance)T=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)e+this._timestampOffset!==0&&(T=!0);else{let t=O(this._startTimestamp-e,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);e+t===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+t,this._timestampOffsetAdjusted=!0):T=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&e<this._startTimestamp){let t=Math.min(this._startTimestamp-e,this._copyTimestampShiftTolerance);e+t>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+t):T=!0}}}if(T&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(T){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(te=te.filter(e=>e===t.codec));let i=cl(t.quality,t.bitrate)??new z(`high`),o=await ml(te,{width:t.process&&t.processedWidth?t.processedWidth:S,height:t.process&&t.processedHeight?t.processedHeight:C,quality:i});if(!o){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let s={codec:o,quality:i,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:w,hardwareAcceleration:t.hardwareAcceleration,transform:{}};n(s.transform);let m=S!==b||C!==x||c!==0&&(!p||t.process!==void 0)||l&&(!p||t.process!==void 0)||!!y||h!==await e.getCodedWidth()||g!==await e.getCodedHeight();if(!m){let t={stack:[],error:void 0,hasError:!1};try{let n=new hm({format:new Xp,target:new Hf}),r=new wp(s);n.addVideoTrack(r),await n.start();let i=gm(t,await new Hl(e).getSample(await e.getFirstTimestamp()),!1);if(i)try{await r.add(i),i.close(),await n.finalize()}catch(e){A._warn(`An error occurred when probing encoder support. Falling back to rerender path.`,e),n.cancel(),m=!0,s.transform.force=!0}else await n.cancel()}catch(e){t.error=e,t.hasError=!0}finally{_m(t)}}t.frameRate&&(s.transform.frameRate=t.frameRate),t.process&&(s.transform.process=t.process),m&&(u=0,d=!1,f=null,s.transform.width=S,s.transform.height=C,s.transform.fit=t.fit??`fill`,s.transform.rotate=t.rotate,s.transform.flip=t.flip,s.transform.crop=y,s.transform.alpha=w);let _=null;s.onEncodedSample=e=>{_=e.timestamp};let v=new wp(s);a=v,this._registerTrackPump(async t=>{let n=new Hl(e);for await(let e of n.samples(this._startTimestamp,this._endTimestamp)){let n={stack:[],error:void 0,hasError:!1};try{let i=gm(n,e,!1);if(this._state===`canceled`)break;let a=Math.max(this._startTimestamp,i.timestamp),o=Math.min(this._endTimestamp,i.timestamp+i.duration);if(a>=o)continue;i.setTimestamp(a+this._timestampOffset),i.setDuration(o-a),this._updateProgress(r,i.timestamp+i.duration),await v.add(i),i.close(),_!==null&&(this._synchronizer.shouldWait(r,_)&&await this._synchronizer.wait(_),await this._checkpoint(t,_))}catch(e){n.error=e,n.hasError=!0}finally{_m(n)}}v.close(),this._closeTrack(r)})}else{let t=new _p(i);a=t,this._registerTrackPump(async n=>{let i=new Pl(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(ne)for await(let e of i.packets(ne,void 0,{verifyKeyPackets:!0})){if(this._state===`canceled`)break;if(e.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy===`shrink`)break;{let t=e,n=!1;for(let e=0;e<6;e++){let e=await i.getNextPacket(t,{metadataOnly:!0});if(!e)break;if(e.timestamp<this._endTimestamp){n=!0;break}t=e}if(!n)break}}let s=e.timestamp,c=e.timestamp+e.duration;this._copyBoundaryPolicy===`shrink`&&(s=Math.max(s,this._startTimestamp),c=Math.min(c,this._endTimestamp),c=Math.max(c,s)),s+=this._timestampOffset,c+=this._timestampOffset;let l=e.type;l===`key`&&o!==null&&s<o&&(l=`delta`),o=Math.max(o??-1/0,s);let u=e.clone({timestamp:s,duration:c-s,sideData:w===`discard`?{}:e.sideData,type:l});this._updateProgress(r,u.timestamp+u.duration),await t.add(u,a),this._synchronizer.shouldWait(r,u.timestamp)&&await this._synchronizer.wait(u.timestamp),await this._checkpoint(n,u.timestamp)}t.close(),this._closeTrack(r)})}let re=null;!t.group&&!this._composable&&(re=new pm);let ie=await e.getLanguageCode(),ae=await e.getName(),oe=await e.getDisposition(),se=T?null:await e.getBitrate(),ce=T?null:await e.getAverageBitrate(),le=w===`keep`&&await e.canBeTransparent();this.output.addVideoTrack(a,{frameRate:t.frameRate,languageCode:Ue(ie)?ie:void 0,name:ae??void 0,disposition:oe,rotation:u,flip:d,transformationMatrix:f??void 0,canBeTransparent:le,group:re??t.group,bitrate:se??void 0,averageBitrate:ce??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(re)}async _processAudioTrack(e,t,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let a,o=await e.getNumberOfChannels(),s=await e.getSampleRate(),c=t.numberOfChannels??o,l=t.sampleRate??s,u=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||c!==o||l!==s||!u.includes(i)||!!t.codec&&t.codec!==i||t.process!==void 0||t.sampleFormat!==void 0,f=null;if(!d){let t=new Pl(e),n=await t.getKeyPacket(this._startTimestamp)??await t.getFirstKeyPacket();n&&(this._copyBoundaryPolicy===`shrink`&&n.timestamp<this._startTimestamp||this._copyBoundaryPolicy===`expand`&&n.timestamp+n.duration<=this._startTimestamp)&&(n=await t.getNextKeyPacket(n));let r=Er.includes(i)&&i!==`flac`;if(n&&this._copyBoundaryPolicy===`expand`&&r){let r=await t.getKeyPacket(n.timestamp-1/await e.getTimeResolution());r&&(n=r)}if(f=n,n){if((this._copyBoundaryPolicy===`shrink`?Math.max(n.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-n.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(!this.output.format.supportsTimestampedMediaData){if(this._timestampOffsetAdjusted)n.timestamp+this._timestampOffset!==0&&(d=!0);else{let e=O(this._startTimestamp-n.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);n.timestamp+e===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+e,this._timestampOffsetAdjusted=!0):d=!0}}else if(this.output.format.negativeTimestampSupport!==`full`&&n.timestamp<this._startTimestamp){let e=Math.min(this._startTimestamp-n.timestamp,this._copyTimestampShiftTolerance);n.timestamp+e>=this._startTimestamp||this.output.format.negativeTimestampSupport===`prefer-non-negative`&&this._copyMode===`forced`?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+e):d=!0}}}if(d&&this._copyMode===`forced`){this.discardedTracks.push({track:e,reason:`cannot_copy`,trackOptions:t});return}if(d){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}let i=null;t.codec&&(u=u.filter(e=>e===t.codec));let d=cl(t.quality,t.bitrate)??new z(`high`),f=await fl(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:l,quality:d});if(!f.some(e=>Er.includes(e))&&u.some(e=>Er.includes(e))&&(c!==2||l!==bm)){let e=(await fl(u,{numberOfChannels:2,sampleRate:bm,quality:d})).find(e=>Er.includes(e));e&&(i=e,c=2,l=bm)}else i=f[0]??null;if(i===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let p={codec:i,quality:d,transform:{sampleFormat:t.sampleFormat,process:t.process}};n(p.transform),c!==o&&(p.transform.numberOfChannels=c),l!==s&&(p.transform.sampleRate=l);let m=null;p.onEncodedSample=e=>{m=e.timestamp};let h=new Ap(p);a=h,this._registerTrackPump(async t=>{let n=null,i=new Kl(e);for await(let e of i.samples(this._startTimestamp,this._endTimestamp)){let i={stack:[],error:void 0,hasError:!1};try{let a=gm(i,e,!1);if(this._state===`canceled`)break;let c=0,l=a.numberOfFrames;if(a.timestamp<this._startTimestamp&&(c=Math.round((this._startTimestamp-a.timestamp)*a.sampleRate)),a.timestamp+a.duration>this._endTimestamp&&(l=Math.round((this._endTimestamp-a.timestamp)*a.sampleRate)),c>=l){a.close();continue}let u;if(c>0||l<a.numberOfFrames){let e=a.trim(c,l);if(a.close(),u=e,e.numberOfFrames===0){e.close();continue}}else u=a;let d=gm(i,u,!1);if(d.setTimestamp(d.timestamp+this._timestampOffset),n===null&&(n=d.timestamp>0&&!this.output.format.supportsTimestampedMediaData),n){let e={stack:[],error:void 0,hasError:!1};try{let i=d.timestamp,c=Math.round(i*s),l=Nc(a.format),u=new Uint8Array(l*c*o);(a.format===`u8`||a.format===`u8-planar`)&&u.fill(128);let f=gm(e,new Mc({data:u,format:a.format,numberOfChannels:o,sampleRate:s,timestamp:0}),!1);await this._registerAudioSample(t,f,h,r,()=>m),n=!1}catch(t){e.error=t,e.hasError=!0}finally{_m(e)}}await this._registerAudioSample(t,d,h,r,()=>m)}catch(e){i.error=e,i.hasError=!0}finally{_m(i)}}h.close(),this._closeTrack(r)})}else{let t=new Op(i);a=t,this._registerTrackPump(async n=>{let i=new Pl(e),a={decoderConfig:await e.getDecoderConfig()??void 0},o=null;if(f)for await(let e of i.packets(f)){if(this._state===`canceled`||e.timestamp>=this._endTimestamp||this._copyBoundaryPolicy===`shrink`&&e.timestamp+e.duration>this._endTimestamp)break;let i=e.timestamp+this._timestampOffset;if(o!==null&&i<o)continue;o=i;let s=e.clone({timestamp:i,duration:e.duration});this._updateProgress(r,s.timestamp+s.duration),await t.add(s,a),this._synchronizer.shouldWait(r,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(n,s.timestamp)}t.close(),this._closeTrack(r)})}let p=null;!t.group&&!this._composable&&(p=new pm);let m=await e.getLanguageCode(),h=await e.getName(),g=await e.getDisposition(),_=d?null:await e.getBitrate(),v=d?null:await e.getAverageBitrate();this.output.addAudioTrack(a,{languageCode:Ue(m)?m:void 0,name:h??void 0,disposition:g,group:p??t.group,bitrate:_??void 0,averageBitrate:v??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _registerAudioSample(e,t,n,r,i){this._updateProgress(r,t.timestamp+t.duration),await n.add(t),t.close();let a=i();a!==null&&(this._synchronizer.shouldWait(r,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){let t={done:!1,resolvers:D(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!==`canceled`&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:n}=D();e.wake=n,await t}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;n(this._totalDuration!==null);let e=Math.min(...this._maxTimestamps.values()),t=O(e/this._totalDuration,0,1);this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,this.onProgress?.(t,e))}},Sm=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},Cm=class{constructor(e){this.maxTimestamps=/* @__PURE__ */ new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){let r=this.maxTimestamps.get(e);n(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r));let i=this.computeMinAndMaybeResolve();return this.conversion._state===`canceled`||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-i>1}wait(e){let{promise:t,resolve:n}=D();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<1&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};
|
|
575
575
|
/*!
|
|
576
576
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
577
577
|
*
|
|
@@ -579,4 +579,4 @@ Check the discardedTracks field for more info.`)}return e}async execute(e={}){if
|
|
|
579
579
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
580
580
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
581
581
|
*/
|
|
582
|
-
export{
|
|
582
|
+
export{Hs as ADTS,Ks as ALL_FORMATS,cm as ALL_TRACK_TYPES,F as AUDIO_CODECS,Ms as AdtsInputFormat,im as AdtsOutputFormat,Bf as AppendOnlyStreamTarget,Bt as AttachedFile,ql as AudioBufferSink,jp as AudioBufferSource,Mc as AudioSample,jc as AudioSampleResource,Kl as AudioSampleSink,Ap as AudioSampleSource,Dp as AudioSource,Il as BaseMediaSampleSink,Xo as BlobSource,Jo as BufferSource,Lf as BufferTarget,Ul as CanvasSink,Tp as CanvasSource,Zp as CmafOutputFormat,It as ConcurrentRunner,xm as Conversion,Sm as ConversionCanceledError,vl as CustomAudioDecoder,bl as CustomAudioEncoder,qo as CustomPathedSource,is as CustomSource,_l as CustomVideoDecoder,yl as CustomVideoEncoder,Op as EncodedAudioPacketSource,I as EncodedPacket,Pl as EncodedPacketSink,_p as EncodedVideoPacketSource,Pt as EventEmitter,Us as FLAC,rs as FilePathSource,Vf as FilePathTarget,js as FlacInputFormat,am as FlacOutputFormat,Gs as HLS,qs as HLS_FORMATS,Ps as HlsInputFormat,sm as HlsOutputFormat,su as Input,Zl as InputAudioTrack,lu as InputDisposedError,Ss as InputFormat,Jl as InputTrack,Xl as InputVideoTrack,Cs as IsobmffInputFormat,Yp as IsobmffOutputFormat,Rt as LogLevel,A as Logging,Ls as MATROSKA,zs as MP3,Fs as MP4,Ws as MPEG_TS,Es as MatroskaInputFormat,mp as MediaSource,Mp as MediaStreamAudioTrackSource,Ep as MediaStreamVideoTrackSource,$p as MkvOutputFormat,Qp as MovOutputFormat,Os as Mp3InputFormat,tm as Mp3OutputFormat,ws as Mp4InputFormat,Xp as Mp4OutputFormat,Ns as MpegTsInputFormat,om as MpegTsOutputFormat,Er as NON_PCM_AUDIO_CODECS,Hf as NullTarget,Vs as OGG,As as OggInputFormat,rm as OggOutputFormat,hm as Output,dm as OutputAudioTrack,Jp as OutputFormat,fm as OutputSubtitleTrack,lm as OutputTrack,pm as OutputTrackGroup,um as OutputVideoTrack,P as PCM_AUDIO_CODECS,Go as PathedSource,Wf as PathedTarget,Is as QTFF,rl as QUALITY_HIGH,tl as QUALITY_LOW,nl as QUALITY_MEDIUM,il as QUALITY_VERY_HIGH,el as QUALITY_VERY_LOW,z as Quality,Ts as QuickTimeInputFormat,ls as RangedSource,Uf as RangedTarget,os as ReadableStreamSource,zt as RichImageData,Dr as SUBTITLE_CODECS,Uo as Source,Wo as SourceRef,as as StreamSource,zf as StreamTarget,Bp as SubtitleSource,Pf as Target,Vp as TextSubtitleSource,cu as UnsupportedInputFormatError,es as UrlSource,N as VIDEO_CODECS,dc as VIDEO_SAMPLE_PIXEL_FORMATS,pc as VideoSample,yc as VideoSampleColorSpace,uc as VideoSampleResource,Hl as VideoSampleSink,wp as VideoSampleSource,hp as VideoSource,Bs as WAVE,Rs as WEBM,nm as WavOutputFormat,ks as WaveInputFormat,Ds as WebMInputFormat,em as WebMOutputFormat,Ql as asc,$s as canDecode,tc as canDecodeAudio,ec as canDecodeVideo,al as canEncode,sl as canEncodeAudio,ll as canEncodeSubtitles,ol as canEncodeVideo,$l as desc,ic as getDecodableAudioCodecs,nc as getDecodableCodecs,rc as getDecodableVideoCodecs,fl as getEncodableAudioCodecs,ul as getEncodableCodecs,pl as getEncodableSubtitleCodecs,dl as getEncodableVideoCodecs,hl as getFirstEncodableAudioCodec,gl as getFirstEncodableSubtitleCodec,ml as getFirstEncodableVideoCodec,eu as prefer,Tl as registerDecoder,El as registerEncoder,hc as registerVideoSampleTransformer};
|