@rr0/ufoathome 0.177.2 → 0.178.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-interview/rr0-interview.mjs +3 -3
- package/dist-embed-scene/{AdsbLolArchiveProvider-BHGe8FVN.js → AdsbLolArchiveProvider-B0Yi081_.js} +1 -1
- package/dist-embed-scene/{BeamEditor-zq64GorX.js → BeamEditor-DFGRzRny.js} +1 -1
- package/dist-embed-scene/{BeamSystem-BXee1GYk.js → BeamSystem-ebEMoYD3.js} +1 -1
- package/dist-embed-scene/{ContrailSystem-BSbI2jUe.js → ContrailSystem-Bn--uCNU.js} +1 -1
- package/dist-embed-scene/ControlPasses-BMma2JRm.js +29 -0
- package/dist-embed-scene/FilmChrome-DYiyzoB_.js +1 -0
- package/dist-embed-scene/{Flightradar24Provider-Dx2Fb8yO.js → Flightradar24Provider-CpwhYfIE.js} +1 -1
- package/dist-embed-scene/GLTFLoader-BxToReDu.js +1 -0
- package/dist-embed-scene/GenerativeKit-DR6C3LMC.js +4 -0
- package/dist-embed-scene/GenerativeKitMessages-Cu7wXgYa.js +1 -0
- package/dist-embed-scene/GenerativeKitMessages_en-Cl3kA96x.js +33 -0
- package/dist-embed-scene/GenerativeKitMessages_es-CEU93Cl3.js +33 -0
- package/dist-embed-scene/GenerativeKitMessages_fr-DmW0OAmF.js +33 -0
- package/dist-embed-scene/GenerativeKitMessages_it-Ba87kumS.js +33 -0
- package/dist-embed-scene/{HeadlightSystem-_BIIKhQ2.js → HeadlightSystem-l2XbBvXf.js} +1 -1
- package/dist-embed-scene/LanternEditor-H8VYYbRn.js +9 -0
- package/dist-embed-scene/{LaserBeam-DmH2JeMa.js → LaserBeam-B48FKTrt.js} +1 -1
- package/dist-embed-scene/LaunchEditor-CIYcS0Y-.js +22 -0
- package/dist-embed-scene/{LaunchPlume-BRnjFVcY.js → LaunchPlume-eEIp7_hM.js} +1 -1
- package/dist-embed-scene/{LaunchSimulation-DL7QBfEl.js → LaunchSimulation-DNNEzmzs.js} +1 -1
- package/dist-embed-scene/{ModuleSession-BvQABNEZ.js → ModuleSession-DLoAutYP.js} +2 -2
- package/dist-embed-scene/ModuleThree-R2LhnY95.js +1 -0
- package/dist-embed-scene/{ParameterForm-BMIW4Gkh.js → ParameterForm-ez-n_0Dw.js} +9 -9
- package/dist-embed-scene/{RailwaySystem-DZQr_rS_.js → RailwaySystem-C3Y0a9aT.js} +1 -1
- package/dist-embed-scene/{ReentryEditor-DJO_M-8-.js → ReentryEditor-CwY4oANp.js} +1 -1
- package/dist-embed-scene/{ReentrySimulation-pWRgNLjt.js → ReentrySimulation-BDgEPekW.js} +1 -1
- package/dist-embed-scene/ReferenceSystem-D9IdSvFM.js +1 -0
- package/dist-embed-scene/{SceneNames_en-CqzjDgS4.js → SceneNames_en-BCTAMSLj.js} +1 -1
- package/dist-embed-scene/{SceneNames_es-DMfxIS0T.js → SceneNames_es-BOWBdXXS.js} +1 -1
- package/dist-embed-scene/{SceneNames_fr-DydzEE4a.js → SceneNames_fr-De6iQ9ff.js} +1 -1
- package/dist-embed-scene/{SceneNames_it-DJAACEvb.js → SceneNames_it-DfBWbCPR.js} +1 -1
- package/dist-embed-scene/{TimelineTracks-B-bXAaF7.js → TimelineTracks-BQXJMJaJ.js} +1 -1
- package/dist-embed-scene/{TraceSystem-gVZk_ffU.js → TraceSystem-BD6YpW6g.js} +2 -2
- package/dist-embed-scene/UfoMessages_en-CXQNZd8v.js +1 -0
- package/dist-embed-scene/UfoMessages_es-CO-v8Jl6.js +1 -0
- package/dist-embed-scene/UfoMessages_fr-CGkQBn5r.js +1 -0
- package/dist-embed-scene/UfoMessages_it-BScqxIaH.js +1 -0
- package/dist-embed-scene/VideoButton-Cy_r767Z.js +1 -0
- package/dist-embed-scene/VideoExport-B8ZhHNnd.js +169 -0
- package/dist-embed-scene/{WaterSystem-DI_NBDfH.js → WaterSystem-DbyWlKho.js} +1 -1
- package/dist-embed-scene/browser-CltifEM0.js +1 -0
- package/dist-embed-scene/logo-h2-w4Mwu.png +0 -0
- package/dist-embed-scene/rr0-scene.mjs +426 -296
- package/dist-embed-scene/{sightingSchema-BfOYR_OD.js → sightingSchema-pBDQNwMz.js} +1 -1
- package/dist-embed-scene/trafficRuntime-CJIPy2oO.js +2 -0
- package/dist-embed-sighting/{AdsbLolArchiveProvider-DK4qEYPv.js → AdsbLolArchiveProvider-BqLvFUVC.js} +1 -1
- package/dist-embed-sighting/{BallesterGuaspAssessor-FGskpWWG.js → BallesterGuaspAssessor-CLQvJKlm.js} +1 -1
- package/dist-embed-sighting/{BeamEditor-BglkfKa6.js → BeamEditor-CcOf6lNz.js} +1 -1
- package/dist-embed-sighting/{BeamSystem-DDtPjozC.js → BeamSystem-B5d0Ymn5.js} +1 -1
- package/dist-embed-sighting/CaseExportMessages_en-jHlu58Y7.js +1 -0
- package/dist-embed-sighting/CaseExportMessages_es-dCQQFgjq.js +1 -0
- package/dist-embed-sighting/CaseExportMessages_fr-sDfEgjWg.js +1 -0
- package/dist-embed-sighting/CaseExportMessages_it-BJaglZtP.js +1 -0
- package/dist-embed-sighting/CaseMessages_en-CBS5QChl.js +1 -0
- package/dist-embed-sighting/CaseMessages_es-DAMl4aTC.js +1 -0
- package/dist-embed-sighting/CaseMessages_fr-C3wQxAk_.js +1 -0
- package/dist-embed-sighting/CaseMessages_it-CyrREg6v.js +1 -0
- package/dist-embed-sighting/CaseReportExport-Uf7Bs2Qz.js +65 -0
- package/dist-embed-sighting/CaseReportTexts_en-DlN7p1pC.js +1 -0
- package/dist-embed-sighting/CaseReportTexts_es-CncAEaey.js +1 -0
- package/dist-embed-sighting/CaseReportTexts_fr-B5nP6RlP.js +1 -0
- package/dist-embed-sighting/CaseReportTexts_it-Dc-oPmXB.js +1 -0
- package/dist-embed-sighting/{ContrailSystem-DXV0DnrQ.js → ContrailSystem-CqpZgLkb.js} +1 -1
- package/dist-embed-sighting/ControlPasses-BxgSO3B9.js +29 -0
- package/dist-embed-sighting/FilmChrome-DYiyzoB_.js +1 -0
- package/dist-embed-sighting/{Flightradar24Provider-Ch4GdVJG.js → Flightradar24Provider-DQtEJ3tX.js} +1 -1
- package/dist-embed-sighting/GLTFLoader-VIIHsteW.js +1 -0
- package/dist-embed-sighting/GenerativeKit-DR6C3LMC.js +4 -0
- package/dist-embed-sighting/GenerativeKitMessages-BudEc93g.js +1 -0
- package/dist-embed-sighting/GenerativeKitMessages_en-Cl3kA96x.js +33 -0
- package/dist-embed-sighting/GenerativeKitMessages_es-CEU93Cl3.js +33 -0
- package/dist-embed-sighting/GenerativeKitMessages_fr-DmW0OAmF.js +33 -0
- package/dist-embed-sighting/GenerativeKitMessages_it-Ba87kumS.js +33 -0
- package/dist-embed-sighting/HeadlightSystem-B4RR270O.js +34 -0
- package/dist-embed-sighting/{HynekAssessor-Cb8mZ9Ib.js → HynekAssessor-CJ9APziM.js} +1 -1
- package/dist-embed-sighting/LanternEditor-D1BA5pRP.js +9 -0
- package/dist-embed-sighting/{LaserBeam-DkKFSSp_.js → LaserBeam-BjjC_CzP.js} +1 -1
- package/dist-embed-sighting/LaunchEditor-TTSgWqbE.js +22 -0
- package/dist-embed-sighting/LaunchPlume-B2Fjd2_C.js +1 -0
- package/dist-embed-sighting/{LaunchSimulation-DUvH6_BB.js → LaunchSimulation-BcmPicEe.js} +1 -1
- package/dist-embed-sighting/{ModuleSession-GzfQ8_LE.js → ModuleSession-CY9_UusZ.js} +2 -2
- package/dist-embed-sighting/ModuleThree-BhryLUjX.js +1 -0
- package/dist-embed-sighting/{NearestApproach-BeKwz4vK.js → NearestApproach-iBLl7o1g.js} +1 -1
- package/dist-embed-sighting/ParameterForm-BaUeWd7v.js +91 -0
- package/dist-embed-sighting/{PoherAssessor-JLqDISRf.js → PoherAssessor-DDRUgnRW.js} +1 -1
- package/dist-embed-sighting/RailwaySystem-C1nfRJfj.js +41 -0
- package/dist-embed-sighting/ReadingSensitivityMessages_en-CF6XauSj.js +1 -0
- package/dist-embed-sighting/ReadingSensitivityMessages_es-Ca-13TTT.js +1 -0
- package/dist-embed-sighting/ReadingSensitivityMessages_fr-Djdd6Hdq.js +1 -0
- package/dist-embed-sighting/ReadingSensitivityMessages_it-CPUXxMqD.js +1 -0
- package/dist-embed-sighting/{ReentryEditor-BHgPXlx3.js → ReentryEditor-CGN3ewTE.js} +1 -1
- package/dist-embed-sighting/ReentrySimulation-C2kIulZ6.js +1 -0
- package/dist-embed-sighting/{ReferenceSystem-B5diz1Lt.js → ReferenceSystem-BRTCOQHk.js} +1 -1
- package/dist-embed-sighting/{RoadMarkings-Dv3xdtFG.js → RoadMarkings-CNLt-BEg.js} +1 -1
- package/dist-embed-sighting/{SceneNames_en-BbQ55UYu.js → SceneNames_en-ChY7v63o.js} +1 -1
- package/dist-embed-sighting/{SceneNames_es-DsJpGSDK.js → SceneNames_es-DH4YgJV5.js} +1 -1
- package/dist-embed-sighting/{SceneNames_fr-CKr5m8QL.js → SceneNames_fr-Ca52lykk.js} +1 -1
- package/dist-embed-sighting/{SceneNames_it-qSw1j95v.js → SceneNames_it-BQe9GLaj.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_en-DuokT218.js → SightingMessages_en-Xm6PILcs.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_es-JO8WQ1_V.js → SightingMessages_es-DMp0MUjJ.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_fr-3C2RZVNA.js → SightingMessages_fr-NvQKGPaf.js} +1 -1
- package/dist-embed-sighting/{SightingMessages_it-BEMBUACg.js → SightingMessages_it-CKIf49Zt.js} +1 -1
- package/dist-embed-sighting/{TimelineTracks-XzShW15O.js → TimelineTracks-Ddv5sZHp.js} +1 -1
- package/{dist-embed-sighting-editor/TraceSystem-CDHG18il.js → dist-embed-sighting/TraceSystem-BkUPo1Xf.js} +2 -2
- package/dist-embed-sighting/UfoMessages_en-cLvtpfIC.js +1 -0
- package/dist-embed-sighting/UfoMessages_es-CO-v8Jl6.js +1 -0
- package/dist-embed-sighting/UfoMessages_fr-CGkQBn5r.js +1 -0
- package/dist-embed-sighting/UfoMessages_it-BScqxIaH.js +1 -0
- package/dist-embed-sighting/VideoButton-C62NkJrH.js +1 -0
- package/dist-embed-sighting/VideoExport-B8ZhHNnd.js +169 -0
- package/dist-embed-sighting/{WaterSystem-CcLIPQfy.js → WaterSystem-DrSAhM5g.js} +1 -1
- package/dist-embed-sighting/browser-CltifEM0.js +1 -0
- package/dist-embed-sighting/logo-h2-w4Mwu.png +0 -0
- package/dist-embed-sighting/rr0-sighting.mjs +531 -337
- package/dist-embed-sighting/{sightingSchema-BfOYR_OD.js → sightingSchema-pBDQNwMz.js} +1 -1
- package/dist-embed-sighting/trafficRuntime-CFgDqQz4.js +2 -0
- package/dist-embed-sighting-editor/{AdsbLolArchiveProvider-CXB-CDQ2.js → AdsbLolArchiveProvider-fZkxLAHp.js} +1 -1
- package/dist-embed-sighting-editor/{BallesterGuaspAssessor-Bb8Kl2FU.js → BallesterGuaspAssessor-DASadJjI.js} +1 -1
- package/dist-embed-sighting-editor/{BeamEditor-DJtZYFp0.js → BeamEditor-B2diaX_e.js} +1 -1
- package/dist-embed-sighting-editor/{BeamSystem-C6Wk_vNQ.js → BeamSystem-BfNJfayv.js} +1 -1
- package/dist-embed-sighting-editor/{BodyEditor-Cj7TgjV-.js → BodyEditor-CCBXFuuL.js} +1 -1
- package/dist-embed-sighting-editor/BodyEditorMessages_en-CckxSS1L.js +1 -0
- package/dist-embed-sighting-editor/BodyEditorMessages_es-B8GlFFBo.js +1 -0
- package/dist-embed-sighting-editor/BodyEditorMessages_fr-638ypdqf.js +1 -0
- package/dist-embed-sighting-editor/BodyEditorMessages_it-SKpMkHFI.js +1 -0
- package/dist-embed-sighting-editor/CaseEditorMessages_en-DrJY0M8h.js +1 -0
- package/dist-embed-sighting-editor/CaseEditorMessages_es-j8EeOBq6.js +1 -0
- package/dist-embed-sighting-editor/CaseEditorMessages_fr-BkwEF9mu.js +1 -0
- package/dist-embed-sighting-editor/CaseEditorMessages_it-d3Z0PBEw.js +1 -0
- package/dist-embed-sighting-editor/CaseExportMessages_en-jHlu58Y7.js +1 -0
- package/dist-embed-sighting-editor/CaseExportMessages_es-dCQQFgjq.js +1 -0
- package/dist-embed-sighting-editor/CaseExportMessages_fr-sDfEgjWg.js +1 -0
- package/dist-embed-sighting-editor/CaseExportMessages_it-BJaglZtP.js +1 -0
- package/dist-embed-sighting-editor/CaseReportExport-iCzv1W9B.js +65 -0
- package/dist-embed-sighting-editor/CaseReportTexts_en-DlN7p1pC.js +1 -0
- package/dist-embed-sighting-editor/CaseReportTexts_es-CncAEaey.js +1 -0
- package/dist-embed-sighting-editor/CaseReportTexts_fr-B5nP6RlP.js +1 -0
- package/dist-embed-sighting-editor/CaseReportTexts_it-Dc-oPmXB.js +1 -0
- package/dist-embed-sighting-editor/{ContrailSystem-e-OLIzTk.js → ContrailSystem-BWvO9taK.js} +1 -1
- package/dist-embed-sighting-editor/ControlPasses-BQ_DUxa_.js +29 -0
- package/dist-embed-sighting-editor/{CoverageAssessor-DUDmS-aG.js → CoverageAssessor-CSktyUlP.js} +1 -1
- package/dist-embed-sighting-editor/FilmChrome-DYiyzoB_.js +1 -0
- package/dist-embed-sighting-editor/{Flightradar24Provider-DtcvpdT3.js → Flightradar24Provider-OvRZWZWj.js} +1 -1
- package/dist-embed-sighting-editor/{GLTFLoader-AHdd-c6G.js → GLTFLoader-CM7Uk25s.js} +1 -1
- package/dist-embed-sighting-editor/GenerativeKit-DR6C3LMC.js +4 -0
- package/dist-embed-sighting-editor/GenerativeKitMessages-BNXaLr1m.js +1 -0
- package/dist-embed-sighting-editor/GenerativeKitMessages_en-Cl3kA96x.js +33 -0
- package/dist-embed-sighting-editor/GenerativeKitMessages_es-CEU93Cl3.js +33 -0
- package/dist-embed-sighting-editor/GenerativeKitMessages_fr-DmW0OAmF.js +33 -0
- package/dist-embed-sighting-editor/GenerativeKitMessages_it-Ba87kumS.js +33 -0
- package/dist-embed-sighting-editor/{GeoExportTexts-DAllttgw.js → GeoExportTexts-DBGGdRnP.js} +1 -1
- package/dist-embed-sighting-editor/{GeoJsonExport-3snOe-2J.js → GeoJsonExport-BZ-0v8fM.js} +1 -1
- package/dist-embed-sighting-editor/GeographicFigures-DqhWddS9.js +1 -0
- package/dist-embed-sighting-editor/{HeadlightSystem-CLhqQjbe.js → HeadlightSystem-C-8Gl3vu.js} +1 -1
- package/dist-embed-sighting-editor/{HynekAssessor-DvVp-CLS.js → HynekAssessor-CH2E88xV.js} +1 -1
- package/dist-embed-sighting-editor/{InterviewEditorElement-44XFadV4.js → InterviewEditorElement-Bz3hyZ-m.js} +2 -2
- package/dist-embed-sighting-editor/{KmlExport-B0SKgn4U.js → KmlExport-Bh4eTycx.js} +1 -1
- package/dist-embed-sighting-editor/{KmlImport-B9mAzJwr.js → KmlImport-CKxaATTA.js} +1 -1
- package/dist-embed-sighting-editor/LanternEditor-tTk1vUZm.js +9 -0
- package/dist-embed-sighting-editor/{LaserBeam-QJPhnVO_.js → LaserBeam-CtogDP38.js} +1 -1
- package/dist-embed-sighting-editor/LaunchEditor-CteAalch.js +22 -0
- package/dist-embed-sighting-editor/{LaunchPlume-C_r62XTj.js → LaunchPlume-BtRrJTP9.js} +1 -1
- package/dist-embed-sighting-editor/{LaunchSimulation-BSDTfZTv.js → LaunchSimulation-xKwguVJt.js} +1 -1
- package/dist-embed-sighting-editor/{ModelSource-B85niY1n.js → ModelSource-CnKzaNDn.js} +1 -1
- package/dist-embed-sighting-editor/{ModelThumbnails-uYh2sUIb.js → ModelThumbnails-UE_Er5EW.js} +1 -1
- package/dist-embed-sighting-editor/{ModelViewer-DLZhhuq5.js → ModelViewer-DoCshJc6.js} +1 -1
- package/dist-embed-sighting-editor/{ModuleConformance-CBMdTSVo.js → ModuleConformance-BKvZnuw9.js} +2 -2
- package/dist-embed-sighting-editor/{ModuleSession-rFLStWcj.js → ModuleSession-CJstaNEN.js} +3 -3
- package/dist-embed-sighting-editor/ModuleThree-1hxqvWFa.js +1 -0
- package/dist-embed-sighting-editor/{ModulesPanelElement-CGp6DrpQ.js → ModulesPanelElement-DdGqqdn4.js} +3 -3
- package/dist-embed-sighting-editor/{NearestApproach-Ctw1-XBO.js → NearestApproach-BH3Yw8Qz.js} +1 -1
- package/dist-embed-sighting-editor/{PictureRegistration-ZyvGfReK.js → PictureRegistration-B9C6iY17.js} +1 -1
- package/dist-embed-sighting-editor/{PoherAssessor-CLKwvgUL.js → PoherAssessor-DWcCWUfa.js} +1 -1
- package/dist-embed-sighting-editor/RailwaySystem-D3VBmx1X.js +41 -0
- package/dist-embed-sighting-editor/ReadingSensitivityMessages_en-CF6XauSj.js +1 -0
- package/dist-embed-sighting-editor/ReadingSensitivityMessages_es-Ca-13TTT.js +1 -0
- package/dist-embed-sighting-editor/ReadingSensitivityMessages_fr-Djdd6Hdq.js +1 -0
- package/dist-embed-sighting-editor/ReadingSensitivityMessages_it-CPUXxMqD.js +1 -0
- package/dist-embed-sighting-editor/{ReentryEditor-DXe8wen6.js → ReentryEditor-BDyG-48K.js} +2 -2
- package/dist-embed-sighting-editor/{ReentrySimulation-BxVE5Dsn.js → ReentrySimulation-BQj0wWXW.js} +1 -1
- package/dist-embed-sighting-editor/ReferenceSystem-C9NRL7UY.js +1 -0
- package/dist-embed-sighting-editor/RoadMarkings-ByQL2MTo.js +1 -0
- package/dist-embed-sighting-editor/SceneNames_en-BdRB6cjg.js +1 -0
- package/dist-embed-sighting-editor/SceneNames_es-Dk0UmXHp.js +1 -0
- package/dist-embed-sighting-editor/SceneNames_fr-_z2iZ8Bm.js +1 -0
- package/dist-embed-sighting-editor/SceneNames_it-CE7fanb3.js +1 -0
- package/dist-embed-sighting-editor/{SightingEditorMessages_en-G8-sD56V.js → SightingEditorMessages_en-jinQLW0J.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_es-DEmsmIRU.js → SightingEditorMessages_es-CsrGiJYn.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_fr-D2HXab_N.js → SightingEditorMessages_fr-cQ6KnPU1.js} +1 -1
- package/dist-embed-sighting-editor/{SightingEditorMessages_it-LpFdlGY5.js → SightingEditorMessages_it-D3Rqso5s.js} +1 -1
- package/dist-embed-sighting-editor/{SightingFileEditor-CnKF2ndt.js → SightingFileEditor-BCjntT4l.js} +1 -1
- package/dist-embed-sighting-editor/{TraceImport-CL8lefw6.js → TraceImport-uGVIjCrc.js} +2 -2
- package/{dist-embed-sighting/TraceSystem-XybhI4uJ.js → dist-embed-sighting-editor/TraceSystem-g262KZ3G.js} +2 -2
- package/dist-embed-sighting-editor/UfoMessages_en-JeMK-39o.js +1 -0
- package/dist-embed-sighting-editor/UfoMessages_es-CO-v8Jl6.js +1 -0
- package/dist-embed-sighting-editor/UfoMessages_fr-CGkQBn5r.js +1 -0
- package/dist-embed-sighting-editor/UfoMessages_it-BScqxIaH.js +1 -0
- package/dist-embed-sighting-editor/VideoButton-CqCZ65oK.js +1 -0
- package/dist-embed-sighting-editor/VideoExport-B8ZhHNnd.js +169 -0
- package/dist-embed-sighting-editor/WaterSystem-CIbQPMqE.js +1 -0
- package/dist-embed-sighting-editor/browser-CltifEM0.js +1 -0
- package/dist-embed-sighting-editor/logo-h2-w4Mwu.png +0 -0
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +610 -398
- package/dist-embed-sighting-editor/{sightingSchema-9xw8srxN.js → sightingSchema-RamhmoRU.js} +1 -1
- package/dist-embed-sighting-editor/{surroundingsSources-DXpzMDPy.js → surroundingsSources-BExFsNzP.js} +1 -1
- package/dist-embed-sighting-editor/trafficRuntime-CPRQW0Ho.js +2 -0
- package/package.json +2 -1
- package/dist-embed-scene/GLTFLoader-DDba3PaV.js +0 -1
- package/dist-embed-scene/LanternEditor-2q5seAWj.js +0 -9
- package/dist-embed-scene/LaunchEditor-Cupksu8A.js +0 -22
- package/dist-embed-scene/ModuleThree-12Uq6OyD.js +0 -1
- package/dist-embed-scene/ReferenceSystem-D9agTeWl.js +0 -1
- package/dist-embed-scene/UfoMessages_en-CRIdIMYy.js +0 -1
- package/dist-embed-scene/UfoMessages_es-BoulVpJw.js +0 -1
- package/dist-embed-scene/UfoMessages_fr-8f6FJbk6.js +0 -1
- package/dist-embed-scene/UfoMessages_it-cngzFg3N.js +0 -1
- package/dist-embed-scene/browser-_Ncw3Jhn.js +0 -1
- package/dist-embed-scene/trafficRuntime-BDtw1Kqi.js +0 -2
- package/dist-embed-sighting/CaseMessages_en-DEyvxYxv.js +0 -1
- package/dist-embed-sighting/CaseMessages_es-DDsQ93tK.js +0 -1
- package/dist-embed-sighting/CaseMessages_fr-DoHbDEkG.js +0 -1
- package/dist-embed-sighting/CaseMessages_it-CF8sKknV.js +0 -1
- package/dist-embed-sighting/GLTFLoader-BDyucwJ-.js +0 -1
- package/dist-embed-sighting/HeadlightSystem-DGUfgm2c.js +0 -34
- package/dist-embed-sighting/LanternEditor-CaZ1JhZS.js +0 -9
- package/dist-embed-sighting/LaunchEditor-QRG2uHH8.js +0 -22
- package/dist-embed-sighting/LaunchPlume-DBINBQgQ.js +0 -1
- package/dist-embed-sighting/ModuleThree-tnKi-oul.js +0 -1
- package/dist-embed-sighting/ParameterForm-DW6cQmYI.js +0 -91
- package/dist-embed-sighting/RailwaySystem-BfTJvmf3.js +0 -41
- package/dist-embed-sighting/ReentrySimulation-C3BR2hs3.js +0 -1
- package/dist-embed-sighting/UfoMessages_en-CoSqGYwb.js +0 -1
- package/dist-embed-sighting/UfoMessages_es-BoulVpJw.js +0 -1
- package/dist-embed-sighting/UfoMessages_fr-8f6FJbk6.js +0 -1
- package/dist-embed-sighting/UfoMessages_it-cngzFg3N.js +0 -1
- package/dist-embed-sighting/browser-_Ncw3Jhn.js +0 -1
- package/dist-embed-sighting/trafficRuntime-BAuwwA-Z.js +0 -2
- package/dist-embed-sighting-editor/BodyEditorMessages_en-zfy3BJb5.js +0 -1
- package/dist-embed-sighting-editor/BodyEditorMessages_es-w95anMnI.js +0 -1
- package/dist-embed-sighting-editor/BodyEditorMessages_fr-ixsDgTbt.js +0 -1
- package/dist-embed-sighting-editor/BodyEditorMessages_it-B3oQzqHE.js +0 -1
- package/dist-embed-sighting-editor/CaseEditorMessages_en-D47ntA6R.js +0 -1
- package/dist-embed-sighting-editor/CaseEditorMessages_es-CyIdBeD_.js +0 -1
- package/dist-embed-sighting-editor/CaseEditorMessages_fr-DXaZI1jZ.js +0 -1
- package/dist-embed-sighting-editor/CaseEditorMessages_it-Cp1-Jm34.js +0 -1
- package/dist-embed-sighting-editor/GeographicFigures-CLBS2HJ-.js +0 -1
- package/dist-embed-sighting-editor/LanternEditor-ngKN2Zt3.js +0 -9
- package/dist-embed-sighting-editor/LaunchEditor-B8KlP5eo.js +0 -22
- package/dist-embed-sighting-editor/ModuleThree-DrKN6B-3.js +0 -1
- package/dist-embed-sighting-editor/RailwaySystem-C67LdkZv.js +0 -41
- package/dist-embed-sighting-editor/ReferenceSystem-B201fXMC.js +0 -1
- package/dist-embed-sighting-editor/RoadMarkings-DJ2HL-6g.js +0 -1
- package/dist-embed-sighting-editor/SceneNames_en-DggkchR4.js +0 -1
- package/dist-embed-sighting-editor/SceneNames_es-BtXXqtTk.js +0 -1
- package/dist-embed-sighting-editor/SceneNames_fr-I6FOP0oQ.js +0 -1
- package/dist-embed-sighting-editor/SceneNames_it-DrW4eXBX.js +0 -1
- package/dist-embed-sighting-editor/UfoMessages_en-BxhQNf5z.js +0 -1
- package/dist-embed-sighting-editor/UfoMessages_es-BoulVpJw.js +0 -1
- package/dist-embed-sighting-editor/UfoMessages_fr-8f6FJbk6.js +0 -1
- package/dist-embed-sighting-editor/UfoMessages_it-cngzFg3N.js +0 -1
- package/dist-embed-sighting-editor/WaterSystem-B2xlCmn2.js +0 -1
- package/dist-embed-sighting-editor/browser-_Ncw3Jhn.js +0 -1
- package/dist-embed-sighting-editor/trafficRuntime-_7Uw8kC_.js +0 -2
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
3
|
+
*
|
|
4
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
*/function p(t){if(!t)throw new Error("Assertion failed.")}const xi=Math.PI/180,_i=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},Lr=[1,0,0,0,1,0,0,0,1],Bi=(t,e,r)=>{const[i,n,,s,o]=t,a=Math.abs(i)*e+Math.abs(s)*r,d=Math.abs(n)*e+Math.abs(o)*r;return Pt(Pt(Qt(-e/2,-r/2),t),Qt(a/2,d/2))},Ai=t=>{const e=t*xi,r=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[r,i,0,-i,r,0,0,0,1]},Qt=(t,e)=>[1,0,0,0,1,0,t,e,1],Pi=(t,e)=>[t,0,0,0,e,0,0,0,1],Pt=(t,e)=>{const r=new Array(9);for(let i=0;i<3;i++)for(let n=0;n<3;n++)r[3*i+n]=t[3*i]*e[n]+t[3*i+1]*e[3+n]+t[3*i+2]*e[6+n];return r},ki=(t,e,r,i)=>({rotation:_i(t+(e?-r:r)),flip:e!==i}),G=t=>t&&t[t.length-1],ye=t=>t>=0&&t<2**32,Ii=t=>t>=-2147483648&&t<2**31,T=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+t.readBits(e)},we=t=>{const e=T(t);return e%2===0?-(e/2):(e+1)/2},$=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),re=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Fi=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const r=new Uint8Array(3*e.length);let i=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s<128)r[i++]=s;else if(s<2048)r[i++]=192|s>>6,r[i++]=128|s&63;else if(s<55296||s>57343)r[i++]=224|s>>12,r[i++]=128|s>>6&63,r[i++]=128|s&63;else{const o=n+1<e.length?e.charCodeAt(n+1):0;s<56320&&o>=56320&&o<=57343?(s=65536+(s-55296<<10)+(o-56320),n++,r[i++]=240|s>>18,r[i++]=128|s>>12&63,r[i++]=128|s>>6&63,r[i++]=128|s&63):(r[i++]=239,r[i++]=191,r[i++]=189)}}return r.slice(0,i)}},me=new Fi,ze={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},We={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Le={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Ri=t=>!t||t.primaries==null&&t.transfer==null&&t.matrix==null&&t.fullRange==null,nt=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t);class Nr{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const r=new Promise(n=>{let s=!1;e=()=>{s||(n(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=r,this.pending++,await i,e}}const Gt=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),Xt=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),Kt=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){const o=i+(n-i+1)/2|0;r(t[o])<=e?(s=o,i=o+1):n=o-1}return s},Vr=()=>{let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}},Be=t=>{throw new Error(`Unexpected value: ${t}`)},Mi=(t,e,r)=>{const i=t.getUint8(e),n=t.getUint8(e+1),s=t.getUint8(e+2);return i<<16|n<<8|s},Wt=(t,e,r,i)=>{r=r>>>0,r=r&16777215,i?(t.setUint8(e,r&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r>>>16&255)):(t.setUint8(e,r>>>16&255),t.setUint8(e+1,r>>>8&255),t.setUint8(e+2,r&255))},Oi=(t,e,r,i)=>{r=D(r,-8388608,8388607),r<0&&(r=r+16777216&16777215),Wt(t,e,r,i)},D=(t,e,r)=>Math.max(e,Math.min(r,t)),zi=(t,e,r)=>t+(e-t)*r,Wi="und",Yt=(t,e)=>Math.round(t/e)*e,Zt=(t,e)=>Math.round(t*e)/e,Jt=(t,e)=>Math.floor(t*e)/e,Li=t=>{let e=0;for(;t!==0;)t&=t-1,e++;return e},Ni=/^[a-z]{3}$/,Vi=t=>Ni.test(t),Se=1e6*(1+Number.EPSILON),Ui=(t,e)=>{const r=t<0?-1:1;t=Math.abs(t);let i=0,n=1,s=1,o=0,a=t;for(;;){const d=Math.floor(a),c=d*s+i,l=d*o+n;if(l>e)return{num:r*s,den:o};if(i=s,n=o,s=c,o=l,a=1/(a-d),!isFinite(a))break}return{num:r*s,den:o}};class Ur{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let lt=null;const Hi=()=>lt!==null?lt:lt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let dt=null;const rt=()=>dt!==null?dt:dt=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let ut=null;const qi=()=>ut!==null?ut:ut=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));let ft=null;const Di=()=>{if(ft!==null)return ft;if(typeof navigator>"u")return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?ft=Number(t[1]):null},Hr=t=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${t} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${t} is not available in this environment.`,$i=t=>t instanceof DOMException&&t.name==="QuotaExceededError"&&/reclaimed/i.test(t.message),ji=(async()=>{})().constructor,_e=t=>t instanceof ji||t instanceof Promise?!0:typeof t?.then=="function",qr=function*(t){for(const e in t){const r=t[e];r!==void 0&&(yield{key:e,value:r})}},Qi=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Gi=t=>typeof t=="number"&&!Number.isNaN(t),Xi=(t,e)=>{let r=-1,i=1/0;for(let n=0;n<t.length;n++){const s=e(t[n]);s<i&&(i=s,r=n)}return r},Dr=t=>{p(Number.isInteger(t.num)),p(Number.isInteger(t.den)),p(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){const n=e%r;e=r,r=n}const i=e||1;return{num:t.num/i,den:t.den/i}},ht=(t,e)=>{if(typeof t!="object"||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},Ki=t=>new Promise(e=>setTimeout(e,t)),er=t=>Array.isArray(t)?t:[t];class Lt{constructor(){this._listeners=new Map}on(e,r,i){this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:r,once:i?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){const[r,i]=e,n=this._listeners.get(r);if(n)for(const s of n){try{s.fn(i)}catch(o){console.error(o)}s.once&&n.delete(s)}}}const Yi=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(e=>typeof e=="string");/*!
|
|
8
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
9
|
+
*
|
|
10
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
11
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
12
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
13
|
+
*/var fe;(function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"})(fe||(fe={}));class L{constructor(){}static get level(){return L._level}static set level(e){if(e!==fe.Silent&&e!==fe.Errors&&e!==fe.Warnings&&e!==fe.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");L._level=e}static get _emitter(){return L._emitterInstance??=new Lt}static on(e,r,i){return L._emitter.on(e,r,i)}static _error(...e){L._emitter._emit("error",e),L._level>=fe.Errors&&console.error(...e)}static _warn(...e){L._emitter._emit("warn",e),L._level>=fe.Warnings&&console.warn(...e)}static _info(...e){L._emitter._emit("info",e),L._level>=fe.Info&&console.info(...e)}}L._level=fe.Info;L._emitterInstance=null;/*!
|
|
14
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
15
|
+
*
|
|
16
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
17
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
18
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
19
|
+
*/class $r{constructor(e,r){if(this.data=e,this.mimeType=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof r!="string")throw new TypeError("mimeType must be a string.")}}class Zi{constructor(e,r,i,n){if(this.data=e,this.mimeType=r,this.name=i,this.description=n,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!==void 0&&typeof r!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}}const Ji=t=>{if(!t||typeof t!="object")throw new TypeError("tags must be an object.");if(t.title!==void 0&&typeof t.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(t.artist!==void 0&&typeof t.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(t.album!==void 0&&typeof t.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(t.albumArtist!==void 0&&typeof t.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(t.trackNumber!==void 0&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(t.tracksTotal!==void 0&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(t.discNumber!==void 0&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(t.discsTotal!==void 0&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(t.genre!==void 0&&typeof t.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(t.date!==void 0&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(t.beatsPerMinute!==void 0&&(!Number.isInteger(t.beatsPerMinute)||t.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(t.lyrics!==void 0&&typeof t.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(t.images!==void 0){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(t.comment!==void 0&&typeof t.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(t.raw!==void 0){if(!t.raw||typeof t.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(r=>typeof r=="string"))&&!(e instanceof Uint8Array)&&!(e instanceof $r)&&!(e instanceof Zi)&&!Yi(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},en=t=>{if(!t||typeof t!="object")throw new TypeError("disposition must be an object.");if(t.default!==void 0&&typeof t.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(t.primary!==void 0&&typeof t.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(t.forced!==void 0&&typeof t.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(t.original!==void 0&&typeof t.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(t.commentary!==void 0&&typeof t.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(t.hearingImpaired!==void 0&&typeof t.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(t.visuallyImpaired!==void 0&&typeof t.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
|
|
20
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
21
|
+
*
|
|
22
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
23
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
24
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
25
|
+
*/class V{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){const i=this.pos+e;for(let n=this.pos;n<i;n++){const s=Math.floor(n/8);let o=this.bytes[s];const a=7-(n&7);o&=~(1<<a),o|=(r&1<<i-n-1)>>i-n-1<<a,this.bytes[s]=o}this.pos=i}copyBits(e,r){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,r.readBits(8));const n=e-i;n>0&&this.writeBits(n,r.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new V(this.bytes);return e.pos=this.pos,e}}/*!
|
|
26
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
27
|
+
*
|
|
28
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
29
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
30
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
31
|
+
*/const $e=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Nt=[-1,1,2,3,4,5,6,8],tn=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new V(t),r=mt(e),{frequencyIndex:i,sampleRate:n}=pt(e),s=e.readBits(4);let o=null;s>=1&&s<=7&&(o=Nt[s]);let a=r,d=!1,c=n;if(r===5||r===29)d=r===29,c=pt(e).sampleRate,a=mt(e),a===22&&e.skipBits(4);else for(;e.getBitsLeft()>15;){const l=e.pos;if(e.readBits(11)!==695){e.pos=l+1;continue}mt(e)===5&&e.readBits(1)&&(c=pt(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(d=!!e.readBits(1)));break}return o!==null&&o>1&&(d=!1),{objectType:r,coreObjectType:a,frequencyIndex:i,channelConfiguration:s,outputSampleRate:c,outputNumberOfChannels:d&&o===1?2:o}},mt=t=>{const e=t.readBits(5);return e===31?32+t.readBits(6):e},pt=t=>{const e=t.readBits(4);return e===15?{frequencyIndex:e,sampleRate:t.readBits(24)}:{frequencyIndex:e,sampleRate:e<$e.length?$e[e]:null}},jr=t=>{const e=t.objectType===5||t.objectType===29,r=t.objectType===29,i=e?t.outputSampleRate/2:t.outputSampleRate,n=r?1:t.outputNumberOfChannels,s=Nt.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let o=16;t.objectType>=32&&(o+=6),kt(i)===15&&(o+=24),e&&(o+=9,kt(t.outputSampleRate)===15&&(o+=24));const a=Math.ceil(o/8),d=new Uint8Array(a),c=new V(d);return tr(c,t.objectType),rr(c,i),c.writeBits(4,s),e&&(rr(c,t.outputSampleRate),tr(c,2)),c.writeBits(3,0),d},tr=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},rr=(t,e)=>{const r=kt(e);t.writeBits(4,r),r===15&&t.writeBits(24,e)},kt=t=>{const e=$e.indexOf(t);return e===-1?15:e};/*!
|
|
32
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
33
|
+
*
|
|
34
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
35
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
36
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
37
|
+
*/const rn=[48e3,44100,32e3],nn=[24e3,22050,16e3];/*!
|
|
38
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
39
|
+
*
|
|
40
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
41
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
42
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
43
|
+
*/const sn="1.62.1",gt=`Mediabunny v${sn}`;/*!
|
|
44
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
45
|
+
*
|
|
46
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
47
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
48
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
49
|
+
*/var be;(function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"})(be||(be={}));var ee;(function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(ee||(ee={}));const Xe=function*(t){let e=0,r=-1;for(;e<t.length-2;){const i=t.indexOf(0,e);if(i===-1||i>=t.length-2)break;e=i;let n=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?n=4:t[e+1]===0&&t[e+2]===1&&(n=3),n===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+n,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})},Qr=function*(t,e){let r=0;const i=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;r+e<=t.length;){let n;e===1?n=i.getUint8(r):e===2?n=i.getUint16(r,!1):e===3?n=Mi(i,r):(p(e===4),n=i.getUint32(r,!1)),r+=e,yield{offset:r,length:n},r+=n}},on=(t,e)=>{if(e.description){const n=($(e.description)[4]&3)+1;return Qr(t,n)}else return Xe(t)},Gr=t=>t&31,st=t=>{const e=new Uint8Array(t.length),r=t.length;let i=0;for(let n=0;n<r;n++)n+2<r&&t[n]===0&&t[n+1]===0&&t[n+2]===3?(e[i++]=0,e[i++]=0,n+=2):e[i++]=t[n];return e.subarray(0,i)},an=(t,e)=>{const r=t.reduce((s,o)=>s+e+o.byteLength,0),i=new Uint8Array(r);let n=0;for(const s of t){const o=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:o.setUint8(n,s.byteLength);break;case 2:o.setUint16(n,s.byteLength,!1);break;case 3:Wt(o,n,s.byteLength,!1);break;case 4:o.setUint32(n,s.byteLength,!1);break}n+=e,i.set(s,n),n+=s.byteLength}return i},Xr=t=>{try{const e=[],r=[],i=[];for(const a of Xe(t)){const d=t.subarray(a.offset,a.offset+a.length),c=Gr(d[0]);c===be.SPS&&e.length<31?e.push(d):c===be.PPS&&r.length<255?r.push(d):c===be.SPS_EXT&&i.length<255&&i.push(d)}if(e.length===0||r.length===0)return null;const n=e[0],s=ln(n);if(!s)return null;const o=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:o?s.chromaFormatIdc:null,bitDepthLumaMinus8:o?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?i:null}}catch(e){return L._error("Error building AVC Decoder Configuration Record:",e),null}},Kr=t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(const r of t.sequenceParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(const r of t.pictureParameterSets){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if((t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144)&&t.chromaFormat!==null){p(t.bitDepthLumaMinus8!==null),p(t.bitDepthChromaMinus8!==null),p(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(const r of t.sequenceParameterSetExt){const i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)},cn=t=>{try{const e=re(t);let r=0;const i=e.getUint8(r++),n=e.getUint8(r++),s=e.getUint8(r++),o=e.getUint8(r++),a=e.getUint8(r++)&3,d=e.getUint8(r++)&31,c=[];for(let h=0;h<d;h++){const m=e.getUint16(r,!1);r+=2,c.push(t.subarray(r,r+m)),r+=m}const l=e.getUint8(r++),u=[];for(let h=0;h<l;h++){const m=e.getUint16(r,!1);r+=2,u.push(t.subarray(r,r+m)),r+=m}const f={configurationVersion:i,avcProfileIndication:n,profileCompatibility:s,avcLevelIndication:o,lengthSizeMinusOne:a,sequenceParameterSets:c,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&r+4<=t.length){const h=e.getUint8(r++)&3,m=e.getUint8(r++)&7,g=e.getUint8(r++)&7,b=e.getUint8(r++);f.chromaFormat=h,f.bitDepthLumaMinus8=m,f.bitDepthChromaMinus8=g;const w=[];for(let E=0;E<b;E++){const C=e.getUint16(r,!1);r+=2,w.push(t.subarray(r,r+C)),r+=C}f.sequenceParameterSetExt=w}return f}catch(e){return L._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Yr={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},ln=t=>{try{const e=st(t),r=new V(e);if(r.skipBits(1),r.skipBits(2),r.readBits(5)!==7)return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),o=r.readAlignedByte();T(r);let a=1,d=0,c=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=T(r),a===3&&(l=r.readBits(1)),d=T(r),c=T(r),r.skipBits(1),r.readBits(1))){for(let H=0;H<(a!==3?8:12);H++)if(r.readBits(1)){const se=H<6?16:64;let oe=8,Q=8;for(let Ee=0;Ee<se;Ee++){if(Q!==0){const Ae=we(r);Q=(oe+Ae+256)%256}oe=Q===0?oe:Q}}}T(r);const u=T(r);if(u===0)T(r);else if(u===1){r.skipBits(1),we(r),we(r);const j=T(r);for(let H=0;H<j;H++)we(r)}T(r),r.skipBits(1);const f=T(r),h=T(r),m=16*(f+1),g=16*(h+1);let b=m,w=g;const E=r.readBits(1);if(E||r.skipBits(1),r.skipBits(1),r.readBits(1)){const j=T(r),H=T(r),ne=T(r),se=T(r);let oe,Q;if((l===0?a:0)===0)oe=1,Q=2-E;else{const Ae=a===3?1:2,Ye=a===1?2:1;oe=Ae,Q=Ye*(2-E)}b-=oe*(j+H),w-=Q*(ne+se)}if(b<=0||w<=0)return null;let x=2,B=2,I=2,A=0,P={num:1,den:1},k=null,R=null,W=null,O=null;const q=r.pos;if(r.readBits(1)){if(r.readBits(1)){const Ae=r.readBits(8);if(Ae===255)P={num:r.readBits(16),den:r.readBits(16)};else{const Ye=Yr[Ae];Ye&&(P=Ye)}}r.readBits(1)&&r.skipBits(1),r.readBits(1)&&(r.skipBits(3),A=r.readBits(1),r.readBits(1)&&(x=r.readBits(8),B=r.readBits(8),I=r.readBits(8))),r.readBits(1)&&(T(r),T(r)),r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.skipBits(1));const Q=r.readBits(1);Q&&ir(r);const Ee=r.readBits(1);Ee&&ir(r),(Q||Ee)&&r.skipBits(1),r.skipBits(1),W=r.pos,O=r.readBits(1),O&&(r.skipBits(1),T(r),T(r),T(r),T(r),k=Math.min(T(r),16),R=Math.min(T(r),16))}if(k===null){p(R===null);const j=s&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&j)k=0,R=0;else{const H=f+1,ne=h+1,se=(2-E)*ne,oe=it.find(Ee=>Ee.level>=o)??G(it),Q=Math.min(Math.floor(oe.maxDpbMbs/(H*se)),16);k=Q,R=Q}}return p(R!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:s,levelIdc:o,frameMbsOnlyFlag:E,chromaFormatIdc:a,bitDepthLumaMinus8:d,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:g,displayWidth:b,displayHeight:w,pixelAspectRatio:P,colourPrimaries:x,matrixCoefficients:I,transferCharacteristics:B,fullRangeFlag:A,numReorderFrames:k,maxDecFrameBuffering:R,vuiParametersFlagBitOffset:q,bitstreamRestrictionFlagBitOffset:W,bitstreamRestrictionFlag:O}}catch(e){return L._error("Error parsing AVC SPS:",e),null}},ir=t=>{const e=T(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)T(t),T(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},dn=(t,e)=>{if(e.description){const n=($(e.description)[21]&3)+1;return Qr(t,n)}else return Xe(t)},It=t=>t>>1&63,un=t=>{try{const e=new V(st(t));e.skipBits(16),e.readBits(4);const r=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:o,general_profile_compatibility_flags:a,general_constraint_indicator_flags:d,general_level_idc:c}=fn(e,r);T(e);const l=T(e);let u=0;l===3&&(u=e.readBits(1));const f=T(e),h=T(e);let m=f,g=h;if(e.readBits(1)){const O=T(e),q=T(e),X=T(e),j=T(e);let H=1,ne=1;const se=u===0?l:0;se===1?(H=2,ne=2):se===2&&(H=2,ne=1),m-=(O+q)*H,g-=(X+j)*ne}if(m<=0||g<=0)return null;const b=T(e),w=T(e);T(e);const C=e.readBits(1)?0:r;let x=0;for(let O=C;O<=r;O++)T(e),x=T(e),T(e);T(e),T(e),T(e),T(e),T(e),T(e),e.readBits(1)&&e.readBits(1)&&hn(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),T(e),T(e),e.skipBits(1));const B=T(e);if(mn(e,B),e.readBits(1)){const O=T(e);for(let q=0;q<O;q++)T(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let I=2,A=2,P=2,k=0,R=0,W={num:1,den:1};if(e.readBits(1)){const O=gn(e,r);W=O.pixelAspectRatio,I=O.colourPrimaries,A=O.transferCharacteristics,P=O.matrixCoefficients,k=O.fullRangeFlag,R=O.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:g,pixelAspectRatio:W,colourPrimaries:I,transferCharacteristics:A,matrixCoefficients:P,fullRangeFlag:k,maxDecFrameBuffering:Math.min(x+1,16),spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:d,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:b,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:R}}catch(e){return L._error("Error parsing HEVC SPS:",e),null}},Zr=t=>{try{const e=[],r=[],i=[],n=[];for(const l of Xe(t)){const u=t.subarray(l.offset,l.offset+l.length),f=It(u[0]);f===ee.VPS_NUT&&e.length<65535?e.push(u):f===ee.SPS_NUT&&r.length<65535?r.push(u):f===ee.PPS_NUT&&i.length<65535?i.push(u):(f===ee.PREFIX_SEI_NUT||f===ee.SUFFIX_SEI_NUT)&&n.length<65535&&n.push(u)}if(r.length===0||i.length===0)return null;const o=un(r[0]);if(!o)return null;let a=0;if(i.length>0){const l=i[0],u=new V(st(l));u.skipBits(16),T(u),T(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),T(u),T(u),we(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&T(u),we(u),we(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const f=u.readBits(1),h=u.readBits(1);!f&&!h?a=0:f&&!h?a=2:!f&&h?a=3:a=0}const d=[...e.length?[{arrayCompleteness:1,nalUnitType:ee.VPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ee.SPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ee.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:It(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:d}}catch(e){return L._error("Error building HEVC Decoder Configuration Record:",e),null}},fn=(t,e)=>{const r=t.readBits(2),i=t.readBits(1),n=t.readBits(5);let s=0;for(let l=0;l<32;l++)s=s<<1|t.readBits(1);const o=new Uint8Array(6);for(let l=0;l<6;l++)o[l]=t.readBits(8);const a=t.readBits(8),d=[],c=[];for(let l=0;l<e;l++)d.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)d[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:a}},hn=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))T(t);else{const n=Math.min(64,1<<4+(e<<1));e>1&&we(t);for(let s=0;s<n;s++)we(t)}},mn=(t,e)=>{const r=[];for(let i=0;i<e;i++)r[i]=pn(t,i,e,r)},pn=(t,e,r,i)=>{let n=0,s=0,o=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){const d=T(t);o=e-(d+1)}else o=e-1;t.readBits(1),T(t);const a=i[o]??0;for(let d=0;d<=a;d++)t.readBits(1)||t.readBits(1);n=i[o]}else{const a=T(t),d=T(t);for(let c=0;c<a;c++)T(t),t.readBits(1);for(let c=0;c<d;c++)T(t),t.readBits(1);n=a+d}return n},gn=(t,e)=>{let r=2,i=2,n=2,s=0,o=0,a={num:1,den:1};if(t.readBits(1)){const d=t.readBits(8);if(d===255)a={num:t.readBits(16),den:t.readBits(16)};else{const c=Yr[d];c&&(a=c)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),i=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(T(t),T(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(T(t),T(t),T(t),T(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&T(t),t.readBits(1)&&wn(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),o=T(t),T(t),T(t),T(t),T(t)),{pixelAspectRatio:a,colourPrimaries:r,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:o}},wn=(t,e,r)=>{let i=!1,n=!1,s=!1;i=t.readBits(1)===1,n=t.readBits(1)===1,(i||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let o=0;o<=r;o++){const a=t.readBits(1)===1;let d=!0;a||(d=t.readBits(1)===1);let c=!1;d?T(t):c=t.readBits(1)===1;let l=1;c||(l=T(t)+1),i&&nr(t,l,s),n&&nr(t,l,s)}},nr=(t,e,r)=>{for(let i=0;i<e;i++)T(t),T(t),r&&(T(t),T(t)),t.readBits(1)},bn=t=>{const e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(const r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(const i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)};var sr;(function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"})(sr||(sr={}));const yn={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Tn=t=>{const e=new V(t);if(e.readBits(2)!==2)return null;const i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let c=8;s>=2&&(c=e.readBits(1)?12:10);const l=e.readBits(3);let u=0,f=0;if(l!==7)if(f=e.readBits(1),s===1||s===3){const P=e.readBits(1),k=e.readBits(1);u=!P&&!k?3:P&&!k?2:1,e.skipBits(1)}else u=1;else u=3,f=1;const h=e.readBits(16),m=e.readBits(16),g=h+1,b=m+1,w=g*b;let E=G(xe).level;for(const A of xe)if(w<=A.maxPictureSize){E=A.level;break}const C=yn[l],x=C?.colourPrimaries??2,B=C?.transferCharacteristics??2,I=C?.matrixCoefficients??2;return{profile:s,level:E,bitDepth:c,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:x,transferCharacteristics:B,matrixCoefficients:I}},Jr=function*(t){const e=new V(t),r=()=>{let i=0;for(let n=0;n<8;n++){const s=e.readAlignedByte();if(i+=(s&127)*2**(n*7),!(s&128))break;if(n===7&&s&128)return null}return i>2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let o;if(s){const a=r();if(a===null)return;o=a}else o=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:i,data:t.subarray(e.pos/8,e.pos/8+o)},e.skipBits(o*8)}},En=t=>{for(const{type:e,data:r}of Jr(t)){if(e!==1)continue;const i=new V(r),n=i.readBits(3);i.readBits(1);const s=i.readBits(1);let o=0,a=0,d=0;if(s)o=i.readBits(5);else{const k=i.readBits(1);let R=0;if(k){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let X=0;for(;X<32&&!i.readBits(1);)X++;X<32&&i.skipBits(X)}R=i.readBits(1),R&&(d=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const W=i.readBits(1),O=i.readBits(5);for(let q=0;q<=O;q++){i.skipBits(12);const X=i.readBits(5);if(q===0&&(o=X),X>7){const j=i.readBits(1);q===0&&(a=j)}if(R&&i.readBits(1)){const H=d+1;i.skipBits(H),i.skipBits(H),i.skipBits(1)}W&&i.readBits(1)&&i.skipBits(4)}}const c=i.readBits(4),l=i.readBits(4),u=c+1;i.skipBits(u);const f=l+1;i.skipBits(f);let h=0;if(s?h=0:h=i.readBits(1),h&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!s){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const k=i.readBits(1);k&&(i.skipBits(1),i.skipBits(1));const R=i.readBits(1);let W=0;R?W=2:W=i.readBits(1),W>0&&(i.readBits(1)||i.skipBits(1)),k&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const m=i.readBits(1);let g=8;n===2&&m?g=i.readBits(1)?12:10:n<=2&&(g=m?10:8);let b=0;n!==1&&(b=i.readBits(1));let w=2,E=2,C=2;i.readBits(1)&&(w=i.readBits(8),E=i.readBits(8),C=i.readBits(8));let B=0,I=1,A=1,P=0;return b?B=i.readBits(1):w===1&&E===13&&C===0?(B=1,I=0,A=0):(B=i.readBits(1),n===0?(I=1,A=1):n===1?(I=0,A=0):g===12?(I=i.readBits(1),A=I?i.readBits(1):0):(I=1,A=0),I&&A&&(P=i.readBits(2))),{profile:n,level:o,tier:a,bitDepth:g,monochrome:b,chromaSubsamplingX:I,chromaSubsamplingY:A,chromaSamplePosition:P,videoFullRangeFlag:B,colourPrimaries:w,transferCharacteristics:E,matrixCoefficients:C}}return null},Cn=t=>t.colourPrimaries!==2||t.transferCharacteristics!==2||t.matrixCoefficients!==2,vn=t=>{if(t.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=re(t),r=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),s=e.getInt16(16,!0),o=e.getUint8(18);let a=null;return o&&(a=t.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:n,outputGain:s,channelMappingFamily:o,channelMappingTable:a}},Sn=(t,e,r)=>{switch(t){case"avc":{for(const i of on(r,e)){const n=r[i.offset],s=Gr(n);if(s>=be.NON_IDR_SLICE&&s<=be.SLICE_DPC)return"delta";if(s===be.IDR)return"key";if(s===be.SEI&&!qi()){const o=r.subarray(i.offset,i.offset+i.length),a=st(o);let d=1;do{let c=0;for(;;){const f=a[d++];if(f===void 0||(c+=f,f<255))break}let l=0;for(;;){const f=a[d++];if(f===void 0||(l+=f,f<255))break}if(c===6){const f=new V(a);f.pos=8*d;let h=-1;try{h=T(f)}catch{}const m=f.readBits(1);if(h===0&&m===1)return"key"}d+=l}while(d<a.length-1)}}return"delta"}case"hevc":{for(const i of dn(r,e)){const n=It(r[i.offset]);if(n<ee.BLA_W_LP)return"delta";if(n<=ee.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(r[0]&1)===0?"key":"delta";case"vp9":{const i=new V(r);if(i.readBits(2)!==2)return null;const n=i.readBits(1);return(i.readBits(1)<<1)+n===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:n,data:s}of Jr(r))if(n===1){const o=new V(s);o.skipBits(4),i=!!o.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const o=new V(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Be(t),p(!1)}};var or;(function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"})(or||(or={}));const xn=t=>{if(t.length<7||t[0]!==11||t[1]!==119)return null;const e=new V(t);e.skipBits(16),e.skipBits(16);const r=e.readBits(2);if(r===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),o=e.readBits(3);(o&1)!==0&&o!==1&&e.skipBits(2),(o&4)!==0&&e.skipBits(2),o===2&&e.skipBits(2);const a=e.readBits(1),d=Math.floor(i/2);return{fscod:r,bsid:n,bsmod:s,acmod:o,lfeon:a,bitRateCode:d}},_n=[1,2,3,6],Bn=t=>{if(t.length<6||t[0]!==11||t[1]!==119)return null;const e=new V(t);e.skipBits(16);const r=e.readBits(2);if(e.skipBits(3),r!==0&&r!==2)return null;const i=e.readBits(11),n=e.readBits(2);let s=0,o;n===3?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),d=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const l=_n[o];let u;return n<3?u=rn[n]/1e3:u=nn[s]/1e3,{dataRate:Math.round((i+1)*u/(l*16)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:d,numDepSub:0,chanLoc:0}]}},An=1683496997,Pn=18,kn=10,ar=32,In=20,Fn=8,Rn=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Mn=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],On=[16,16,20,20,0,24,24,0],cr=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],zn=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Wn=8,Ln=[32e3,44100,48e3,0],Nn=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Vn=[512,1024,2048,4096],Un=t=>{const e=Hn(t),r=re(t);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=t.length&&r.getUint32(i)===An;){const o=qn(t.subarray(i));if(!o)break;n??=o,i+=o.frameSize}if(e)return{frameSize:n?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:n!==null};if(!n?.asset)return null;const{asset:s}=n;return{frameSize:i,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Hn=t=>{if(t.length<Pn||t[0]!==127||t[1]!==254||t[2]!==128||t[3]!==1)return null;const e=new V(t);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==ar-1)return null;const r=e.readBits(1),i=e.readBits(7)+1;if(i%Fn!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=cr.length)return null;const o=Rn[e.readBits(4)];if(o===0)return null;const a=Mn[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const d=e.readBits(2);if(d===3)return null;e.skipBits(1),r&&e.skipBits(16),e.skipBits(7);const c=On[e.readBits(3)];if(c===0)return null;const l=d!==0;return{frameSize:n,sampleRate:o,numberOfChannels:cr[s]+(l?1:0),sampleCount:i*ar,channelLayout:zn[s]|(l?Wn:0),amode:s,lfePresent:l,bitRate:a,pcmResolution:c}},qn=t=>{if(t.length<kn||t[0]!==100||t[1]!==88||t[2]!==32||t[3]!==37)return null;const e=new V(t);e.skipBits(32),e.skipBits(8);const r=e.readBits(2),i=e.readBits(1),n=8+4*i,s=16+4*i;e.skipBits(n);const o=e.readBits(s)+1,a={frameSize:o,asset:null};if(!e.readBits(1))return a;const d=Ln[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,u=e.readBits(3)+1,f=[];for(let w=0;w<l;w++)f.push(e.readBits(r+1));for(const w of f)e.skipBits(8*Li(w));if(e.readBits(1)){e.skipBits(2);const w=e.readBits(2)+1<<2,E=e.readBits(2)+1;e.skipBits(E*w)}for(let w=0;w<u;w++)e.skipBits(s);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const h=e.readBits(5)+1,m=Nn[e.readBits(4)],g=e.readBits(8)+1;let b=0;if(e.readBits(1)&&(g>2&&e.skipBits(1),g>6&&e.skipBits(1),e.readBits(1))){const w=e.readBits(2)+1<<2;b=e.readBits(w)}return d===0||e.getBitsLeft()<0?a:{frameSize:o,asset:{sampleRate:m,numberOfChannels:g,sampleCount:Math.round(c*m/d),channelLayout:b,pcmResolution:h}}},Dn=t=>{const e=new Uint8Array(In),r=re(e);r.setUint32(0,t.sampleRate),r.setUint32(4,t.bitRate),r.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const i=t.core&&!t.hasExtensions?1:0,n=new V(e);return n.seekToByte(13),n.writeBits(2,Math.max(Vn.indexOf(t.sampleCount),0)),n.writeBits(5,i),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e};/*!
|
|
50
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
51
|
+
*
|
|
52
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
53
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
54
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
55
|
+
*/const Te=["avc","hevc","vp9","av1","vp8","prores"],ce=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Vt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Fe=[...Vt,...ce],je=["webvtt"],it=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],lr=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],xe=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],dr=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],ur=".01.01.01.01.00",fr=".0.110.01.01.01.0",De=["ap4x","ap4h","apch","apcn","apcs","apco"],Ft=["dtsc","dtsh","dtsl","dtse"],$n=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],jn=(t,e,r,i,n)=>{if(t==="avc"){const o=Math.ceil(e/16)*Math.ceil(r/16),a=it.find(f=>o<=f.maxMacroblocks&&i<=f.maxBitrate)??G(it),d=a?a.level:0,c="64".padStart(2,"0"),l="00",u=d.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(t==="hevc"){const d=e*r,c=lr.find(u=>d<=u.maxPictureSize&&i<=u.maxBitrate)??G(lr);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const o=e*r;return`vp09.00.${(xe.find(c=>o<=c.maxPictureSize&&i<=c.maxBitrate)??G(xe)).level.toString().padStart(2,"0")}.08`}else if(t==="av1"){const o=e*r,a=dr.find(l=>o<=l.maxPictureSize&&i<=l.maxBitrate)??G(dr);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}else if(t==="prores"){const o=Math.pow(e*r/2073600,.95),a=$n.filter(l=>l.alpha===n);let d=a[0].fourCc,c=1/0;for(const{fourCc:l,bitrate:u}of a){const f=Math.abs(u*o-i);f<c&&(c=f,d=l)}return d}else Be(t)}throw new TypeError(`Unhandled codec '${String(t)}'.`)},Qn=t=>{const e=t.split("."),n=(1<<7)+1,s=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),d=(s<<5)+a,c=o.slice(-1)==="H"?1:0,l=Number(e[3]),u=l===8?0:1,f=l===12?1:0,h=e[4]?Number(e[4]):0,m=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,w=(c<<7)+(u<<6)+(f<<5)+(h<<4)+(m<<3)+(g<<2)+b;return[n,d,w,0]},Gn=t=>{const{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:o,av1CodecInfo:a,proresFormat:d}=t;if(e==="avc"){if(p(t.avcType!==null),n){const c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Gt(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Gt(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,f,h,m;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=Xt(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,m=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const b=re(r),w=b.getUint8(1);c=w>>6&3,l=w&31,u=Xt(b.getUint32(2)),f=w>>5&1,h=b.getUint8(12),m=[];for(let E=0;E<6;E++)m.push(b.getUint8(6+E))}let g="hev1.";for(g+=["","A","B","C"][c]+l,g+=".",g+=u.toString(16).toUpperCase(),g+=".",g+=f===0?"L":"H",g+=h;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(g+=".",g+=m.map(b=>b.toString(16).toUpperCase()).join(".")),g}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!o){const E=t.width*t.height;let C=G(xe).level;for(const x of xe)if(E<=x.maxPictureSize){C=x.level;break}return`vp09.00.${C.toString().padStart(2,"0")}.08`}const c=o.profile.toString().padStart(2,"0"),l=o.level.toString().padStart(2,"0"),u=o.bitDepth.toString().padStart(2,"0"),f=o.chromaSubsampling.toString().padStart(2,"0"),h=o.colourPrimaries.toString().padStart(2,"0"),m=o.transferCharacteristics.toString().padStart(2,"0"),g=o.matrixCoefficients.toString().padStart(2,"0"),b=o.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${c}.${l}.${u}.${f}`;return w+=`.${h}.${m}.${g}.${b}`,w.endsWith(ur)&&(w=w.slice(0,-ur.length)),w}else if(e==="av1"){if(!a){const x=t.width*t.height;let B=G(xe).level;for(const I of xe)if(x<=I.maxPictureSize){B=I.level;break}return`av01.0.${B.toString().padStart(2,"0")}M.08`}const c=a.profile,l=a.level.toString().padStart(2,"0"),u=a.tier?"H":"M",f=a.bitDepth.toString().padStart(2,"0"),h=a.monochrome?"1":"0",m=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0);let g,b,w,E;Cn(a)?(g=a.colourPrimaries,b=a.transferCharacteristics,w=a.matrixCoefficients,E=a.videoFullRangeFlag):(g=i?.primaries?ze[i.primaries]:1,b=i?.transfer?We[i.transfer]:1,w=i?.matrix?Le[i.matrix]:1,E=i?.fullRange?1:0);let C=`av01.${c}.${l}${u}.${f}`;return C+=`.${h}.${m.toString().padStart(3,"0")}`,C+=`.${g.toString().padStart(2,"0")}`,C+=`.${b.toString().padStart(2,"0")}`,C+=`.${w.toString().padStart(2,"0")}`,C+=`.${E}`,C.endsWith(fr)&&(C=C.slice(0,-fr.length)),C}else{if(e==="prores")return d??"apch";e!==null&&Be(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Xn=(t,e,r)=>{if(t==="aac")return e>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(t==="dts")return"dtsc";if(ce.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ei=/^pcm-([usf])(\d+)(be)?$/,Re=t=>{if(p(ce.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=ei.exec(t);p(e);let r;e[1]==="u"?r="unsigned":e[1]==="s"?r="signed":r="float";const i=Number(e[2])/8,n=e[3]!=="be",s=t==="pcm-u8"?2**7:0;return{dataType:r,sampleSize:i,littleEndian:n,silentValue:s}},ot=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":De.includes(t)?"prores":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"||t==="mp4a.40.34"?"mp3":t.startsWith("mp4a.40.")||t==="mp4a.67"?"aac":t==="opus"||t==="Opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ac-3"||t==="ac3"?"ac3":t==="ec-3"||t==="eac3"?"eac3":Ft.includes(t)?"dts":t==="ulaw"?"ulaw":t==="alaw"?"alaw":ei.test(t)?t:t==="webvtt"?"webvtt":null,Kn=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},Yn=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},Zn=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...De],Jn=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,es=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ts=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,rs=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ti=(t,e)=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Zn.some(r=>t.decoderConfig.codec.startsWith(r)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(t.decoderConfig.displayAspectWidth!==void 0!=(t.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(t.decoderConfig.description!==void 0&&!nt(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){const{colorSpace:r}=t.decoderConfig;if(typeof r!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(ze);if(r.primaries!=null&&!i.includes(r.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(We);if(r.transfer!=null&&!n.includes(r.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const s=Object.keys(Le);if(r.matrix!=null&&!s.includes(r.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(r.fullRange!=null&&typeof r.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!Jn.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!es.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!ts.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!rs.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(De.some(r=>t.decoderConfig.codec.startsWith(r))&&!De.some(r=>t.decoderConfig.codec===r))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${De.join(", ")}.`);if(e!==null&&ot(t.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},is=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],ri=(t,e)=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!is.some(r=>t.decoderConfig.codec.startsWith(r)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(t.decoderConfig.description!==void 0&&!nt(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if(t.decoderConfig.codec!=="mp3"&&t.decoderConfig.codec!=="mp4a.69"&&t.decoderConfig.codec!=="mp4a.6B"&&t.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if(t.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if(t.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if(t.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if(t.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if(t.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Ft.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Ft.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!ce.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ce.join(", ")}).`);if(e!==null&&ot(t.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},ns=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if(typeof t!="object")throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof t.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof t.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
|
|
56
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
57
|
+
*
|
|
58
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
59
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
60
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
61
|
+
*/const hr=new Uint8Array(0);class pe{constructor(e,r,i,n,s=-1,o,a){if(this.data=e,this.type=r,this.timestamp=i,this.duration=n,this.sequenceNumber=s,e===hr&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(r!=="key"&&r!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===hr}get microsecondTimestamp(){return Math.trunc(Se*this.timestamp)}get microsecondDuration(){return Math.trunc(Se*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,r){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new pe(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,r)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new pe(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}/*!
|
|
62
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
63
|
+
*
|
|
64
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
65
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
66
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
67
|
+
*/const ss=t=>{let r=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");if(t.codecStrings.length>0){const i=[...new Set(t.codecStrings)];r+=`; codecs="${i.join(", ")}"`}return r};/*!
|
|
68
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
69
|
+
*
|
|
70
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
71
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
72
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
73
|
+
*/const wt=8,mr=16,bt=t=>{let e=0;for(let r=0;r<4;r++){e<<=7;const i=ke(t);if(e|=i&127,(i&128)===0)break}return e},os=t=>{if(ke(t)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");bt(t),t.skip(2);const r=ke(t),i=(r&128)!==0,n=(r&64)!==0,s=(r&32)!==0;if(i&&t.skip(2),n){const u=ke(t);t.skip(u)}if(s&&t.skip(2),ke(t)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");const a=bt(t),d=t.filePos,c=ke(t);t.skip(12);let l=null;if(a>t.filePos-d){if(ke(t)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");const f=bt(t);l=fi(t,f)}return{objectTypeIndication:c,decoderSpecificInfo:l}};/*!
|
|
74
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
75
|
+
*
|
|
76
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
77
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
78
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
79
|
+
*/const Rt=7,as=9,pr=t=>{const e=t.filePos;if(t.remainingLength<Rt)return null;const r=fi(t,Rt),i=new V(r);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const o=i.readBits(1),a=i.readBits(2)+1,d=i.readBits(4);if(d>=$e.length)return null;i.skipBits(1);const c=i.readBits(3);if(c===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const l=i.readBits(13);i.skipBits(11);const u=i.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;if(o===0){if(t.remainingLength<2)return null;f=Ps(t)}return l<t.filePos-e?null:{objectType:a,samplingFrequencyIndex:d,channelConfiguration:c,frameLength:l,numberOfAacFrames:u,crcCheck:f,startPos:e}};/*!
|
|
80
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
81
|
+
*
|
|
82
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
84
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
85
|
+
*/var cs=function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],r&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:i,async:r})}else r&&t.stack.push({async:!0});return e},ls=(function(t){return function(e){function r(o){e.error=e.hasError?new t(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var o=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(o).then(s,function(a){return r(a),s()})}else n|=1}catch(a){r(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var i=new Error(r);return i.name="SuppressedError",i.error=t,i.suppressed=e,i});Qi();let gr=-1/0,wr=-1/0,Qe=null;typeof FinalizationRegistry<"u"&&(Qe=new FinalizationRegistry(t=>{const e=performance.now();t.type==="video"?(e-gr>=1e3&&(L._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."),gr=e),typeof VideoFrame<"u"&&t.data instanceof VideoFrame&&t.data.close()):(e-wr>=1e3&&(L._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."),wr=e),typeof AudioData<"u"&&t.data instanceof AudioData&&t.data.close())}));class Pe{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Mt=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ds=new Set(Mt);class K{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(Se*this.timestamp)}get microsecondDuration(){return Math.trunc(Se*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.format===void 0||!ds.has(r.format))throw new TypeError("init.format must be one of: "+Mt.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const s of r.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.visibleRect!==void 0&&ht(r.visibleRect,"init.visibleRect"),r.displayWidth!==void 0&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(r.displayHeight!==void 0&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(r.displayWidth!==void 0!=(r.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=r.format,this.rotation=r.rotation??0,this.flip=r.flip??!1,this.timestamp=r.timestamp,this.duration=r.duration??0;const i=r.layout??hs(r.format,r.codedWidth,r.codedHeight);let n=r.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},r.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180===0?r.displayHeight:r.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=r._doNotCopy?$(e):$(e).slice(),this._layout=i,this.colorSpace=new yt(n)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r?.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");r?.visibleRect!==void 0&&ht(r.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=r?.rotation??0,this.flip=r?.flip??!1,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6;const{primaries:i,transfer:n,matrix:s,fullRange:o}=e.colorSpace;this.colorSpace=new yt({primaries:i!==null&&i in ze?i:null,transfer:n!==null&&n in We?n:null,matrix:s!==null&&s in Le?s:null,fullRange:o})}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(r.visibleRect!==void 0&&ht(r.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new K(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*Se),duration:Math.trunc((r.duration??0)*Se)||void 0,visibleRect:r.visibleRect&&{x:r.visibleRect.left,y:r.visibleRect.top,width:r.visibleRect.width,height:r.visibleRect.height}}),r);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const s=r.visibleRect??{left:0,top:0,width:i,height:n},o=new OffscreenCanvas(s.width,s.height),a=o.getContext("2d",{alpha:rt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-s.left,-s.top),this._data=o,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:s.width,height:s.height},this.squarePixelWidth=s.width,this.squarePixelHeight=s.height,this.rotation=r.rotation??0,this.flip=r.flip??!1,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new yt({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Pe){if(!r||typeof r!="object")throw new TypeError("init must be an object.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Mt.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=r.rotation??0,this.flip=r.flip??!1,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=r?.encodeOptions??{},this.pixelAspectRatio=Dr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Qe?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),this._data instanceof Pe?new K(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Ve(this._data)?new K(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(p(this._layout),new K(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 K(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||(Qe?.unregister(this),this._data instanceof Pe?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ve(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Er(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Ve(this._data)?this._data.allocationSize(e):Cr(this,e).allocationSize}async copyTo(e,r={}){if(!nt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Er(r),this._closed)throw new Error("VideoSample is closed.");if((r.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(p(this._data!==null),Ve(this._data))return this._data.copyTo(e,r);if(r.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(r.format))if(this._data instanceof Pe){const c={stack:[],error:void 0,hasError:!1};try{const l=cs(c,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},r.colorSpace??"srgb"),!1);if(!(l instanceof K))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(l.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${l.format}' instead.`);return await l.copyTo(e,r)}catch(l){c.error=l,c.hasError=!0}finally{ls(c)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const c=this.toVideoFrame(),l=await c.copyTo(e,r);return c.close(),l}const i=Cr(this,r);p(this.format);const n=$(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=at(this.format);let o;if(this._data instanceof Pe){let c=this._data.getDataPlanes();if(_e(c)&&(c=await c),!Array.isArray(c)||c.some(l=>!(l.data instanceof Uint8Array)||!Number.isInteger(l.stride)||l.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=c}else if(this._data instanceof Uint8Array)p(this._layout),p(this._layout.length===s.length),o=this._layout.map((c,l)=>{const u=Math.ceil(this.codedHeight/s[l].heightDivisor);return{data:this._data.subarray(c.offset,c.offset+c.stride*u),stride:c.stride}});else{const l=this._data.getContext("2d");p(l);const u=l.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:$(u.data),stride:4*this.codedWidth}]}const a=[],d=s.length;for(let c=0;c<d;c++){const l=i.computedLayouts[c],u=o[c].stride,f=o[c].data;let h=l.sourceTop*u;h+=l.sourceLeftBytes;let m=l.destinationOffset;const g=l.sourceWidthBytes,b={offset:m,stride:l.destinationStride};for(let w=0;w<l.sourceHeight;w++){if(h+g>f.byteLength)throw new Error("Source buffer OOB read.");if(m+g>n.byteLength)throw new Error("Destination buffer OOB write.");const E=f.subarray(h,h+g);n.set(E,m),h+=u,m+=l.destinationStride}a.push(b)}if(r.format!==void 0){const c=this.format.startsWith("RGB")!==r.format.startsWith("RGB"),l=this.format.includes("X")&&r.format.includes("A");if(c||l)for(let u=0;u<i.allocationSize;u+=4){if(c){const f=n[u],h=n[u+2];n[u]=h,n[u+2]=f}l&&(n[u+3]=255)}}return a}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Pe){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(_e(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const r=e.reduce((o,a)=>o+a.data.byteLength,0),i=new Uint8Array(r);let n=0;const s=[];for(const o of e)i.set(o.data,n),s.push(n),n+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((o,a)=>({offset:s[a],stride:o.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Ve(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(p(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,r,i,n,s,o,a,d,c){let l=0,u=0,f=this.displayWidth,h=this.displayHeight,m=0,g=0,b=this.displayWidth,w=this.displayHeight;if(o!==void 0?(l=r,u=i,f=n,h=s,m=o,g=a,d!==void 0?(b=d,w=c):(b=f,w=h)):(m=r,g=i,n!==void 0&&(b=n,w=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:f,sHeight:h}=this._unmapSourceRegion(l,u,f,h,this.rotation,this.flip));const E=this.toCanvasImageSource();e.save();const C=m+b/2,x=g+w/2;e.translate(C,x),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const B=this.rotation%180===0?1:b/w;e.scale(1/B,B),e.drawImage(E,l,u,f,h,-b/2,-w/2,b,w),e.restore()}drawWithFit(e,r){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");r.crop!==void 0&&Ot(r.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=r.rotation??this.rotation,o=r.flip??this.flip,[a,d]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=r.crop;c&&(c=Tr(c,a,d));let l,u,f,h;const{sx:m,sy:g,sWidth:b,sHeight:w}=this._unmapSourceRegion(r.crop?.left??0,r.crop?.top??0,r.crop?.width??a,r.crop?.height??d,s,o);if(r.fit==="fill")l=0,u=0,f=i,h=n;else{const[C,x]=r.crop?[r.crop.width,r.crop.height]:[a,d],B=r.fit==="contain"?Math.min(i/C,n/x):Math.max(i/C,n/x);f=C*B,h=x*B,l=(i-f)/2,u=(n-h)/2}e.save();const E=s%180===0?1:f/h;e.translate(i/2,n/2),o&&e.scale(-1,1),e.rotate(s*Math.PI/180),e.scale(1/E,E),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),m,g,b,w,l,u,f,h),e.restore()}_unmapSourceRegion(e,r,i,n,s,o){return o&&(e=(s%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-i),s===90?[e,r,i,n]=[r,this.squarePixelHeight-e-i,n,i]:s===180?[e,r]=[this.squarePixelWidth-e-i,this.squarePixelHeight-r-n]:s===270&&([e,r,i,n]=[this.squarePixelWidth-r-n,e,n,i]),{sx:e,sy:r,sWidth:i,sHeight:n}}_drawWithFitAndMipmapping(e,r,i){const n=e.width,s=e.height,[o,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],d=i.crop?i.crop.width:o,c=i.crop?i.crop.height:a;let l=0;2*n<d&&2*s<c&&(l=Math.floor(Math.log2(Math.min(d/n,c/s))));const u=n*2**l,f=s*2**l,{canvas:h,context:m,isNew:g}=l>0?yr(u,f):{canvas:e,context:r,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,u,f)):g||m.clearRect(0,0,u,f),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,flip:i.flip,crop:i.crop}),m.globalCompositeOperation="copy";for(let b=l;b>1;b--){const w=n*2**b,E=s*2**b;m.drawImage(h,0,0,w,E,0,0,w/2,E/2)}m.globalCompositeOperation="source-over",l>0&&(r.imageSmoothingQuality="high",r.globalCompositeOperation="copy",r.drawImage(h,0,0,2*n,2*s,0,0,n,s),r.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof Pe||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&Ot(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const{rotation:r,flip:i}=ki(this.rotation,this.flip,e.rotate??0,e.flip??!1),[n,s]=r%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=Tr(o,n,s));const a=o?o.width:n,d=o?o.height:s,c=a/d;let l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=d),l=Yt(l,e.roundDimensionsTo??1),u=Yt(u,e.roundDimensionsTo??1);const f={width:l,height:u,fit:e.fit??"fill",rotation:r,flip:i,crop:o??{left:0,top:0,width:n,height:s},alpha:e.alpha??"keep"};for(const b of us){let w=b(this,f);if(_e(w)&&(w=await w),w!==null)return w}const{canvas:h,context:m,isNew:g}=yr(f.width,f.height);return this._drawWithFitAndMipmapping(h,m,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:g,fillBlack:f.alpha==="discard"}),new K(h,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setFlip(e){if(typeof e!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const us=[],fs=3,Ne=[];let br=0;const yr=(t,e)=>{for(const n of Ne)if(n.canvas.width===t&&n.canvas.height===e)return n.age=br++,{canvas:n.canvas,context:n.context,isNew:!1};let r;if(typeof OffscreenCanvas<"u")r=new OffscreenCanvas(t,e);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");r=document.createElement("canvas"),r.width=t,r.height=e}const i=r.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Ne.length>=fs&&Ne.splice(Xi(Ne,n=>n.age),1),Ne.push({canvas:r,context:i,age:br++}),{canvas:r,context:i,isNew:!0}};class yt{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const r=Object.keys(ze);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${r.join(", ")}.`);const i=Object.keys(We);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const n=Object.keys(Le);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Ve=t=>typeof VideoFrame<"u"&&t instanceof VideoFrame,Tr=(t,e,r)=>{const i=Math.min(t.left,e),n=Math.min(t.top,r),s=Math.min(t.width,e-i),o=Math.min(t.height,r-n);return p(s>=0),p(o>=0),{left:i,top:n,width:s,height:o}},Ot=(t,e)=>{if(!t||typeof t!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Er=t=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.colorSpace!==void 0&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(t.format!==void 0&&typeof t.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.rect!==void 0){if(!t.rect||typeof t.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(t.rect.x!==void 0&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(t.rect.y!==void 0&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(t.rect.width!==void 0&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(t.rect.height!==void 0&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},hs=(t,e,r)=>{const i=at(t),n=[];let s=0;for(const o of i){const a=Math.ceil(e/o.widthDivisor),d=Math.ceil(r/o.heightDivisor),c=a*o.sampleBytes,l=c*d;n.push({offset:s,stride:c}),s+=l}return n},at=t=>{const e=(r,i,n,s,o)=>{const a=[{sampleBytes:r,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:n,heightDivisor:s},{sampleBytes:i,widthDivisor:n,heightDivisor:s}];return o&&a.push({sampleBytes:r,widthDivisor:1,heightDivisor:1}),a};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Be(t),p(!1)}},Cr=(t,e)=>{const r={left:0,top:0,width:t.codedWidth,height:t.codedHeight},i=e.rect,n=ms(r,i,t.codedWidth,t.codedHeight,t.format),s=e.layout;let o;if(!e.format||e.format===t.format)o=t.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))o=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return gs(n,o,s)},ms=(t,e,r,i,n)=>{const s={...t};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>r)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!ps(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},ps=(t,e)=>{if(t===null)return!0;const r=at(t);for(let i=0;i<r.length;i++){const n=r[i],s=n.widthDivisor,o=n.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%o!==0)return!1}return!0},gs=(t,e,r)=>{const i=at(e),n=i.length;if(r!==void 0&&r.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const o=[],a=[];for(let d=0;d<n;d++){const c=i[d],l=c.sampleBytes,u=c.widthDivisor,f=c.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(t.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(t.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/u)*l,h.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/u)*l,r!==void 0){const b=r[d];if(b.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${d} is too small.`);h.destinationOffset=b.offset,h.destinationStride=b.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const g=h.destinationStride*h.sourceHeight+h.destinationOffset;if(g>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(g),s=Math.max(s,g);for(let b=0;b<d;b++){const w=o[b];if(!(a[d]<=w.destinationOffset||a[b]<=h.destinationOffset))throw new TypeError("Planes overlap.")}o.push(h)}return{allocationSize:s,computedLayouts:o}},Ze=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ue{constructor(){this._referenceCount=0}}class Y{get microsecondTimestamp(){return Math.trunc(Se*this.timestamp)}get microsecondDuration(){return Math.trunc(Se*this.duration)}constructor(e){if(this._closed=!1,He(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Ue){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Ze.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ze.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const r=e.data.byteLength/(ve(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*ve(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Qe?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Ze.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const r=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=ve(r),o=Ie(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(o?n:n*this.numberOfChannels)*s}copyTo(e,r){if(!nt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(r.planeIndex)||r.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(r.format!==void 0&&!Ze.has(r.format))throw new TypeError("Invalid format.");if(r.frameOffset!==void 0&&(!Number.isInteger(r.frameOffset)||r.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(r.frameCount!==void 0&&(!Number.isInteger(r.frameCount)||r.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:s}=r;let{planeIndex:o}=r,a=this.format;const d=i??this.format;if(!d)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=s??0;if(u>=c)throw new RangeError("frameOffset out of range");const f=n!==void 0?n:c-u;if(f>c-u)throw new RangeError("frameCount out of range");const h=ve(d),m=Ie(d);if(m&&o>=l)throw new RangeError("planeIndex out of range");if(!m&&o!==0)throw new RangeError("planeIndex out of range");const b=(m?f:f*l)*h;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");const w=re(e),E=ni(d);if(He(this._data))if(Hi()&&l>2&&d!==a){bs(this._data,w,a,d,l,o,u,f);return}else try{this._data.copyTo(e,{planeIndex:o,frameOffset:u,frameCount:f,format:d});return}catch(P){if(d==="f32-planar")throw P;a="f32-planar"}const C=ii(a),x=ve(a),B=Ie(a);let I;if(this._data instanceof Ue){const P=k=>{const R=this._data.getDataPlane(k);if(!(R instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const W=c*x*(B?1:l);if(R.byteLength!==W)throw new TypeError(`Data plane ${k} has invalid size. Expected exactly ${W} bytes, got ${R.byteLength} bytes.`);return R};if(B)if(m)I=P(o),o=0;else{I=new Uint8Array(c*x*l);for(let k=0;k<l;k++){const R=P(k);I.set(R,k*c*x)}}else I=P(0)}else if(this._data instanceof Uint8Array)I=this._data;else if(p(a==="f32-planar"),m)I=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:o})),this._data.copyTo(I,{format:"f32-planar",planeIndex:o}),o=0;else{I=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let P=0;P<l;P++)this._data.copyTo(I.subarray(P*c*x,(P+1)*c*x),{format:"f32-planar",planeIndex:P})}const A=re(I);for(let P=0;P<f;P++)if(m){const k=P*h;let R;B?R=(o*c+(P+u))*x:R=((P+u)*l+o)*x;const W=C(A,R);E(w,k,W)}else for(let k=0;k<l;k++){const W=(P*l+k)*h;let O;B?O=(k*c+(P+u))*x:O=((P+u)*l+k)*x;const q=C(A,O);E(w,W,q)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Ue){const e=new Y(this._data);return e.setTimestamp(this.timestamp),e}else if(He(this._data)){const e=new Y(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Y({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,r=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(r)||r<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(r>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(r<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=r-e,n=ve(this.format);let s;if(Ie(this.format)){const o=i*n;if(s=new Uint8Array(o*this.numberOfChannels),i>0)for(let a=0;a<this.numberOfChannels;a++)this.copyTo(s.subarray(a*o,(a+1)*o),{planeIndex:a,format:this.format,frameOffset:e,frameCount:i})}else s=new Uint8Array(i*this.numberOfChannels*n),i>0&&this.copyTo(s,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Y({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Qe?.unregister(this),this._data instanceof Ue?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):He(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Ue?this._createAudioDataFromData():He(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(Ie(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),r=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(r,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:r})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),r=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(r,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(r,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n);let d=0,c=o;for(;c>0;){const l=Math.min(a,c),u=new Float32Array(n*l);for(let f=0;f<n;f++)e.copyFromChannel(u.subarray(f*l,(f+1)*l),f,d);yield new Y({format:"f32-planar",sampleRate:s,numberOfFrames:l,numberOfChannels:n,timestamp:r+d/s,data:u}),d+=l,c-=l}}static fromAudioBuffer(e,r){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,s=e.sampleRate,o=e.length,a=Math.floor(i/n);let d=0,c=o;const l=[];for(;c>0;){const u=Math.min(a,c),f=new Float32Array(n*u);for(let m=0;m<n;m++)e.copyFromChannel(f.subarray(m*u,(m+1)*u),m,d);const h=new Y({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:n,timestamp:r+d/s,data:f});l.push(h),d+=u,c-=u}return l}}const ve=t=>{switch(t){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Ie=t=>{switch(t){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},ii=t=>{switch(t){case"u8":case"u8-planar":return(e,r)=>(e.getUint8(r)-128)/128;case"s16":case"s16-planar":return(e,r)=>e.getInt16(r,!0)/32768;case"s32":case"s32-planar":return(e,r)=>e.getInt32(r,!0)/2147483648;case"f32":case"f32-planar":return(e,r)=>e.getFloat32(r,!0)}},ni=t=>{switch(t){case"u8":case"u8-planar":return(e,r,i)=>e.setUint8(r,D(Math.round(i*128)+128,0,255));case"s16":case"s16-planar":return(e,r,i)=>e.setInt16(r,D(Math.round(i*32768),-32768,32767),!0);case"s32":case"s32-planar":return(e,r,i)=>e.setInt32(r,D(Math.round(i*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,r,i)=>e.setFloat32(r,i,!0)}},He=t=>typeof AudioData<"u"&&t instanceof AudioData,ws=t=>{switch(t){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return t}},bs=(t,e,r,i,n,s,o,a)=>{const d=ii(r),c=ni(i),l=ve(r),u=ve(i),f=Ie(r);if(Ie(i))if(f){const m=new ArrayBuffer(a*l),g=re(m);t.copyTo(m,{planeIndex:s,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++){const w=b*l,E=b*u,C=d(g,w);c(e,E,C)}}else{const m=new ArrayBuffer(a*n*l),g=re(m);t.copyTo(m,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++){const w=(b*n+s)*l,E=b*u,C=d(g,w);c(e,E,C)}}else if(f){const m=a*l,g=new ArrayBuffer(m),b=re(g);for(let w=0;w<n;w++){t.copyTo(g,{planeIndex:w,frameOffset:o,frameCount:a,format:r});for(let E=0;E<a;E++){const C=E*l,x=(E*n+w)*u,B=d(b,C);c(e,x,B)}}}else{const m=new ArrayBuffer(a*n*l),g=re(m);t.copyTo(m,{planeIndex:0,frameOffset:o,frameCount:a,format:r});for(let b=0;b<a;b++)for(let w=0;w<n;w++){const E=b*n+w,C=E*l,x=E*u,B=d(g,C);c(e,x,B)}}},ys=(t,e)=>{const r=t.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(r);return t.copyTo(i,{format:e,planeIndex:0}),new Y({data:i,format:e,numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,timestamp:t.timestamp,duration:t.duration})};/*!
|
|
86
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
87
|
+
*
|
|
88
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
89
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
90
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
91
|
+
*/const vr=new Map,Sr=new Map,Ts=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Te.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Te.join(", ")}.`);const e=t.bitrate;if(t.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(t.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(t.quality!==void 0&&!(t.quality instanceof J))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof J)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.transform!==void 0){if(typeof t.transform!="object"||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(t.transform.width!==void 0&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(t.transform.height!==void 0&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(t.transform.fit!==void 0&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.transform.width!==void 0&&t.transform.height!==void 0&&t.transform.fit===void 0&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(t.transform.fit!==void 0&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(t.transform.rotate!==void 0&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(t.transform.flip!==void 0&&typeof t.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(t.transform.crop!==void 0&&Ot(t.transform.crop,"config.transform."),t.transform.process!==void 0&&typeof t.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(t.transform.frameRate!==void 0&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(t.transform.force!==void 0&&typeof t.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(t.onEncodedSample!==void 0&&typeof t.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");si(t.codec,t)},si=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const r=e.bitrateMode;if(r!==void 0&&!["constant","variable"].includes(r))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&ot(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},oi=t=>{const e=t.bitrateMode,r=t.quality._toVideoRateControl(t.codec,t.width,t.height,e),i=(s,o,a)=>({codec:t.fullCodecString??jn(t.codec,t.width,t.height,a,t.alpha==="keep"),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:s,bitrateMode:o,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...Kn(t.codec)}),n=[];return r.quantizer!==null&&n.push({config:i(void 0,"quantizer",r.bitrate),quantizer:r.quantizer}),r.bitrateMode!=="quantizer"&&n.push({config:i(r.bitrate,r.bitrateMode,r.bitrate),quantizer:null}),p(n.length>0),n},Es=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!Fe.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${Fe.join(", ")}.`);const e=t.bitrate;if(t.quality===void 0&&e===void 0&&!(ce.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(t.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(t.quality!==void 0&&!(t.quality instanceof J))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof J)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.transform!==void 0){if(typeof t.transform!="object"||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(t.transform.numberOfChannels!==void 0&&(!Number.isInteger(t.transform.numberOfChannels)||t.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(t.transform.sampleRate!==void 0&&(!Number.isInteger(t.transform.sampleRate)||t.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(t.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(t.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(t.transform.process!==void 0&&typeof t.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(t.onEncodedSample!==void 0&&typeof t.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");ai(t.codec,t)},ai=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");const r=e.bitrateMode;if(r!==void 0&&!["constant","variable"].includes(r))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&ot(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},ci=t=>{const e=t.bitrateMode;return{codec:t.fullCodecString??Xn(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:t.quality?._toAudioBitrate(t.codec),bitrateMode:t.quality?._bitrateMode??e,...Yn(t.codec)}};class J{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in xr):typeof e.quality!="number"||Number.isNaN(e.quality))throw new 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 new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?xr[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 new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new 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,r,i,n){const s=Cs[e];let o=null,a=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(s)if(this._quantizer<s.min||this._quantizer>s.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${s.min} and ${s.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(a="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&s&&!this._preferBitrate&&(p(this._quality!==void 0),o=D(Math.round(zi(s.worst,s.best,this._quality)),s.min,s.max));let d;if(this._bitrate!==void 0)d=this._bitrate;else{let c=this._quality;c===void 0&&(p(o!==null&&s),c=D((o-s.worst)/(s.best-s.worst),0,1)),d=_r(e,r,i,Tt(c))}return{quantizer:o,bitrate:d,bitrateMode:a}}_toVideoBitrate(e,r,i){return this._bitrate!==void 0?this._bitrate:(p(this._quality!==void 0),_r(e,r,i,Tt(this._quality)))}_toAudioBitrate(e){if(ce.includes(e)||e==="flac")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const r=Tt(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let s=n*r;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,d)=>Math.abs(d-s)<Math.abs(a-s)?d:a):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,d)=>Math.abs(d-s)<Math.abs(a-s)?d:a)),Math.round(s/1e3)*1e3}}const xr={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Cs={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(Di()??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}},Tt=t=>.3*Math.exp(2.5538*t),_r=(t,e,r,i)=>{const n=e*r,s=1920*1080,o=3e6,a=Math.pow(n/s,.95),d=o*a,c={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/o},u=d*c[t]*i;return Math.ceil(u/1e3)*1e3},li=(t,e)=>{if(t==="avc")return{avc:{quantizer:e}};if(t==="hevc")return{hevc:{quantizer:e}};if(t==="vp9")return{vp9:{quantizer:e}};if(t==="av1")return{av1:{quantizer:e}};p(!1)},Br=new J("high"),vs=async(t,e={})=>{const{width:r=1280,height:i=720,quality:n,bitrate:s,frameRate:o,...a}=e;if(!Te.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof J))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof J)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");si(t,a);const d=ct(n,s)??new J("medium");let c;try{c=oi({codec:t,width:r,height:i,quality:d,framerate:o,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),u=vr.get(l);if(u)return u;const f=(async()=>{for(const{config:m}of c)if(di.some(g=>g.supports(t,m)))return!0;if(typeof VideoEncoder>"u"||(r%2===1||i%2===1)&&(t==="avc"||t==="hevc"))return!1;for(const{config:m,quantizer:g}of c){try{if(!(await VideoEncoder.isConfigSupported(m)).supported)continue}catch{continue}if(!rt()||await new Promise(async w=>{try{const E=new VideoEncoder({output:()=>{},error:()=>w(!1)});E.configure(m);const C=new Uint8Array(r*i*4),x=new VideoFrame(C,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});E.encode(x,g!==null?li(t,g):void 0),x.close(),await E.flush(),w(!0)}catch{w(!1)}}))return!0}return!1})();return vr.set(l,f),f},Ss=async(t,e={})=>{const{numberOfChannels:r=2,sampleRate:i=48e3,quality:n,bitrate:s,...o}=e;if(!Fe.includes(t))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof J))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&s!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(s!==void 0&&!(s instanceof J)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");ai(t,o);const a=ct(n,s)??new J("medium"),d=ci({codec:t,numberOfChannels:r,sampleRate:i,quality:a,...o}),c=JSON.stringify(d),l=Sr.get(c);if(l)return l;const u=(async()=>{if(ui.some(f=>f.supports(t,d))||ce.includes(t))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(d)).supported===!0}catch{return!1}})();return Sr.set(c,u),u},ct=(t,e)=>{if(t!==void 0)return t;if(e!==void 0)return e instanceof J?e:new J({bitrate:e})},xs=async(t,e)=>{for(const r of t)if(await vs(r,e))return r;return null},_s=async(t,e)=>{for(const r of t)if(await Ss(r,e))return r;return null};/*!
|
|
92
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
93
|
+
*
|
|
94
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
95
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
96
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
97
|
+
*/const di=[],ui=[];/*!
|
|
98
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
99
|
+
*
|
|
100
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
101
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
102
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
103
|
+
*/const Bs=t=>{let i=t>>2,n=4096,s=0,o=12,a=0;for(i<0&&(i=-i,s=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&o>=5;)n>>=1,o--;return a=i>>o-4&15,~(s|o-5<<4|a)&255},As=t=>{let r=2048,i=0,n=11,s=0,o=t>>3;for(o<0?o=-o-1:i=128,o>4095&&(o=4095);(o&r)!==r&&n>=5;)r>>=1,n--;return s=o>>(n===4?1:n-4)&15,(i|n-4<<4|s)^85};/*!
|
|
104
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
105
|
+
*
|
|
106
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
107
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
108
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
109
|
+
*/class Me{constructor(e,r,i,n,s){this.bytes=e,this.view=r,this.offset=i,this.start=n,this.end=s,this.bufferPos=n-i}static tempFromBytes(e){return new Me(e,re(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,r=this.end-e){if(e<this.start||e+r>this.end)throw new RangeError("Slicing outside of original slice.");return new Me(this.bytes,this.view,this.offset,e,e+r)}}const Ut=(t,e)=>{if(e<0||t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},fi=(t,e)=>{Ut(t,e);const r=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,r},ke=t=>(Ut(t,1),t.view.getUint8(t.bufferPos++)),Ps=t=>{Ut(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e};/*!
|
|
110
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
111
|
+
*
|
|
112
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
113
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
114
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
115
|
+
*/class ks{constructor(e){this.mutex=new Nr,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,r,i){let n=this.trackTimestampInfo.get(e);if(n){if(i&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&r<n.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${r}s, but largest timestamp is ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,r)}else{if(!i)throw new Error("First packet must be a key packet.");n={maxTimestamp:r,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,n)}}}/*!
|
|
116
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
117
|
+
*
|
|
118
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
119
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
120
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
121
|
+
*/const Ar=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Is=t=>{const e=Math.floor(t/36e5),r=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};/*!
|
|
122
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
123
|
+
*
|
|
124
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
125
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
126
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
127
|
+
*/class Je{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let r=0;r<e.length;r++)this.helperView.setUint8(r%8,e.charCodeAt(r)),r%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{const r=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const i=this.writer.getPos(),n=e.size??i-r;this.writer.seek(r),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,r){this.writeU32(e.largeSize?1:r),this.writeAscii(e.type),e.largeSize&&this.writeU64(r)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const r=this.offsets.get(e);p(r!==void 0);const i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let r=this.measureBoxHeader(e);if(e.contents&&(r+=e.contents.byteLength),e.children)for(const i of e.children)i&&(r+=this.measureBox(i));return r}}}const _=new Uint8Array(8),ie=new DataView(_.buffer),N=t=>[(t%256+256)%256],S=t=>(ie.setUint16(0,t,!1),[_[0],_[1]]),Ht=t=>(ie.setInt16(0,t,!1),[_[0],_[1]]),hi=t=>(ie.setUint32(0,t,!1),[_[1],_[2],_[3]]),y=t=>(ie.setUint32(0,t,!1),[_[0],_[1],_[2],_[3]]),he=t=>(ie.setInt32(0,t,!1),[_[0],_[1],_[2],_[3]]),le=t=>(ie.setUint32(0,Math.floor(t/2**32),!1),ie.setUint32(4,t,!1),[_[0],_[1],_[2],_[3],_[4],_[5],_[6],_[7]]),Pr=t=>(ie.setInt32(0,Math.floor(t/2**32),!1),ie.setUint32(4,t,!1),[_[0],_[1],_[2],_[3],_[4],_[5],_[6],_[7]]),mi=t=>(ie.setInt16(0,2**8*t,!1),[_[0],_[1]]),te=t=>(ie.setInt32(0,2**16*t,!1),[_[0],_[1],_[2],_[3]]),Et=t=>(ie.setInt32(0,2**30*t,!1),[_[0],_[1],_[2],_[3]]),Ct=(t,e)=>{const r=[];let i=t;do{let n=i&127;i>>=7,r.length>0&&(n|=128),r.push(n)}while(i>0||e);return r.reverse()},M=(t,e=!1)=>{const r=Array(t.length).fill(null).map((i,n)=>t.charCodeAt(n));return e&&r.push(0),r},pi=t=>[te(t[0]),te(t[1]),Et(t[2]),te(t[3]),te(t[4]),Et(t[5]),te(t[6]),te(t[7]),Et(t[8])],v=(t,e,r)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:r}),F=(t,e,r,i,n)=>v(t,[N(e),hi(r),i??[]],n),Fs=t=>t.isQuickTime?v("ftyp",[M("qt "),y(512),M("qt ")]):t.fragmented?t.cmaf?v("ftyp",[M("iso5"),y(512),M("iso5"),M("iso6"),M("mp41"),M("cmfc"),M("dash")]):v("ftyp",[M("iso5"),y(512),M("iso5"),M("iso6"),M("mp41")]):v("ftyp",[M("isom"),y(512),M("isom"),t.holdsAvc?M("avc1"):[],M("mp41")]),kr=()=>v("styp",[M("iso5"),y(0),M("iso5"),M("iso6"),M("mp41"),M("cmfc"),M("dash")]),Ir=(t,e)=>{const r=Math.max(0,t.minWrittenTimestamp);let i=Math.max(0,t.maxWrittenEndTimestamp-r);return Number.isFinite(i)||(i=0),F("sidx",1,0,[y(1),y(Z),le(z(r,Z)),le(0),S(0),S(1),y(e&2147483647),y(z(i,Z)),y(0)])},et=t=>({type:"mdat",largeSize:t}),Rs=t=>({type:"free",size:t}),qe=t=>v("moov",void 0,[Ms(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Os(e,t.creationTime)),t.isFragmented?Co(t.trackDatas):null,Oo(t)]),Ms=(t,e)=>{const r=Math.max(0,...e.map(o=>Math.max(0,z(Oe(o),Z)+z(o.startTimestampOffset??0,Z)))),i=Math.max(0,...e.map(o=>o.track.id))+1,n=!ye(t)||!ye(r),s=n?le:y;return F("mvhd",+n,0,[s(t),s(t),y(Z),s(r),te(1),mi(1),Array(10).fill(0),pi(Lr),Array(24).fill(0),y(i)])},Os=(t,e)=>{const r=jo(t),i=t.startTimestampOffset!==null&&t.startTimestampOffset!==0;return v("trak",void 0,[zs(t,e),i?Ws(t):null,Ls(t,e),r.name!==void 0?v("udta",void 0,[v("name",[...me.encode(r.name)])]):null])},zs=(t,e)=>{const r=Math.max(0,z(Oe(t),Z)+z(t.startTimestampOffset??0,Z)),i=!ye(e)||!ye(r),n=i?le:y;let s;if(t.type==="video"&&t.track.metadata.transformationMatrix)s=t.track.metadata.transformationMatrix;else if(t.type==="video"){const{rotation:d,flip:c}=t.track.metadata,l=Pt(Ai(d??0),Pi(c?-1:1,1));s=Bi(l,t.info.width,t.info.height)}else s=Lr;let o=2;t.track.metadata.disposition?.default!==!1&&(o|=1);const a=t.type==="video"?0:t.type==="audio"?1:t.type==="subtitle"?2:Be(t);return F("tkhd",+i,o,[n(e),n(e),y(t.track.id),y(0),n(r),Array(8).fill(0),S(0),S(a),mi(t.type==="audio"?1:0),S(0),pi(s),te(t.type==="video"?t.info.width:0),te(t.type==="video"?t.info.height:0)])},Ws=t=>{const e=t.startTimestampOffset;if(p(e!==null),e>0){const r=z(e,Z),i=z(Oe(t),Z),n=!ye(r)||!ye(i),s=n?le:y,o=n?Pr:he;return v("edts",void 0,[F("elst",n?1:0,0,[y(2),s(r),o(-1),te(1),s(i),o(0),te(1)])])}else{const r=z(-e,t.timescale),i=Math.max(0,z(Oe(t),Z)+z(e,Z)),n=!Ii(r)||!ye(i),s=n?le:y,o=n?Pr:he;return v("edts",void 0,[F("elst",n?1:0,0,[y(1),s(i),o(r),te(1)])])}},Ls=(t,e)=>v("mdia",void 0,[Ns(t,e),qt(!0,Vs[t.type],Us[t.type]),Hs(t)]),Ns=(t,e)=>{const r=z(Oe(t),t.timescale),i=!ye(e)||!ye(r),n=i?le:y;return F("mdhd",+i,0,[n(e),n(e),y(t.timescale),n(r),S(yi(t.track.metadata.languageCode??Wi)),S(0)])},Vs={video:"vide",audio:"soun",subtitle:"text"},Us={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},qt=(t,e,r,i="\0\0\0\0")=>F("hdlr",0,0,[t?M("mhlr"):y(0),M(e),M(i),y(0),y(0),M(r,!0)]),Hs=t=>v("minf",void 0,[js[t.type](),Qs(),Ks(t)]),qs=()=>F("vmhd",0,1,[S(0),S(0),S(0),S(0)]),Ds=()=>F("smhd",0,0,[S(0),S(0)]),$s=()=>F("nmhd",0,0),js={video:qs,audio:Ds,subtitle:$s},Qs=()=>v("dinf",void 0,[Gs()]),Gs=()=>F("dref",0,0,[y(1)],[Xs()]),Xs=()=>F("url ",0,1),Ks=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(r=>r.sampleCompositionTimeOffset!==0);return v("stbl",void 0,[Ys(t),po(t),e?To(t):null,e?Eo(t):null,wo(t),bo(t),yo(t),go(t)])},Ys=t=>{let e;if(t.type==="video")e=Zs(No(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const r=bi(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime);p(r),e=no(r,t)}else t.type==="subtitle"&&(e=ho(Ho[t.track.source._codec],t));return p(e),F("stsd",0,0,[y(1)],[e])},Zs=(t,e)=>v(t,[Array(6).fill(0),S(1),S(0),S(0),Array(12).fill(0),S(e.info.width),S(e.info.height),y(4718592),y(4718592),y(0),S(1),N(gt.length),M(gt),Array(31-gt.length).fill(0),S(e.info.hasAlphaChannel?32:24),Ht(65535)],[Vo[e.track.source._codec]?.(e)??null,Js(e),Ri(e.info.decoderConfig.colorSpace)?null:eo(e),Dt(e)]),Dt=t=>t.avgBitrate===0&&t.maxBitrate===0?null:v("btrt",[y(0),y(t.maxBitrate),y(t.avgBitrate)]),Js=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:v("pasp",[y(t.info.pixelAspectRatio.num),y(t.info.pixelAspectRatio.den)]),eo=t=>{const e=t.info.decoderConfig.colorSpace;return v("colr",[M(t.muxer.isQuickTime?"nclc":"nclx"),S(e?.primaries!=null?ze[e.primaries]:2),S(e?.transfer!=null?We[e.transfer]:2),S(e?.matrix!=null?Le[e.matrix]:2),t.muxer.isQuickTime?[]:N((e?.fullRange?1:0)<<7)])},to=t=>t.info.decoderConfig&&v("avcC",[...$(t.info.decoderConfig.description)]),ro=t=>t.info.decoderConfig&&v("hvcC",[...$(t.info.decoderConfig.description)]),Fr=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,r=e.codec.split("."),i=Number(r[1]),n=Number(r[2]),s=Number(r[3]),o=r[4]?Number(r[4]):1,a=r[8]?Number(r[8]):Number(e.colorSpace?.fullRange??0),d=(s<<4)+(o<<1)+a,c=r[5]?Number(r[5]):e.colorSpace?.primaries?ze[e.colorSpace.primaries]:1,l=r[6]?Number(r[6]):e.colorSpace?.transfer?We[e.colorSpace.transfer]:1,u=r[7]?Number(r[7]):e.colorSpace?.matrix?Le[e.colorSpace.matrix]:1;return F("vpcC",1,0,[N(i),N(n),N(d),N(c),N(l),N(u),S(0)])},io=t=>v("av1C",Qn(t.info.decoderConfig.codec)),no=(t,e)=>{let r=0,i,n=16;const s=ce.includes(e.track.source._codec);if(s){const o=e.track.source._codec,{sampleSize:a}=Re(o);n=8*a,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),r===0)i=[Array(6).fill(0),S(1),S(r),S(0),y(0),S(e.info.numberOfChannels),S(n),S(0),S(0),S(e.info.sampleRate<2**16?e.info.sampleRate:0),S(0)];else{const o=s?0:-2;i=[Array(6).fill(0),S(1),S(r),S(0),y(0),S(e.info.numberOfChannels),S(Math.min(n,16)),Ht(o),S(0),S(e.info.sampleRate<2**16?e.info.sampleRate:0),S(0),s?[y(1),y(n/8),y(e.info.numberOfChannels*n/8)]:[y(0),y(0),y(0)],y(2)]}return v(t,i,[Uo(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null,Dt(e)])},vt=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let r=[...N(e),...N(21),...hi(0),...y(t.maxBitrate),...y(t.avgBitrate)];if(t.info.decoderConfig.description){const i=$(t.info.decoderConfig.description);r=[...r,...N(5),...Ct(i.byteLength),...i]}return r=[...S(1),...N(0),...N(4),...Ct(r.length),...r,...N(6),...N(1),...N(2)],r=[...N(3),...Ct(r.length),...r],F("esds",0,0,r)},Ce=t=>v("wave",void 0,[so(t),oo(t),v("\0\0\0\0")]),so=t=>v("frma",[M(bi(t.track.source._codec,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),oo=t=>{const{littleEndian:e}=Re(t.track.source._codec);return v("enda",[S(+e)])},ao=t=>{let e=t.info.numberOfChannels,r=3840,i=t.info.sampleRate,n=0,s=0,o=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){p(a.byteLength>=18);const d=$(a),c=vn(d);e=c.outputChannelCount,r=c.preSkip,i=c.inputSampleRate,n=c.outputGain,s=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return v("dOps",[N(0),N(e),S(r),y(i),Ht(n),N(s),...o])},co=t=>{const e=t.info.decoderConfig?.description;p(e);const r=$(e);return F("dfLa",0,0,[...r.subarray(4)])},de=t=>{const{littleEndian:e,sampleSize:r}=Re(t.track.source._codec),i=+e;return F("pcmC",0,0,[N(i),N(8*r)])},lo=t=>{p(t.info.primingPacket);const e=xn(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const r=new Uint8Array(3),i=new V(r);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),v("dac3",[...r])},uo=t=>{p(t.info.primingPacket);const e=Bn(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let r=16;for(const o of e.substreams)r+=23,o.numDepSub>0?r+=9:r+=1;const i=Math.ceil(r/8),n=new Uint8Array(i),s=new V(n);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(const o of e.substreams)s.writeBits(2,o.fscod),s.writeBits(5,o.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,o.bsmod),s.writeBits(3,o.acmod),s.writeBits(1,o.lfeon),s.writeBits(3,0),s.writeBits(4,o.numDepSub),o.numDepSub>0?s.writeBits(9,o.chanLoc):s.writeBits(1,0);return v("dec3",[...n])},fo=t=>{p(t.info.primingPacket);const e=Un(t.info.primingPacket.data);if(!e)throw new 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 v("ddts",[...Dn(e)])},ho=(t,e)=>v(t,[Array(6).fill(0),S(1)],[qo[e.track.source._codec](e),Dt(e)]),mo=t=>v("vttC",[...me.encode(t.info.config.description)]),po=t=>F("stts",0,0,[y(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[y(e.sampleCount),y(e.sampleDelta)])]),go=t=>{if(t.samples.every(r=>r.type==="key"))return null;const e=[...t.samples.entries()].filter(([,r])=>r.type==="key");return F("stss",0,0,[y(e.length),e.map(([r])=>y(r+1))])},wo=t=>F("stsc",0,0,[y(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[y(e.firstChunk),y(e.samplesPerChunk),y(1)])]),bo=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=Re(t.track.source._codec);return F("stsz",0,0,[y(e*t.info.numberOfChannels),y(t.samples.reduce((r,i)=>r+z(i.duration,t.timescale),0))])}return F("stsz",0,0,[y(0),y(t.samples.length),t.samples.map(e=>y(e.size))])},yo=t=>t.finalizedChunks.length>0&&G(t.finalizedChunks).offset>=2**32?F("co64",0,0,[y(t.finalizedChunks.length),t.finalizedChunks.map(e=>le(e.offset))]):F("stco",0,0,[y(t.finalizedChunks.length),t.finalizedChunks.map(e=>y(e.offset))]),To=t=>F("ctts",1,0,[y(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[y(e.sampleCount),he(e.sampleCompositionTimeOffset)])]),Eo=t=>{let e=1/0,r=-1/0,i=1/0,n=-1/0;p(t.compositionTimeOffsetTable.length>0),p(t.samples.length>0);for(let o=0;o<t.compositionTimeOffsetTable.length;o++){const a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){const a=t.samples[o];i=Math.min(i,z(a.timestamp,t.timescale)),n=Math.max(n,z(a.timestamp+a.duration,t.timescale))}const s=Math.max(-e,0);return n>=2**31?null:F("cslg",0,0,[he(s),he(e),he(r),he(i),he(n)])},Co=t=>v("mvex",void 0,t.map(vo)),vo=t=>F("trex",0,0,[y(t.track.id),y(1),y(0),y(0),y(0)]),Rr=(t,e)=>v("moof",void 0,[So(t),...e.map(xo)]),So=t=>F("mfhd",0,0,[y(t)]),gi=t=>{let e=0,r=0;const i=0,n=0,s=t.type==="delta";return r|=+s,s?e|=1:e|=2,e<<24|r<<16|i<<8|n},xo=t=>v("traf",void 0,[_o(t),Bo(t),Ao(t)]),_o=t=>{p(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const r=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:gi(r)};return F("tfhd",0,e,[y(t.track.id),y(i.duration),y(i.size),y(i.flags)])},Bo=t=>(p(t.currentChunk),F("tfdt",1,0,[le(z(t.currentChunk.startTimestamp,t.timescale))])),Ao=t=>{p(t.currentChunk);const e=t.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),r=t.currentChunk.samples.map(g=>g.size),i=t.currentChunk.samples.map(gi),n=t.currentChunk.samples.map(g=>z(g.timestamp-g.decodeTimestamp,t.timescale)),s=new Set(e),o=new Set(r),a=new Set(i),d=new Set(n),c=a.size===2&&i[0]!==i[1],l=s.size>1,u=o.size>1,f=!c&&a.size>1,h=d.size>1||[...d].some(g=>g!==0);let m=0;return m|=1,m|=4*+c,m|=256*+l,m|=512*+u,m|=1024*+f,m|=2048*+h,F("trun",1,m,[y(t.currentChunk.samples.length),y(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?y(i[0]):[],t.currentChunk.samples.map((g,b)=>[l?y(e[b]):[],u?y(r[b]):[],f?y(i[b]):[],h?he(n[b]):[]])])},Po=t=>v("mfra",void 0,[...t.map(ko),Io()]),ko=t=>{const r=[];for(const i of t.finalizedChunks){const n=i.samples.findIndex(o=>o.type==="key");if(n===-1)continue;const s=i.samples[n];r.push([le(z(s.timestamp,t.timescale)),le(i.moofOffset),y(i.trafIndex+1),y(1),y(n+1)])}return F("tfra",1,0,[y(t.track.id),y(63),y(r.length),r])},Io=()=>F("mfro",0,0,[y(0)]),Fo=()=>v("vtte"),Ro=(t,e,r,i,n)=>v("vttc",void 0,[n!==null?v("vsid",[he(n)]):null,r!==null?v("iden",[...me.encode(r)]):null,e!==null?v("ctim",[...me.encode(Is(e))]):null,i!==null?v("sttg",[...me.encode(i)]):null,v("payl",[...me.encode(t)])]),Mo=t=>v("vtta",[...me.encode(t)]),Oo=t=>{const e=[],r=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(r==="mdir"||r==="auto"&&!t.isQuickTime){const n=Wo(i);n&&e.push(n)}else if(r==="mdta"){const n=Lo(i);n&&e.push(n)}else(r==="udta"||r==="auto"&&t.isQuickTime)&&zo(e,t.output._metadataTags);return e.length===0?null:v("udta",void 0,e)},zo=(t,e)=>{for(const{key:r,value:i}of qr(e))switch(r){case"title":t.push(ue("©nam",i));break;case"description":t.push(ue("©des",i));break;case"artist":t.push(ue("©ART",i));break;case"album":t.push(ue("©alb",i));break;case"albumArtist":t.push(ue("albr",i));break;case"genre":t.push(ue("©gen",i));break;case"date":t.push(ue("©day",i.toISOString().slice(0,10)));break;case"comment":t.push(ue("©cmt",i));break;case"lyrics":t.push(ue("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Be(r)}if(e.raw)for(const r in e.raw){const i=e.raw[r];i==null||r.length!==4||t.some(n=>n.type===r)||(typeof i=="string"?t.push(ue(r,i)):i instanceof Uint8Array&&t.push(v(r,Array.from(i))))}},ue=(t,e)=>{const r=me.encode(e);return v(t,[S(r.length),S(yi("und")),Array.from(r)])},Mr={"image/jpeg":13,"image/png":14,"image/bmp":27},wi=(t,e)=>{const r=[];for(const{key:i,value:n}of qr(t))switch(i){case"title":r.push({key:e?"title":"©nam",value:ae(n)});break;case"description":r.push({key:e?"description":"©des",value:ae(n)});break;case"artist":r.push({key:e?"artist":"©ART",value:ae(n)});break;case"album":r.push({key:e?"album":"©alb",value:ae(n)});break;case"albumArtist":r.push({key:e?"album_artist":"aART",value:ae(n)});break;case"comment":r.push({key:e?"comment":"©cmt",value:ae(n)});break;case"genre":r.push({key:e?"genre":"©gen",value:ae(n)});break;case"beatsPerMinute":e||r.push({key:"tmpo",value:v("data",[y(21),y(0),S(n)])});break;case"lyrics":r.push({key:e?"lyrics":"©lyr",value:ae(n)});break;case"date":r.push({key:e?"date":"©day",value:ae(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&r.push({key:"covr",value:v("data",[y(Mr[s.mimeType]??0),y(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=t.tracksTotal!==void 0?`${n}/${t.tracksTotal}`:n.toString();r.push({key:"track",value:ae(s)})}else r.push({key:"trkn",value:v("data",[y(0),y(0),S(0),S(n),S(t.tracksTotal??0),S(0)])});break;case"discNumber":e||r.push({key:"disc",value:v("data",[y(0),y(0),S(0),S(n),S(t.discsTotal??0),S(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Be(i)}if(t.raw)for(const i in t.raw){const n=t.raw[i];n==null||!e&&i.length!==4||r.some(s=>s.key===i)||(typeof n=="string"?r.push({key:i,value:ae(n)}):n instanceof Uint8Array?r.push({key:i,value:v("data",[y(0),y(0),Array.from(n)])}):n instanceof $r&&r.push({key:i,value:v("data",[y(Mr[n.mimeType]??0),y(0),Array.from(n.data)])}))}return r},Wo=t=>{const e=wi(t,!1);return e.length===0?null:F("meta",0,0,void 0,[qt(!1,"mdir","","appl"),v("ilst",void 0,e.map(r=>v(r.key,void 0,[r.value])))])},Lo=t=>{const e=wi(t,!0);return e.length===0?null:v("meta",void 0,[qt(!1,"mdta",""),F("keys",0,0,[y(e.length)],e.map(r=>v("mdta",[...me.encode(r.key)]))),v("ilst",void 0,e.map((r,i)=>{const n=String.fromCharCode(...y(i+1));return v(n,void 0,[r.value])}))])},ae=t=>v("data",[y(1),y(0),...me.encode(t)]),No=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Vo={avc:to,hevc:ro,vp8:Fr,vp9:Fr,av1:io,prores:null},bi=(t,e,r)=>{switch(t){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 e}if(r)switch(t){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(t){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"}},Uo=(t,e)=>{switch(t){case"aac":return vt;case"mp3":return vt;case"opus":return ao;case"vorbis":return vt;case"flac":return co;case"ac3":return lo;case"eac3":return uo;case"dts":return fo}if(e)switch(t){case"pcm-s24":return Ce;case"pcm-s24be":return Ce;case"pcm-s32":return Ce;case"pcm-s32be":return Ce;case"pcm-f32":return Ce;case"pcm-f32be":return Ce;case"pcm-f64":return Ce;case"pcm-f64be":return Ce}else switch(t){case"pcm-s16":return de;case"pcm-s16be":return de;case"pcm-s24":return de;case"pcm-s24be":return de;case"pcm-s32":return de;case"pcm-s32be":return de;case"pcm-f32":return de;case"pcm-f32be":return de;case"pcm-f64":return de;case"pcm-f64be":return de}return null},Ho={webvtt:"wvtt"},qo={webvtt:mo},yi=t=>{p(t.length===3);let e=0;for(let r=0;r<3;r++)e<<=5,e+=t.charCodeAt(r)-96;return e};/*!
|
|
128
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
129
|
+
*
|
|
130
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
131
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
132
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
133
|
+
*/class zt{constructor(e,r){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(r),e._writerAcquired=!0}start(){p(!this.started),this.target._start(),this.started=!0}write(e){p(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let r=this.getPos();if(r<this.trackedStart){if(r+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-r),r=0}const i=r+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const s=new Uint8Array(n);s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,r-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,r+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const r={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,r}}/*!
|
|
134
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
135
|
+
*
|
|
136
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
137
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
138
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
139
|
+
*/class ge extends Lt{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,r){this.onwrite?.(e,r),this._emit("write",{start:e,end:r})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Do(this,e)}}const St=2**16,xt=2**32;class tt extends ge{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(St,{maxByteLength:xt})}catch{this._buffer=new ArrayBuffer(St),this._supportsResize=!1}else this._buffer=new ArrayBuffer(St);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>xt)throw new Error(`ArrayBuffer exceeded maximum size of ${xt} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{const i=new ArrayBuffer(r),n=new Uint8Array(i);n.set(this._bytes,0),this._buffer=i,this._bytes=n}}}_start(){}_write(e,r){this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+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,r){return this._bytes.slice(e,r)}}class Do extends ge{constructor(e,r){super(),this._baseTarget=e,this._offset=r}_start(){}_write(e,r){this._baseTarget._write(e,this._offset+r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class _t{constructor(e,r){if(this.rootPath=e,this.getTarget=r,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof r!="function")throw new TypeError("getTarget must be a function.")}}/*!
|
|
140
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
141
|
+
*
|
|
142
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
143
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
144
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
145
|
+
*/const Z=57600,$o=2082844800,jo=t=>{const e={},r=t.track;return r.metadata.name!==void 0&&(e.name=r.metadata.name),e},z=(t,e,r=!0)=>{const i=t*e;return r?Math.round(i):i},Oe=t=>{if(t.samples.length===0)return 0;let e=1/0,r=-1/0;for(let i=0;i<t.samples.length;i++){const n=t.samples[i];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>r&&(r=n.timestamp+n.duration)}return e===1/0?0:r-e};class Qo extends ks{constructor(e,r){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new tt,this.auxWriter=new zt(this.auxTarget,!1),this.auxBoxWriter=new Je(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Vr(),this.creationTime=Math.floor(Date.now()/1e3)+$o,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=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof Si,this.isCmaf=r instanceof zr,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof zr?1/0:1),this.auxWriter.start()}async start(){const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":i instanceof tt),this.boxWriter=new Je(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof tt?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const i=await this.output._getInitTarget(),n=new zt(i,!0);n.start(),this.initWriter=n,this.initBoxWriter=new Je(n)}const r=this.output.tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(p(i),this.formatOptions.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Fs({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:n,start:s}=i.writer.stopTrackingWrites();this.formatOptions.onFtyp(n,s)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output.tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(p(this.writer),p(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=et(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(const i of this.output.tracks)i.isVideoTrack()&&i.metadata.decoderConfig?this.getVideoTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig}):i.isAudioTrack()&&i.metadata.decoderConfig&&this.getAudioTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig});e()}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return ss({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){const n=this.trackDatas.find(h=>h.track===e);if(n)return n;ti(i,e.source._codec),p(i),p(i.decoderConfig);const s={...i.decoderConfig};p(s.codedWidth!==void 0),p(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const h=Xr(r.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=Kr(h),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const h=Zr(r.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=bn(h),o=!0}const a=Ui(1/(e.metadata.frameRate??Z),1e6).den,d=s.displayAspectWidth,c=s.displayAspectHeight,l=d===void 0||c===void 0?{num:1,den:1}:Dr({num:d*s.codedHeight,den:c*s.codedWidth}),u=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:l,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:u},timescale:a,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((h,m)=>h.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,r,i){const n=this.trackDatas.find(d=>d.track===e);if(n)return n;ri(i,e.source._codec),p(i),p(i.decoderConfig);const s={...i.decoderConfig};let o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const d=pr(Me.tempFromBytes(r.data));if(!d)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const c=$e[d.samplingFrequencyIndex],l=Nt[d.channelConfiguration];if(c===void 0||l===void 0)throw new Error("Invalid ADTS frame header.");s.description=jr({objectType:d.objectType,outputSampleRate:c,outputNumberOfChannels:l}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.")}const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ce.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r},timescale:s.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(a),this.trackDatas.sort((d,c)=>d.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,r){const i=this.trackDatas.find(s=>s.track===e);if(i)return i;ns(r),p(r),p(r.config);const n={muxer:this,track:e,type:"subtitle",info:{config:r.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:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,r,i);let o=r.data;if(s.info.requiresAnnexBTransformation){const d=[...Xe(o)].map(c=>o.subarray(c.offset,c.offset+c.length));if(d.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=an(d,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");const a=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);await this.registerSample(s,a)}finally{n()}}async addEncodedAudioPacket(e,r,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,r,i);let o=r.data;if(s.info.requiresAdtsStripping){const l=pr(Me.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const u=l.crcCheck===null?Rt:as;o=o.subarray(u)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let a=r.timestamp,d=r.duration;if(s.info.requiresPcmTransformation){const u=Re(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(d=o.byteLength/u/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const f=a-s.info.expectedNextPcmPacketTimestamp;if(f<.01)a=s.info.expectedNextPcmPacketTimestamp;else{const h=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);a=s.info.expectedNextPcmPacketTimestamp+h}}s.info.expectedNextPcmPacketTimestamp=a+d}const c=this.createSampleForTrack(s,o,a,d,r.type);await this.registerSample(s,c)}finally{n()}}async padWithSilence(e,r,i){const n=z(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:s,silentValue:o}=Re(e.info.decoderConfig.codec),a=n*e.info.numberOfChannels,d=new Uint8Array(s*a).fill(o),c=this.createSampleForTrack(e,new Uint8Array(d.buffer),r,i,"key");await this.registerSample(e,c)}return i}async addSubtitleCue(e,r,i){const n=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{n()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);const i=new Set([]);for(const c of e.cueQueue)p(c.timestamp<=r),p(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,l)=>c-l),s=n[0],o=n[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=Fo();this.auxBoxWriter.writeBox(c);const l=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,l,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const l=e.cueQueue[c];if(l.timestamp>=o)break;Ar.lastIndex=0;const u=Ar.test(l.text),f=l.timestamp+l.duration;let h=e.cueToSourceId.get(l);if(h===void 0&&o<f&&(h=e.nextSourceId++,e.cueToSourceId.set(l,h)),l.notes){const g=Mo(l.notes);this.auxBoxWriter.writeBox(g)}const m=Ro(l.text,u?s:null,l.identifier??null,l.settings??null,h??null);this.auxBoxWriter.writeBox(m),f===o&&e.cueQueue.splice(c--,1)}const a=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,a,s,o-s,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,i,n,s){return{timestamp:i,decodeTimestamp:i,duration:n,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:z(n,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){p(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let n=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const o=e.timestampProcessingQueue[s],a=z(o.duration,e.timescale);n+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const s=G(e.timeToSampleTable);s.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,s)=>n-s);this.isFragmented?e.startTimestampOffset??=Math.min(i[0],0):e.startTimestampOffset??=i[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n];const o=z(s.timestamp-s.decodeTimestamp,e.timescale),a=z(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const d=z(s.decodeTimestamp,e.timescale,!1),c=Math.round(d-e.lastTimescaleUnits);if(p(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let l=G(e.timeToSampleTable);if(p(l),l.sampleCount===1){l.sampleDelta=c;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===c&&(f.sampleCount++,e.timeToSampleTable.pop(),l=f)}else l.sampleDelta!==c&&(l.sampleCount--,e.timeToSampleTable.push(l={sampleCount:1,sampleDelta:c}));l.sampleDelta===a?l.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const u=G(e.compositionTimeOffsetTable);p(u),u.sampleCompositionTimeOffset===o?u.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=z(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(r.type==="key");const n=z(r.timestamp,e.timescale,!1),s=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){const n=e.track.metadata.maximumPacketCount;if(p(n!==void 0),e.samples.length>n)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${n}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);const n=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.closed});n>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),p(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(p(!this.isFragmented),p(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,n)=>i+z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||G(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;const n=r.sampleQueue.shift();await this.addSampleToTrack(r,n)}}async finalizeFragment(e=!this.isCmaf){if(p(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const h=this.initBoxWriter??this.boxWriter;p(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const m=qe(this);if(h.writeBox(m),this.formatOptions.onMoov){const{data:g,start:b}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(g,b)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Je(this.writer);const g=this.boxWriter.measureBox(kr()),b=this.boxWriter.measureBox(Ir(this,0));this.segmentHeaderSize=g+b,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(this.boxWriter);const r=this.trackDatas.filter(h=>h.currentChunk);if(r.length===0){e&&await this.writer.flush();return}const i=this.nextFragmentNumber++,n=Rr(i,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(n);let a=o+wt,d=1/0;for(let h=0;h<r.length;h++){const m=r[h];p(m.currentChunk),p(m.startTimestampOffset!==null),m.currentChunk.offset=a,m.currentChunk.moofOffset=s,m.currentChunk.trafIndex=h,m.currentChunk.startTimestamp-=m.startTimestampOffset;for(const g of m.currentChunk.samples)a+=g.size,g.timestamp-=m.startTimestampOffset,g.decodeTimestamp-=m.startTimestampOffset;d=Math.min(d,m.currentChunk.startTimestamp)}const c=a-o,l=c>=2**32;if(l)for(const h of r)h.currentChunk.offset+=mr-wt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const u=Rr(i,r);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){const{data:h,start:m}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,m,d)}p(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=et(l);f.size=c,this.boxWriter.writeBox(f),this.writer.seek(o+(l?mr:wt));for(const h of r)for(const m of h.currentChunk.samples)this.writer.write(m.data),m.data=null;if(this.formatOptions.onMdat){const{data:h,start:m}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,m)}for(const h of r)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,r)):e.sampleQueue.push(r)}async createFastStartReserveMdat(){p(this.writer),p(this.boxWriter),this.ensureOneEnabledTrack();const e=qe(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=et(!0),this.boxWriter.writeBox(this.mdat);for(const n of this.trackDatas){for(const s of n.sampleQueue)await this.addSampleToTrack(n,s);n.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(const r of this.trackDatas){const i=r.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const r=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const r=this.trackDatas.filter(n=>n.type===e);if(r.length===0)continue;if(!r.some(n=>n.track.metadata.disposition?.default!==!1)){const n=r[0];n.track.metadata.disposition={...n.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){p(this.isFragmented);const e=await this.mutex.acquire();try{for(const r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(const r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const r of this.trackDatas){await this.finalizeCurrentChunk(r);const i=Oe(r);if(i>0){let a=0;for(const d of r.samples)a+=d.size;r.avgBitrate=Math.round(8*a/i)}else r.avgBitrate=0;let n=0,s=0,o=0;for(let a=0;a<r.samples.length;a++){const d=r.samples[a];for(s+=d.size;d.decodeTimestamp-r.samples[n].decodeTimestamp>=1;)s-=r.samples[n].size,n++;o=Math.max(o,s)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let a=0;a<r.samples.length;a++){const d=r.samples[a];d.timestamp-=r.startTimestampOffset,d.decodeTimestamp-=r.startTimestampOffset}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=et(!1);let r;for(let n=0;n<2;n++){const s=qe(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+r;for(const d of this.finalizedChunks){d.offset=a;for(const{data:c}of d.samples)p(c),a+=c.byteLength,r+=c.byteLength}if(a<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const i=qe(this);if(this.boxWriter.writeBox(i),this.formatOptions.onMoov){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(n,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const s of n.samples)p(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){const{data:n,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(n,s)}}else if(this.isFragmented)if(this.isCmaf){const r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(kr()),this.boxWriter.writeBox(Ir(this,r))}else{const r=this.writer.getPos(),i=Po(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{p(this.mdat);const r=this.boxWriter.offsets.get(this.mdat);p(r!==void 0);const i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}const n=qe(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Rs(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){const{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}}/*!
|
|
146
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
147
|
+
*
|
|
148
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
149
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
150
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
151
|
+
*/class Go{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){p(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,r=this.targetNumberOfChannels;e===1&&r===2?this.channelMixer=(i,n)=>i[n*e]:e===1&&r===4?this.channelMixer=(i,n,s)=>i[n*e]*+(s<2):e===1&&r===6?this.channelMixer=(i,n,s)=>i[n*e]*+(s===2):e===2&&r===1?this.channelMixer=(i,n)=>{const s=n*e;return .5*(i[s]+i[s+1])}:e===2&&r===4?this.channelMixer=(i,n,s)=>s<2?i[n*e+s]:0:e===2&&r===6?this.channelMixer=(i,n,s)=>s<2?i[n*e+s]:0:e===4&&r===1?this.channelMixer=(i,n)=>{const s=n*e;return .25*(i[s]+i[s+1]+i[s+2]+i[s+3])}:e===4&&r===2?this.channelMixer=(i,n,s)=>{const o=n*e;return .5*(i[o+s]+i[o+s+2])}:e===4&&r===6?this.channelMixer=(i,n,s)=>{const o=n*e;return s<2?i[o+s]:s===2||s===3?0:i[o+s-2]}:e===6&&r===1?this.channelMixer=(i,n)=>{const s=n*e;return Math.SQRT1_2*(i[s]+i[s+1])+i[s+2]+.5*(i[s+4]+i[s+5])}:e===6&&r===2?this.channelMixer=(i,n,s)=>{const o=n*e;return i[o+s]+Math.SQRT1_2*(i[o+2]+i[o+s+4])}:e===6&&r===4?this.channelMixer=(i,n,s)=>{const o=n*e;return s<2?i[o+s]+Math.SQRT1_2*i[o+2]:i[o+s+2]}:this.channelMixer=(i,n,s)=>s<e?i[n*e+s]:0}ensureTempBufferSize(e){let r=this.tempSourceBuffer.length;for(;r<e;)r*=2;if(r!==this.tempSourceBuffer.length){const i=new Float32Array(r);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;const c=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+c,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}p(this.startTime!==null);const r=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(r);const i=e.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(n,{planeIndex:0,format:"f32"});const s=e.timestamp-this.startTime,o=s+e.duration,a=Math.floor((s-1/this.sourceSampleRate)*this.targetSampleRate)+1,d=Math.ceil(o*this.targetSampleRate);for(let c=a;c<d;c++){if(c<this.bufferStartFrame)continue;for(;c>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const l=c-this.bufferStartFrame;p(l<this.bufferCapacityInFrames);const h=(c/this.targetSampleRate-s)*this.sourceSampleRate,m=Math.floor(h),g=Math.ceil(h),b=h-m;for(let w=0;w<this.targetNumberOfChannels;w++){let E=0,C=0;m>=0&&m<e.numberOfFrames&&(E=this.channelMixer(n,m,w)),g>=0&&g<e.numberOfFrames&&(C=this.channelMixer(n,g,w));const x=E+b*(C-E),B=l*this.targetNumberOfChannels+w;this.outputBuffer[B]+=x}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;p(this.startTime!==null);const e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,r=new Float32Array(e);r.set(this.outputBuffer.subarray(0,e));const i=new Y({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:r});await this.onSample(i),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}}/*!
|
|
152
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
153
|
+
*
|
|
154
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
155
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
156
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
157
|
+
*/var Xo=function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],r&&(n=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");n&&(i=function(){try{n.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:i,async:r})}else r&&t.stack.push({async:!0});return e},Ko=(function(t){return function(e){function r(o){e.error=e.hasError?new t(o,e.error,"An error was suppressed during disposal."):o,e.hasError=!0}var i,n=0;function s(){for(;i=e.stack.pop();)try{if(!i.async&&n===1)return n=0,e.stack.push(i),Promise.resolve().then(s);if(i.dispose){var o=i.dispose.call(i.value);if(i.async)return n|=2,Promise.resolve(o).then(s,function(a){return r(a),s()})}else n|=1}catch(a){r(a)}if(n===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var i=new Error(r);return i.name="SuppressedError",i.error=t,i.suppressed=e,i});class $t{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class Ti extends $t{constructor(e){if(super(),!Te.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Te.join(", ")}.`);this._codec=e}}const Or=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Yo{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,r){this.source=e,this.encodingConfig=r,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 Ur,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,r,i){const n=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const s=this.encodingConfig,o=s.sizeChangeBehavior??"deny";let a=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(a=!0,o==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.flip!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||a&&o!=="passThrough"){let u=s.transform?.width,f=s.transform?.height,h=s.transform?.fit??"fill";a&&o!=="passThrough"&&(p(this.outputWidth),p(this.outputHeight),p(o!=="deny"),u=this.outputWidth,f=this.outputHeight,h=o);const m=await e.transform({width:u,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,flip:s.transform?.flip,fit:h,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=m.displayWidth,this.outputHeight=m.displayHeight),r&&e.close(),e=m,r=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const l=s.transform?.frameRate;if(l!==void 0){const u=e.timestamp+e.duration,f=Jt(e.timestamp,l);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=u;return}else await this.padFrameRate(f,i);e===n&&(e=e.clone(),r=!0),e.setTimestamp(f),e.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=u}await this.processAndEncode(e,i)}finally{r&&e.close()}}async processAndEncode(e,r){const i=this.encodingConfig;let n;if(i.transform?.process){let s=i.transform.process(e);if(_e(s)&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);const o=[];try{for(const a of s)a instanceof K?o.push(a):typeof VideoFrame<"u"&&a instanceof VideoFrame?o.push(new K(a)):o.push(new K(a,{timestamp:e.timestamp,duration:e.duration}))}catch(a){for(const d of o)d!==e&&d.close();for(const d of s)(d instanceof K&&d!==e||typeof VideoFrame<"u"&&d instanceof VideoFrame)&&d.close();throw a}n=o}else n=[e];try{for(const s of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(s),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();const o=this.encodingConfig.keyFrameInterval??2,a=Math.floor(s.timestamp/o),d={...this.defaultEncodeOptions,...s.encodeOptions,...r},c={...d,keyFrame:d.keyFrame!==void 0?d.keyFrame:o===0||a!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=a,this.encodingConfig.onEncodedSample?.(s),this.customEncoder){this.customEncoderQueueSize++;const l=s.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,c)).catch(f=>this.setError(f)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await u}else{p(this.encoder);const l=s.toVideoFrame(),u=Kt(this.preciseTimings,l.timestamp,h=>h.microsecondTimestamp),f=u!==-1?this.preciseTimings[u]:null;if(f&&f.microsecondTimestamp===l.timestamp?(f.timestamp!==s.timestamp&&(f.timestampIsValid=!1),f.duration!==s.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(u+1,0,{microsecondTimestamp:l.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(l,c)}finally{l.close()}}else{this.splitter||(this.splitter=new ea);const{colorFrame:m,alphaFrame:g}=await this.splitter.split(l);this.alphaFrameQueue.push(g);try{this.encoder.encode(m,c)}finally{m.close()}}else try{this.encoder.encode(l,c)}finally{l.close()}this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const s of n)s!==e&&s.close()}}async padFrameRate(e,r){const i=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);const n=Math.round((e-this.frameRateLastTimestamp)*i);for(let s=1;s<n;s++){const o={stack:[],error:void 0,hasError:!1};try{const a=Xo(o,this.frameRateLastSample.clone(),!1);a.setTimestamp(this.frameRateLastTimestamp+s/i),a.setDuration(1/i),await this.processAndEncode(a,r)}catch(a){o.error=a,o.hasError=!0}finally{Ko(o)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const r=ct(this.encodingConfig.quality,this.encodingConfig.bitrate);p(r!==void 0);const i=oi({...this.encodingConfig,quality:r,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});let n=null,s;for(const a of i){const d=a.config;if(this.encodingConfig.onEncoderConfig?.(d),s=di.find(l=>l.supports(this.encodingConfig.codec,d)),s){n=a;break}if(typeof VideoEncoder>"u")continue;if(d.alpha="discard",this.encodingConfig.alpha==="keep"&&(d.latencyMode="quality"),(d.width%2===1||d.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${d.width}x${d.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(d)).supported){n=a;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(Hr("VideoEncoder"));const a=i[0].config,d=i.map(({config:c,quantizer:l})=>l!==null?`quantizer ${l}`:`${c.bitrate} bps`);throw new Error(`This specific encoder configuration (${a.codec}, ${d.join(" / ")}, ${a.width}x${a.height}, hardware acceleration: ${a.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const o=n.config;n.quantizer!==null?this.defaultEncodeOptions=li(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=o.bitrate??null,s?(this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(a,d)=>{if(!(a instanceof pe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(d!==void 0&&(!d||typeof d!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Or(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,d),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,d).catch(c=>{this.setError(c)})},this.customEncoder.onError=a=>{this.setError(a)},await this.customEncoder.init()):(this.encoderConfig=o,this.encodingConfig.codec==="avc"&&rt()&&(this.chunkTimestampsAreShiftedByDuration=await Jo()),this.createWebCodecsEncoders()),p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const e=this.encoderConfig;p(e);const r=[],i=[];let n=0,s=0;const o=(d,c)=>{if($i(d)){this.encodersReclaimed=!0;return}d.stack=c,this.setError(d)},a=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(d,c)=>{if(!this.alphaEncoder){this.addPacket(d,null,c);return}const l=this.alphaFrameQueue.shift();p(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:d.type==="key"}),s++,l.close(),r.push({chunk:d,meta:c})):s===0?this.addPacket(d,null,c):(i.push(n+s),r.push({chunk:d,meta:c}))},error:d=>o(d,a)}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const d=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(c,l)=>{s--;const u=r.shift();for(p(u!==void 0),this.addPacket(u.chunk,c,u.meta),n++;i.length>0&&i[0]===n;){i.shift();const f=r.shift();p(f!==void 0),this.addPacket(f.chunk,null,f.meta)}},error:c=>o(c,d)}),this.alphaEncoder.configure(e)}}addPacket(e,r,i){const n={};if(r){const u=new Uint8Array(r.byteLength);r.copyTo(u),n.alpha=u}let s=pe.fromEncodedChunk(e,n);const o=this.encoderConfig;if(p(o),i?.decoderConfig&&(i.decoderConfig.codec=Gn({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:i.decoderConfig.description?$(i.decoderConfig.description):null,colorSpace:i.decoderConfig.colorSpace??null,avcType:o.codec.includes("avc1.")?1:o.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!i.decoderConfig.description?Xr(s.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!i.decoderConfig.description?Zr(s.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?Tn(s.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?En(s.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&i.decoderConfig.description&&rt())){const u=cn($(i.decoderConfig.description));let f=u?.sequenceParameterSets[0];if(f&&f[0]===f[1]){p(u),f=f.subarray(1);let h=u.pictureParameterSets[0];h&&(h=h.subarray(1));const m=Kr({...u,sequenceParameterSets:[f],pictureParameterSets:h?[h]:[]});i.decoderConfig.description=m}}let a=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(a-=e.duration??0,s=s.clone({timestamp:a/1e6}));const d=Kt(this.preciseTimings,a,u=>u.microsecondTimestamp),c=d!==-1?this.preciseTimings[d]:null;let l=null;this.emittedEncoderPackets===0&&s.type==="delta"&&i?.decoderConfig&&(l=Sn(this.encodingConfig.codec,i.decoderConfig,s.data)),(c&&c.microsecondTimestamp===a||l!==null)&&(s=s.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:l??void 0})),Or(this.source._connectedTrack,s),this.encodingConfig.onEncodedPacket?.(s,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,i).catch(u=>{this.setError(u)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){p(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)){const r=this.encodingConfig.transform.frameRate,i=Jt(this.frameRateLastEndTimestamp,r);await this.padFrameRate(i)}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 Ki(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(r=>this.setError(r)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(r=>r?.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 Zo=null;const Jo=()=>Zo??=(async()=>{let t=null;const e=new VideoEncoder({output:r=>{t??=r.timestamp},error:()=>{}});try{e.configure({codec:"avc1.64001f",width:1280,height:720});const r=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});e.encode(r,{keyFrame:!0}),r.close(),await e.flush()}catch{return!1}finally{e.state!=="closed"&&e.close()}return t===500})();let Bt=null;class ea{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Bt){const n=new Blob([`(${ta.toString()})()`],{type:"application/javascript"});Bt=URL.createObjectURL(n)}this.worker=new Worker(Bt),this.worker.addEventListener("message",n=>{const s=n.data,o=this.pendingRequests.get(s.id);o&&(this.pendingRequests.delete(s.id),"error"in s?o.reject(new Error(s.error)):o.resolve({colorFrame:s.colorFrame,alphaFrame:s.alphaFrame}))}),this.worker.addEventListener("error",n=>{const s=new Error(n.message||"Color/alpha splitter worker error.");for(const o of this.pendingRequests.values())o.reject(s);this.pendingRequests.clear()})}const r=this.nextRequestId++,i=Vr();return this.pendingRequests.set(r,i),this.worker.postMessage({id:r,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const r of this.pendingRequests.values())r.reject(e);this.pendingRequests.clear()}}const ta=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:o,sourceFrame:a}=s.data;e=e.then(async()=>{try{const{colorFrame:d,alphaFrame:c}=await r(a);self.postMessage({id:o,colorFrame:d,alphaFrame:c},{transfer:[d,c]})}catch(d){self.postMessage({id:o,error:d.message})}finally{a.close()}})});const r=async s=>{const o=s.format;if(!o)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const a=s.allocationSize();if((!t||t.byteLength!==a)&&(t=new Uint8Array(a)),await s.copyTo(t),o==="RGBA"||o==="BGRA")return i(t,o,s);if(o==="I420A"||o==="I420AP10"||o==="I420AP12"||o==="I422A"||o==="I422AP10"||o==="I422AP12"||o==="I444A"||o==="I444AP10"||o==="I444AP12")return n(t,o,s);throw new Error(`CPU color/alpha splitting does not support format '${o}'.`)},i=(s,o,a)=>{const d=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,l=d*c,u=Math.ceil(d/2),f=Math.ceil(c/2),h=l+u*f*2,m=new Uint8Array(h);for(let E=0,C=3;E<l;E++,C+=4)m[E]=s[C];m.fill(128,l);const g=new VideoFrame(s,{format:o==="RGBA"?"RGBX":"BGRX",codedWidth:d,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),b={format:"I420",codedWidth:d,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[m.buffer]},w=new VideoFrame(m,b);return{colorFrame:g,alphaFrame:w}},n=(s,o,a)=>{const d=a.visibleRect?.width??a.codedWidth,c=a.visibleRect?.height??a.codedHeight,l=o.includes("P10"),u=o.includes("P12"),f=l||u?2:1;let h,m;o.startsWith("I420")?(h=Math.ceil(d/2),m=Math.ceil(c/2)):o.startsWith("I422")?(h=Math.ceil(d/2),m=c):(h=d,m=c);const g=d*c,b=h*m,w=g*f,E=b*f,C=g*f,x=w+E*2,B=o.replace("A",""),I=Math.ceil(d/2),A=Math.ceil(c/2),P=I*A,k=P*f,R=C+2*k,W=new Uint8Array(R),O=x;W.set(s.subarray(O,O+C),0);const q=C,X=l?512:u?2048:128;f===1?W.fill(X,q):new Uint16Array(W.buffer,q,2*P).fill(X);const j=l?"I420P10":u?"I420P12":"I420",H=new VideoFrame(s.subarray(0,x),{format:B,codedWidth:d,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0}),ne={format:j,codedWidth:d,codedHeight:c,timestamp:a.timestamp,duration:a.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[W.buffer]},se=new VideoFrame(W,ne);return{colorFrame:H,alphaFrame:se}}};class ra extends Ti{constructor(e,r){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Ts(r),super(r.codec),this._encoder=new Yo(this,r),this._canvas=e}add(e,r=0,i){if(!Number.isFinite(e))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");const n=new K(this._canvas,{timestamp:e,duration:r});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Ei extends $t{constructor(e){if(super(),!Fe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Fe.join(", ")}.`);this._codec=e}}class ia{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,r){this.source=e,this.encodingConfig=r,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 Ur,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,r){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Go({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,r)}finally{r&&e.close()}}async processAndEncode(e,r){const i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&ws(e.format)!==i.transform.sampleFormat){const n=ys(e,i.transform.sampleFormat);r&&e.close(),e=n,r=!0}if(i.transform?.process)try{let n=i.transform.process(e);if(_e(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(const s of n)if(!(s instanceof Y))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(const s of n)await this.encodeSample(s,!0)}finally{for(const s of n)s instanceof Y&&s.close()}}finally{r&&e.close()}else await this.encodeSample(e,r)}async encodeSample(e,r){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized),this.closed)return;{const i=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{const s=i-this.lastEndSampleIndex;if(s>=64){const o=new Y({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(o,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).catch(s=>this.setError(s)).finally(()=>{this.customEncoderQueueSize--,i.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{p(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){p(this.outputSampleSize),p(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:o}=e,a=2048,d=[];for(let g=0;g<n;g+=a){const b=Math.min(a,e.numberOfFrames-g),w=b*i*this.outputSampleSize,E=new ArrayBuffer(w),C=new DataView(E);d.push({frameCount:b,view:C})}const c=e.format==="s32"||e.format==="s32-planar",l=c?"s32-planar":"f32-planar",u=c?1/2147483648:1,f=e.allocationSize({planeIndex:0,format:l}),h=c?new Int32Array(f/4):new Float32Array(f/4);for(let g=0;g<i;g++){e.copyTo(h,{planeIndex:g,format:l});for(let b=0;b<d.length;b++){const{frameCount:w,view:E}=d[b];for(let C=0;C<w;C++)this.writeOutputValue(E,(C*i+g)*this.outputSampleSize,h[b*a+C]*u)}}r&&e.close();const m={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let g=0;g<d.length;g++){const{frameCount:b,view:w}=d[g],E=w.buffer,C=g*a,x=new pe(new Uint8Array(E),"key",o+C/s,b/s);this.encodingConfig.onEncodedPacket?.(x,m),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,x,m)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:r,sampleRate:i}=e,n=ct(this.encodingConfig.quality,this.encodingConfig.bitrate),s=ci({numberOfChannels:r,sampleRate:i,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(s),this.source._nominalBitrate=s.bitrate??null;const o=ui.find(a=>a.supports(this.encodingConfig.codec,s));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(a,d)=>{if(!(a instanceof pe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(d!==void 0&&(!d||typeof d!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,d),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,d).catch(c=>{this.setError(c)})},this.customEncoder.onError=a=>{this.setError(a)},await this.customEncoder.init();else if(ce.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(Hr("AudioEncoder"));let a;try{a=(await AudioEncoder.isConfigSupported(s)).supported??!1}catch{a=!1}if(!a)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);const d=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){if(l.decoderConfig.description&&l.decoderConfig.description.byteLength>0&&$(l.decoderConfig.description)[0]===3){const{decoderSpecificInfo:h}=os(Me.tempFromBytes($(l.decoderConfig.description)));l.decoderConfig.description=h??void 0}let f=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?f=!0:f=tn($(l.decoderConfig.description)).objectType===0,f){const h=Number(G(s.codec.split(".")));l.decoderConfig.description=jr({objectType:h,outputNumberOfChannels:l.decoderConfig.numberOfChannels,outputSampleRate:l.decoderConfig.sampleRate})}}let u=pe.fromEncodedChunk(c);u=u.clone({timestamp:Zt(u.timestamp,s.sampleRate),duration:c.duration!=null?Zt(u.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(u,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,l).catch(f=>{this.setError(f)})},error:c=>{c.stack=d,this.setError(c)}}),this.encoder.configure(s)}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:r,sampleSize:i,littleEndian:n}=Re(e);switch(this.outputSampleSize=i,i){case 1:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint8(o,D(Math.round(a*128)+128,0,255)):r==="signed"?this.writeOutputValue=(s,o,a)=>{s.setInt8(o,D(Math.round(a*128),-128,127))}:r==="ulaw"?this.writeOutputValue=(s,o,a)=>{const d=D(Math.round(a*32768),-32768,32767);s.setUint8(o,Bs(d))}:r==="alaw"?this.writeOutputValue=(s,o,a)=>{const d=D(Math.round(a*32768),-32768,32767);s.setUint8(o,As(d))}:p(!1);break;case 2:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint16(o,D(Math.round(a*32768)+32768,0,65535),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt16(o,D(Math.round(a*32768),-32768,32767),n):p(!1);break;case 3:r==="unsigned"?this.writeOutputValue=(s,o,a)=>Wt(s,o,D(Math.round(a*8388608)+8388608,0,16777215),n):r==="signed"?this.writeOutputValue=(s,o,a)=>Oi(s,o,D(Math.round(a*8388608),-8388608,8388607),n):p(!1);break;case 4:r==="unsigned"?this.writeOutputValue=(s,o,a)=>s.setUint32(o,D(Math.round(a*2147483648)+2147483648,0,4294967295),n):r==="signed"?this.writeOutputValue=(s,o,a)=>s.setInt32(o,D(Math.round(a*2147483648),-2147483648,2147483647),n):r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat32(o,a,n):p(!1);break;case 8:r==="float"?this.writeOutputValue=(s,o,a)=>s.setFloat64(o,a,n):p(!1);break;default:Be(i),p(!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(r=>this.setError(r)):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}}class na extends Ei{constructor(e,r={}){if(Es(e),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.startTimestamp!==void 0&&!Number.isFinite(r.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec),this._encoder=new ia(this,e),this._accumulatedTime=r.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=Y._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of r)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class sa extends $t{constructor(e){if(super(),!je.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${je.join(", ")}.`);this._codec=e}}/*!
|
|
158
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
159
|
+
*
|
|
160
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
161
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
162
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
163
|
+
*/class Ci{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Te.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Fe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>je.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class jt extends Ci{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Gi(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}_createMuxer(e){return new Qo(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class vi extends jt{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...Vt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...je]}_codecUnsupportedHint(e){return new Si().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class zr extends jt{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Te,...Vt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...je]}}class Si extends jt{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Te,...Fe]}_codecUnsupportedHint(e){return new vi().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}/*!
|
|
164
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
165
|
+
*
|
|
166
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
167
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
168
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
169
|
+
*/const Wr=["video","audio","subtitle"];class Ke{constructor(e,r,i,n,s){this.id=e,this.output=r,this.type=i,this.source=n,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Ke))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const r=er(this.metadata.group),i=er(e.metadata.group);for(const n of r)if(this.type!==e.type&&i.some(a=>n===a)||i.some(a=>n._pairedGroups.has(a)))return!0;return!1}}class oa extends Ke{constructor(e,r,i,n){super(e,r,"video",i,n)}}class aa extends Ke{constructor(e,r,i,n){super(e,r,"audio",i,n)}}class ca extends Ke{constructor(e,r,i,n){super(e,r,"subtitle",i,n)}}class Ge{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Ge))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const At=t=>{if(!t||typeof t!="object")throw new TypeError("metadata must be an object.");if(t.languageCode!==void 0&&!Vi(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(t.disposition!==void 0&&en(t.disposition),t.maximumPacketCount!==void 0&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(t.bitrate!==void 0&&(!Number.isFinite(t.bitrate)||t.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(t.averageBitrate!==void 0&&(!Number.isFinite(t.averageBitrate)||t.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(t.group!==void 0&&!(t.group instanceof Ge)&&(!Array.isArray(t.group)||t.group.some(e=>!(e instanceof Ge))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class la extends Lt{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const r=this._getRootTarget();if(_e(r))throw new TypeError(e);return r}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Ge,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Nr,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ci))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ge||e.target instanceof _t))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ge&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ge)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ge&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){p(this._target instanceof _t);const r=this._target.getTarget(e),i=n=>{if(!(n instanceof ge))throw new TypeError("getTarget must return a Target.");return n};return _e(r)?r.then(i):i(r)}async _getTarget(e){p(this._target instanceof _t);const r=await this._getTargetValidated(e);return this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this.state==="canceled"?await r._close():this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(p(this._initTarget!==null),this._initTarget instanceof ge)return this._initTarget;const 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 ge)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),i=n=>(this.state==="canceled"?n._close():this._rememberTarget(n),this._emit("target",{target:n,request:e,isRoot:!0}),this._rootTarget=n,n);return _e(r)?this._rootTargetPromise=r.then(i):i(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const r=await this._getRootTarget(),i=new zt(r,typeof e=="boolean"?e:e(r));return i.start(),i})()}addVideoTrack(e,r={}){if(!(e instanceof Ti))throw new TypeError("source must be a VideoSource.");if(At(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(n=>Number.isFinite(n))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&ti({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof pe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new oa(this.tracks.length+1,this,e,i))}addAudioTrack(e,r={}){if(!(e instanceof Ei))throw new TypeError("source must be an AudioSource.");if(At(r),r.decoderConfig!==void 0&&ri({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof pe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new aa(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,r={}){if(!(e instanceof sa))throw new TypeError("source must be a SubtitleSource.");At(r);const i={...r};return i.group??=this.defaultTrackGroup,this._addTrack(new ca(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(Ji(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const r=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((o,a)=>o+(a.type===e.type?1:0),0),n=r[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(a=>`'${a}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const i of Wr){const n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),s=e[i].min;if(n<s)return!1}const r=e.total.min;return!(this.tracks.length<r)}async start(){const e=this.format.getSupportedTrackCounts();for(const i of Wr){const n=this.tracks.reduce((o,a)=>o+(a.type===i?1:0),0),s=e[i].min;if(n<s)throw new Error(s===e[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}const r=e.total.min;if(this.tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(L._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=this._mutex.acquire();try{await this._muxer.start();const n=this.tracks.map(s=>s.source._start());await Promise.all(n)}finally{(await i)()}})()}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"&&L._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const r=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(L._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const r=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",r}finally{await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}class U{static FRAME_RATE=30;static MADE_BY="UFO@home (https://ufoathome.org)";static CHANNELS=2;static SAMPLE_RATE=48e3;static FRAME_PATIENCE_MS=3e4;static PAINT_EVERY_MS=100;static PAINT_WAIT_MS=50;static FRAME_RETRY_MS=20;static get supported(){return typeof VideoEncoder<"u"&&typeof OffscreenCanvas<"u"}static async film(e,r,i){const n=Math.max(2,Math.floor(e.width/2)*2),s=Math.max(2,Math.floor(e.height/2)*2),o=await xs(["avc","vp9","av1"],{width:n,height:s});if(!o)throw new Error(`No video codec for ${n}×${s}`);const a=new OffscreenCanvas(n,s),d=a.getContext("2d");if(!d)throw new Error("No 2D context");d.imageSmoothingQuality="high";const c=new la({format:new vi({fastStart:"in-memory"}),target:new tt});c.setMetadataTags({artist:U.MADE_BY,date:new Date,...e.about?.title?{title:e.about.title}:{},...e.about?.description?{description:e.about.description}:{},...e.about?.source?{comment:e.about.source}:{}});const l=new ra(a,{codec:o,quality:Br});c.addVideoTrack(l,{frameRate:U.FRAME_RATE});const u=1e3/U.FRAME_RATE,f=e.rate>0?e.rate:1,h=Math.max(0,e.toMs-e.fromMs)/f,m=Math.floor(h/u)+1,g=await _s(["aac","opus"],{numberOfChannels:U.CHANNELS,sampleRate:U.SAMPLE_RATE}),b=g?new na({codec:g,quality:Br}):void 0;b&&c.addAudioTrack(b);const w=b?new OfflineAudioContext(U.CHANNELS,Math.ceil(m/U.FRAME_RATE*U.SAMPLE_RATE),U.SAMPLE_RATE):void 0;await c.start();try{w&&e.hearInto(w);const C=[];for(let A=1;A<m&&w;A++)C[A]=w.suspend(A/U.FRAME_RATE);const x=performance.now();let B,I=performance.now();for(let A=0;A<m;A++){i.throwIfAborted(),A>0&&await C[A];const P=Math.min(e.fromMs+A*u*f,e.toMs);await U.drawFrame(e,P,x+A*u,d,i),await l.add(A/U.FRAME_RATE,1/U.FRAME_RATE),await e.afterFrame?.(A,d),r((A+1)/m),w&&(B?await w.resume():B=w.startRendering()),performance.now()-I>U.PAINT_EVERY_MS&&typeof document<"u"&&!document.hidden?(await new Promise(k=>{requestAnimationFrame(k),setTimeout(k,U.PAINT_WAIT_MS)}),I=performance.now()):await U.nextTask()}b&&B&&await b.add(await B),await c.finalize()}catch(C){throw await c.cancel().catch(()=>{}),C}finally{w&&e.hearInto(void 0)}const E=c.target.buffer;if(!E)throw new Error("Empty film");return new Blob([E],{type:c.format.mimeType})}static async drawFrame(e,r,i,n,s){const o=performance.now()+U.FRAME_PATIENCE_MS;for(;!e.frameAt(r,i,n);){if(s.throwIfAborted(),performance.now()>o)throw new Error(`No frame at ${Math.round(r)} ms`);typeof document<"u"&&document.hidden?await U.nextTask():await new Promise(a=>setTimeout(a,U.FRAME_RETRY_MS))}}static nextTask(){return new Promise(e=>{const r=new MessageChannel;r.port1.onmessage=()=>{r.port1.close(),e()},r.port2.postMessage(void 0)})}}const ua=Object.freeze(Object.defineProperty({__proto__:null,VideoExport:U},Symbol.toStringTag,{value:"Module"}));export{tt as B,ra as C,vi as M,la as O,Br as Q,U as V,ua as a,xs as g};
|