zhuda-laya-engine 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +236 -0
- package/CHANGELOG.md +431 -0
- package/LICENSE +41 -0
- package/README.md +247 -2
- package/assets/branding/layaair-tribute-mark.svg +5 -0
- package/assets/branding/zhuda-layaair-mark.svg +34 -0
- package/assets/prefabs/CoinFountainVfx.lh +197 -0
- package/assets/prefabs/ConfirmActionButton.lh +87 -0
- package/assets/prefabs/LevelUpAuraVfx.lh +136 -0
- package/assets/prefabs/MineExplosionParticle.lh +352 -0
- package/assets/prefabs/NineSliceDialogFrame.lh +171 -0
- package/assets/prefabs/SwordSlashTrailVfx.lh +117 -0
- package/assets/prefabs/TacticalHudBar.lh +134 -0
- package/assets/prefabs/TelemetryDashboard.lh +87 -0
- package/assets/prefabs/UnityCrystalGuardian.lh +144 -0
- package/assets/prefabs/ZhudaSpine42Mascot.lh +183 -0
- package/assets/scenes/MinesweeperStage.ls +1180 -0
- package/dist/asset-calibration-report.json +969 -0
- package/dist/build-manifest.json +254 -0
- package/dist/sdk/zhuda-laya-csg.cjs +710 -0
- package/dist/sdk/zhuda-laya-csg.esm.js +683 -0
- package/dist/sdk/zhuda-laya-csg.min.cjs +7 -0
- package/dist/sdk/zhuda-laya-csg.min.esm.js +7 -0
- package/dist/sdk/zhuda-laya-demo.cjs +5990 -0
- package/dist/sdk/zhuda-laya-demo.esm.js +5956 -0
- package/dist/sdk/zhuda-laya-demo.min.cjs +12 -0
- package/dist/sdk/zhuda-laya-demo.min.esm.js +12 -0
- package/dist/sdk/zhuda-laya-engine.cjs +52628 -0
- package/dist/sdk/zhuda-laya-engine.esm.js +51848 -0
- package/dist/sdk/zhuda-laya-engine.min.cjs +2710 -0
- package/dist/sdk/zhuda-laya-engine.min.esm.js +2710 -0
- package/docs/3d-acceptance.md +47 -0
- package/docs/3d-integration.md +190 -0
- package/docs/README.md +112 -0
- package/docs/SUPPORT.md +21 -0
- package/docs/agent-development.md +219 -0
- package/docs/animation-control.md +213 -0
- package/docs/asset-loading.md +97 -0
- package/docs/assets/reference-games.jpg +0 -0
- package/docs/assets/solana-qr.png +0 -0
- package/docs/assets/sponsor-pass.svg +32 -0
- package/docs/audio.md +319 -0
- package/docs/backend-delivery.md +218 -0
- package/docs/basis-textures.md +94 -0
- package/docs/browser-sdk-releases.json +204 -0
- package/docs/browser-sdk.md +187 -0
- package/docs/cinematics.md +267 -0
- package/docs/cloth.md +280 -0
- package/docs/combat-runtime.md +82 -0
- package/docs/consumer-route.md +169 -0
- package/docs/consumer-tooling.md +518 -0
- package/docs/crowd-runtime.md +195 -0
- package/docs/developer-tooling.md +191 -0
- package/docs/film-scenes.md +1504 -0
- package/docs/filmic-rendering.md +743 -0
- package/docs/flythrough.md +89 -0
- package/docs/gpu-depth.md +207 -0
- package/docs/grass.md +127 -0
- package/docs/hdr-environment.md +76 -0
- package/docs/instanced-meshes.md +137 -0
- package/docs/layout-and-media.md +37 -0
- package/docs/layout-wireframe.md +80 -0
- package/docs/lighting-depth.md +185 -0
- package/docs/minigame-packaging.md +79 -0
- package/docs/model-editor.md +66 -0
- package/docs/model-lod.md +122 -0
- package/docs/model-pipeline.md +74 -0
- package/docs/model-showcase.md +365 -0
- package/docs/overview.md +183 -0
- package/docs/plans/README.md +133 -0
- package/docs/plans/TASK-TEMPLATE.md +64 -0
- package/docs/plans/TASK-spine38-isolated-topology-20261106.md +89 -0
- package/docs/plans/TEMPLATE.md +44 -0
- package/docs/plans/VERIFICATION-TEMPLATE.md +45 -0
- package/docs/plans/asset-packaging.md +140 -0
- package/docs/plans/cinematic-production/task.md +97 -0
- package/docs/plans/cinematic-production/verification.md +49 -0
- package/docs/plans/consumer-delivery-followups.md +129 -0
- package/docs/plans/desktop-and-agent-gates/hardening-task.md +85 -0
- package/docs/plans/desktop-and-agent-gates/hardening-verification.md +109 -0
- package/docs/plans/desktop-and-agent-gates/task.md +94 -0
- package/docs/plans/desktop-and-agent-gates/verification.md +60 -0
- package/docs/plans/prefab-toolchain.md +73 -0
- package/docs/plans/preview-runtime-hardening.md +68 -0
- package/docs/platform-adapters.md +113 -0
- package/docs/post-quality.md +242 -0
- package/docs/prefab-editor.md +194 -0
- package/docs/prefab-library.md +94 -0
- package/docs/prefab-workflow.md +75 -0
- package/docs/procedural-assets.md +463 -0
- package/docs/procedural-prefabs.md +133 -0
- package/docs/quality-route.md +386 -0
- package/docs/release-policy.md +79 -0
- package/docs/routes/README.md +180 -0
- package/docs/routes/TEMPLATE.md +54 -0
- package/docs/routes/action-adventure-3d-minigame.md +238 -0
- package/docs/routes/apocalypse-survival-3d.md +219 -0
- package/docs/routes/aqua-freeze-2d-minigame.md +183 -0
- package/docs/routes/astral-minimal-film-look.md +141 -0
- package/docs/routes/cascade-slot.md +93 -0
- package/docs/routes/clip-free-garments.md +229 -0
- package/docs/routes/drop-merge-2d-minigame.md +200 -0
- package/docs/routes/dungeon-line-slot.md +87 -0
- package/docs/routes/film-as-data.md +131 -0
- package/docs/routes/film-fight-that-lands.md +198 -0
- package/docs/routes/film-ink-lines.md +120 -0
- package/docs/routes/floating-island.md +229 -0
- package/docs/routes/game-2d.md +168 -0
- package/docs/routes/game-rules-first.md +89 -0
- package/docs/routes/game-to-prefabs.md +249 -0
- package/docs/routes/go-game-server.md +95 -0
- package/docs/routes/good-looking-3d-scene.md +99 -0
- package/docs/routes/high-quality-character.md +263 -0
- package/docs/routes/humanoid-from-shapes.md +97 -0
- package/docs/routes/hunting-action-3d.md +76 -0
- package/docs/routes/idle-gacha-2d.md +67 -0
- package/docs/routes/interactive-film-viewer.md +141 -0
- package/docs/routes/isometric-mystery-2d.md +217 -0
- package/docs/routes/key-art-to-animated-title.md +132 -0
- package/docs/routes/laya-ide-project-cli-web.md +125 -0
- package/docs/routes/layered-cloth-on-body.md +240 -0
- package/docs/routes/low-poly-character-from-shapes.md +475 -0
- package/docs/routes/match-three-2d.md +64 -0
- package/docs/routes/merge-2d.md +59 -0
- package/docs/routes/mini-game-build.md +80 -0
- package/docs/routes/mobile-always-landscape.md +149 -0
- package/docs/routes/mobile-web-fullscreen.md +255 -0
- package/docs/routes/model-from-dcc.md +106 -0
- package/docs/routes/new-game-project.md +100 -0
- package/docs/routes/onboarding-tutorial-2d.md +54 -0
- package/docs/routes/online-lockstep-match.md +473 -0
- package/docs/routes/outdoor-landscape.md +134 -0
- package/docs/routes/outfit-swap-3d.md +144 -0
- package/docs/routes/papercraft-diorama.md +186 -0
- package/docs/routes/platform-fighter-2d.md +235 -0
- package/docs/routes/platformer-2d.md +69 -0
- package/docs/routes/pole-rescue-arcade-3d.md +198 -0
- package/docs/routes/pose-atlas-motion.md +188 -0
- package/docs/routes/prototype-to-center.md +162 -0
- package/docs/routes/raft-brawl-3d-minigame.md +205 -0
- package/docs/routes/rhythm-2d.md +82 -0
- package/docs/routes/rigged-phone-character.md +120 -0
- package/docs/routes/screen-fit-game-box.md +127 -0
- package/docs/routes/shared-islands.md +195 -0
- package/docs/routes/side-view-duel.md +266 -0
- package/docs/routes/single-html-page.md +83 -0
- package/docs/routes/smooth-character-motion.md +162 -0
- package/docs/routes/spine-character.md +175 -0
- package/docs/routes/story-counting-2d.md +219 -0
- package/docs/routes/survivors-2d.md +60 -0
- package/docs/routes/third-person-town-3d.md +240 -0
- package/docs/routes/tower-defence-3d.md +67 -0
- package/docs/routes/ui-test-by-probe.md +219 -0
- package/docs/routes/underwater.md +138 -0
- package/docs/routes/visual-content-prefab.md +101 -0
- package/docs/runtime-hardening.md +108 -0
- package/docs/shader-warm-up.md +125 -0
- package/docs/spring-bones.md +79 -0
- package/docs/stylized-shading.md +171 -0
- package/docs/terrain-shader.md +130 -0
- package/docs/vrm.md +128 -0
- package/docs/walking.md +97 -0
- package/docs/webgpu.md +225 -0
- package/docs/white-label-themes.md +212 -0
- package/docs/zh-CN/README.md +130 -0
- package/examples/browser-sdk/2d-webgpu.html +46 -0
- package/examples/browser-sdk/2d.html +46 -0
- package/examples/browser-sdk/3d-gltf-webgpu.html +50 -0
- package/examples/browser-sdk/3d-gltf.html +50 -0
- package/examples/browser-sdk/3d-webgpu.html +46 -0
- package/examples/browser-sdk/3d.html +46 -0
- package/examples/cinematic-capture/Main.ts +294 -0
- package/examples/cinematic-capture/README.md +27 -0
- package/examples/model-inspector/README.md +15 -0
- package/examples/model-inspector/asset.gltf +158 -0
- package/examples/windows-webgpu/README.md +57 -0
- package/examples/windows-webgpu/bundle.mjs +122 -0
- package/examples/windows-webgpu/main.mjs +302 -0
- package/examples/windows-webgpu/package-lock.json +2353 -0
- package/examples/windows-webgpu/package.json +40 -0
- package/examples/windows-webgpu/squirrel.mjs +66 -0
- package/package.json +259 -4
- package/packages/ci-gate/export-film.mjs +347 -0
- package/packages/ci-gate/verify-sequence.mjs +285 -0
- package/packages/compiler/agent-contract.mjs +545 -0
- package/packages/compiler/ast-scanner.mjs +254 -0
- package/packages/compiler/backend-loader.mjs +62 -0
- package/packages/compiler/branding-assets.mjs +32 -0
- package/packages/compiler/branding.mjs +324 -0
- package/packages/compiler/browser-auto-example.mjs +31 -0
- package/packages/compiler/browser-model-example.mjs +53 -0
- package/packages/compiler/browser-process.mjs +344 -0
- package/packages/compiler/browser-sdk-example.mjs +50 -0
- package/packages/compiler/browser-sdk.mjs +342 -0
- package/packages/compiler/chrome-host.mjs +196 -0
- package/packages/compiler/cli.mjs +22 -0
- package/packages/compiler/compiler-runtime.mjs +41 -0
- package/packages/compiler/consumer-accept.mjs +89 -0
- package/packages/compiler/consumer-build.mjs +641 -0
- package/packages/compiler/consumer-guards.mjs +422 -0
- package/packages/compiler/consumer-publication.mjs +56 -0
- package/packages/compiler/consumer-scripts.mjs +134 -0
- package/packages/compiler/consumer-starter-2d.mjs +54 -0
- package/packages/compiler/consumer-starter-minigame.mjs +30 -0
- package/packages/compiler/editor-http.mjs +210 -0
- package/packages/compiler/editor-request.ts +12 -0
- package/packages/compiler/film-host-client.ts +249 -0
- package/packages/compiler/flythrough-file.mjs +144 -0
- package/packages/compiler/json-locate.mjs +85 -0
- package/packages/compiler/layout-contract.mjs +472 -0
- package/packages/compiler/minigame-bootstrap.mjs +24 -0
- package/packages/compiler/minigame-bridge.mjs +66 -0
- package/packages/compiler/minigame-guards.mjs +107 -0
- package/packages/compiler/minigame-toolchain.mjs +241 -0
- package/packages/compiler/model-crown.mjs +173 -0
- package/packages/compiler/model-editor-client.ts +809 -0
- package/packages/compiler/model-editor.mjs +242 -0
- package/packages/compiler/model-lod.mjs +547 -0
- package/packages/compiler/prefab-check.mjs +288 -0
- package/packages/compiler/prefab-checks.mjs +74 -0
- package/packages/compiler/prefab-dependencies.mjs +102 -0
- package/packages/compiler/prefab-editor-client.ts +950 -0
- package/packages/compiler/prefab-editor-preview.ts +89 -0
- package/packages/compiler/prefab-editor-server.mjs +585 -0
- package/packages/compiler/prefab-editor.mjs +43 -0
- package/packages/compiler/prefab-environment.mjs +107 -0
- package/packages/compiler/prefab-lifecycle.mjs +60 -0
- package/packages/compiler/prefab-preview.mjs +159 -0
- package/packages/compiler/prefab-watch.mjs +459 -0
- package/packages/compiler/runtime3d-types.mjs +91 -0
- package/packages/compiler/stage-probe.mjs +557 -0
- package/packages/compiler/visual-asset-audit.mjs +609 -0
- package/packages/compiler/visual-contract-audit.mjs +173 -0
- package/packages/compiler/webgpu-loader.mjs +153 -0
- package/packages/compiler/zhuda-build.mjs +714 -0
- package/packages/compiler/zhuda-doctor.mjs +186 -0
- package/packages/compiler/zhuda-init.mjs +353 -0
- package/packages/compiler/zhuda-layout.mjs +163 -0
- package/packages/compiler/zhuda-minigame.mjs +636 -0
- package/packages/core/BenchmarkEngine.ts +2 -0
- package/packages/core/BitmapFontContract.ts +159 -0
- package/packages/core/DeclarativeSDK.ts +686 -0
- package/packages/core/IframeSoundAdapter.ts +1824 -0
- package/packages/core/NoSleepAdapter.ts +302 -0
- package/packages/core/PixelCalibrationEngine.ts +602 -0
- package/packages/core/Prefab.ts +314 -0
- package/packages/core/RealmGuards.ts +111 -0
- package/packages/core/ResponsiveLayout.ts +149 -0
- package/packages/core/RuntimeGuards.ts +261 -0
- package/packages/core/SpineCharacter.ts +243 -0
- package/packages/core/SpineVisualContract.ts +238 -0
- package/packages/core/SplashSignal.ts +72 -0
- package/packages/core/StaticAssetPipeline.ts +3 -0
- package/packages/core/TopologyGraph.ts +693 -0
- package/packages/core/UnityBridgePipeline.ts +2 -0
- package/packages/core/VideoSurface.ts +75 -0
- package/packages/core/ViewportMatrixEngine.ts +237 -0
- package/packages/core/VisualFocusContract.ts +76 -0
- package/packages/core/VisualMigrationPipeline.ts +245 -0
- package/packages/core/WebViewSurface.ts +116 -0
- package/packages/core/audio/OfflineMix.ts +186 -0
- package/packages/core/audio/Spatial.ts +312 -0
- package/packages/core/audio/StreamVoice.ts +161 -0
- package/packages/core/csg/Bsp.ts +310 -0
- package/packages/core/csg/index.ts +589 -0
- package/packages/core/effects/Effect2D.ts +286 -0
- package/packages/core/effects/Effect3D.ts +213 -0
- package/packages/core/effects/EffectBudget.ts +695 -0
- package/packages/core/effects/EffectDirector.ts +254 -0
- package/packages/core/effects/EffectPresets.ts +843 -0
- package/packages/core/effects/EffectPresets2D.ts +1011 -0
- package/packages/core/effects/EffectSprites.ts +143 -0
- package/packages/core/effects/ParticleEventLink.ts +53 -0
- package/packages/core/effects/README.md +108 -0
- package/packages/core/effects/VfxMaterial.ts +253 -0
- package/packages/core/film/BakeKey.ts +21 -0
- package/packages/core/film/ColorValues.ts +44 -0
- package/packages/core/film/FilmLint.ts +353 -0
- package/packages/core/film/FilmPrefab.ts +82 -0
- package/packages/core/film/FilmReview.ts +84 -0
- package/packages/core/film/FilmScene.ts +3442 -0
- package/packages/core/film/FilmStage.ts +2148 -0
- package/packages/core/film/Flythrough.ts +169 -0
- package/packages/core/film/FlythroughReport.ts +326 -0
- package/packages/core/film/FrameMetrics.ts +167 -0
- package/packages/core/film/LiveLook.ts +242 -0
- package/packages/core/film/LookQuality.ts +94 -0
- package/packages/core/film/Projection.ts +74 -0
- package/packages/core/film/SceneLook.ts +363 -0
- package/packages/core/film/index.ts +12 -0
- package/packages/core/index.ts +48 -0
- package/packages/core/particles/EffectEnvelope.ts +52 -0
- package/packages/core/particles/LayaParticleRenderer.ts +182 -0
- package/packages/core/particles/LayaParticleRenderer3D.ts +218 -0
- package/packages/core/particles/ParticleExtras.ts +163 -0
- package/packages/core/particles/ParticleMesh3D.ts +156 -0
- package/packages/core/particles/ParticleSystem.ts +324 -0
- package/packages/core/particles/ParticleSystem3D.ts +411 -0
- package/packages/core/particles/ParticleTypes.ts +230 -0
- package/packages/core/particles/ParticleTypes3D.ts +115 -0
- package/packages/core/particles/README.md +181 -0
- package/packages/core/particles/RibbonPath3D.ts +234 -0
- package/packages/core/particles/RibbonTrail.ts +145 -0
- package/packages/core/particles/RibbonTrail3D.ts +166 -0
- package/packages/core/particles/index.ts +12 -0
- package/packages/core/prefabs/PrefabLibrary.ts +692 -0
- package/packages/core/prefabs/PrefabTree3D.ts +291 -0
- package/packages/core/prefabs/index.ts +10 -0
- package/packages/core/procedural/Geometry.ts +1871 -0
- package/packages/core/procedural/Hand.ts +1510 -0
- package/packages/core/procedural/Isosurface.ts +1035 -0
- package/packages/core/procedural/ModuleHarness.ts +180 -0
- package/packages/core/procedural/Noise.ts +123 -0
- package/packages/core/procedural/PhotoMaterial.ts +283 -0
- package/packages/core/procedural/ProceduralAssetProvider.ts +105 -0
- package/packages/core/procedural/ProceduralMaterial.ts +184 -0
- package/packages/core/procedural/PropFactory.ts +307 -0
- package/packages/core/procedural/Random.ts +70 -0
- package/packages/core/procedural/SynthAudio.ts +221 -0
- package/packages/core/procedural/TerrainMesh.ts +207 -0
- package/packages/core/procedural/TextureRecipe.ts +464 -0
- package/packages/core/procedural/TriplanarMaterial.ts +169 -0
- package/packages/core/procedural/Variation.ts +94 -0
- package/packages/core/procedural/index.ts +15 -0
- package/packages/core/runtime3d/ActionFrames.ts +245 -0
- package/packages/core/runtime3d/AnimationBlend.ts +282 -0
- package/packages/core/runtime3d/AnimationBlendMath.ts +98 -0
- package/packages/core/runtime3d/AssetProvider.ts +775 -0
- package/packages/core/runtime3d/AssetShowcase.ts +190 -0
- package/packages/core/runtime3d/Assets.ts +801 -0
- package/packages/core/runtime3d/AsyncDeadline.ts +53 -0
- package/packages/core/runtime3d/AsyncOperation.ts +39 -0
- package/packages/core/runtime3d/BackendChoice.ts +359 -0
- package/packages/core/runtime3d/BakedCrowd.ts +575 -0
- package/packages/core/runtime3d/BasisTexture.ts +657 -0
- package/packages/core/runtime3d/CameraCollision.ts +69 -0
- package/packages/core/runtime3d/CameraEffects.ts +752 -0
- package/packages/core/runtime3d/CameraRig.ts +70 -0
- package/packages/core/runtime3d/CharacterController.ts +272 -0
- package/packages/core/runtime3d/CinematicCapture.ts +457 -0
- package/packages/core/runtime3d/Clocks.ts +724 -0
- package/packages/core/runtime3d/Cloth.ts +183 -0
- package/packages/core/runtime3d/Clouds.ts +462 -0
- package/packages/core/runtime3d/ColorLut.ts +351 -0
- package/packages/core/runtime3d/CombatQueries.ts +240 -0
- package/packages/core/runtime3d/ComputePass.ts +582 -0
- package/packages/core/runtime3d/CrowdPresentation.ts +368 -0
- package/packages/core/runtime3d/DebugDraw.ts +567 -0
- package/packages/core/runtime3d/DebugStats.ts +35 -0
- package/packages/core/runtime3d/Decals.ts +309 -0
- package/packages/core/runtime3d/DensityVolume.ts +238 -0
- package/packages/core/runtime3d/DistanceBricks.ts +349 -0
- package/packages/core/runtime3d/Dither.ts +199 -0
- package/packages/core/runtime3d/DrawWarmUp.ts +217 -0
- package/packages/core/runtime3d/EdgeSmoothing.ts +108 -0
- package/packages/core/runtime3d/EnvironmentProbe.ts +656 -0
- package/packages/core/runtime3d/Filmic.ts +973 -0
- package/packages/core/runtime3d/Foliage.ts +367 -0
- package/packages/core/runtime3d/GltfIntake.ts +914 -0
- package/packages/core/runtime3d/GltfSecondUv.ts +153 -0
- package/packages/core/runtime3d/GraphicsGuard.ts +171 -0
- package/packages/core/runtime3d/Grass.ts +1080 -0
- package/packages/core/runtime3d/GroundTruthAO.ts +360 -0
- package/packages/core/runtime3d/HalfFloat.ts +44 -0
- package/packages/core/runtime3d/HdrEnvironment.ts +588 -0
- package/packages/core/runtime3d/Ik.ts +392 -0
- package/packages/core/runtime3d/InputBuffer.ts +165 -0
- package/packages/core/runtime3d/InstancedMesh.ts +460 -0
- package/packages/core/runtime3d/Laya342Adapters.ts +1095 -0
- package/packages/core/runtime3d/Laya342GltfAdapter.ts +751 -0
- package/packages/core/runtime3d/LensFinish.ts +153 -0
- package/packages/core/runtime3d/LensFlare.ts +490 -0
- package/packages/core/runtime3d/LightFog.ts +1008 -0
- package/packages/core/runtime3d/LightingDepth.ts +544 -0
- package/packages/core/runtime3d/Lightmap.ts +238 -0
- package/packages/core/runtime3d/Math3D.ts +84 -0
- package/packages/core/runtime3d/MeshQuery.ts +547 -0
- package/packages/core/runtime3d/MeshoptModelDecoder.ts +354 -0
- package/packages/core/runtime3d/MiniGameSplash.ts +70 -0
- package/packages/core/runtime3d/ModelAnimationSampler.ts +97 -0
- package/packages/core/runtime3d/ModelCompatibility.ts +890 -0
- package/packages/core/runtime3d/ModelDecoder.ts +294 -0
- package/packages/core/runtime3d/ModelInspector.ts +226 -0
- package/packages/core/runtime3d/ModelLod.ts +163 -0
- package/packages/core/runtime3d/ModelPlacements.ts +426 -0
- package/packages/core/runtime3d/ObjectMotion.ts +217 -0
- package/packages/core/runtime3d/PhysicalCamera.ts +190 -0
- package/packages/core/runtime3d/PointShadow.ts +500 -0
- package/packages/core/runtime3d/PointShadowSchedule.ts +201 -0
- package/packages/core/runtime3d/Pool.ts +120 -0
- package/packages/core/runtime3d/ProbeVolume.ts +695 -0
- package/packages/core/runtime3d/QualityGovernor.ts +385 -0
- package/packages/core/runtime3d/QualityMemory.ts +200 -0
- package/packages/core/runtime3d/RenderScale.ts +356 -0
- package/packages/core/runtime3d/RenderSpaces.ts +105 -0
- package/packages/core/runtime3d/Renderer.ts +377 -0
- package/packages/core/runtime3d/ResultPlayback.ts +239 -0
- package/packages/core/runtime3d/Runtime.ts +507 -0
- package/packages/core/runtime3d/RuntimeDriver.ts +127 -0
- package/packages/core/runtime3d/SceneLifecycle.ts +211 -0
- package/packages/core/runtime3d/SceneMutation.ts +107 -0
- package/packages/core/runtime3d/SceneQueries.ts +191 -0
- package/packages/core/runtime3d/ScreenReflections.ts +595 -0
- package/packages/core/runtime3d/SelectionOutline.ts +389 -0
- package/packages/core/runtime3d/ShaderErrors.ts +104 -0
- package/packages/core/runtime3d/ShaderRegistry.ts +34 -0
- package/packages/core/runtime3d/ShaderWarmUp.ts +473 -0
- package/packages/core/runtime3d/ShadowUpdates.ts +287 -0
- package/packages/core/runtime3d/SkinBinding.ts +235 -0
- package/packages/core/runtime3d/Smaa.ts +386 -0
- package/packages/core/runtime3d/SmaaTables.ts +244 -0
- package/packages/core/runtime3d/SpringBones.ts +184 -0
- package/packages/core/runtime3d/SurfaceBuffer.ts +76 -0
- package/packages/core/runtime3d/Surfaces.ts +1105 -0
- package/packages/core/runtime3d/Themes.ts +344 -0
- package/packages/core/runtime3d/Timeline.ts +362 -0
- package/packages/core/runtime3d/ToneCurves.ts +292 -0
- package/packages/core/runtime3d/TransformGizmo.ts +539 -0
- package/packages/core/runtime3d/TriangleMask.ts +250 -0
- package/packages/core/runtime3d/Underwater.ts +778 -0
- package/packages/core/runtime3d/Utf8.ts +87 -0
- package/packages/core/runtime3d/Vrm.ts +773 -0
- package/packages/core/runtime3d/VrmDocument.ts +1830 -0
- package/packages/core/runtime3d/WalkGrid.ts +471 -0
- package/packages/core/runtime3d/WebGPU342Adapters.ts +280 -0
- package/packages/core/runtime3d/index.ts +147 -0
- package/packages/core/shaders/Laya342ShaderTemplates.ts +6 -0
- package/packages/core/shaders/LitSurfaceMaterial.ts +1076 -0
- package/packages/core/shaders/LitSurfaceTemplates.ts +13 -0
- package/packages/core/shaders/ReflectiveSurface.ts +285 -0
- package/packages/core/shaders/ShaderMaterials.ts +387 -0
- package/packages/core/shaders/ToonMaterial.ts +559 -0
- package/packages/core/shaders/WaterRipples.ts +170 -0
- package/packages/core/shaders/WaterSurface.ts +480 -0
- package/packages/core/shaders/ZhudaCommon.ts +109 -0
- package/packages/core/shaders/index.ts +6 -0
- package/packages/core/simulation/Cloth.ts +1541 -0
- package/packages/core/simulation/ParticleCore.ts +498 -0
- package/packages/core/simulation/SpringBones.ts +553 -0
- package/packages/core/simulation/index.ts +3 -0
- package/packages/core/terrain/Heightfield.ts +385 -0
- package/packages/core/terrain/Terrain2D.ts +324 -0
- package/packages/core/terrain/Terrain3D.ts +452 -0
- package/packages/core/terrain/TerrainShell.ts +94 -0
- package/packages/core/terrain/index.ts +3 -0
- package/packages/demo/BenchmarkEngine.ts +184 -0
- package/packages/demo/PixelCalibrationEngine.ts +36 -0
- package/packages/demo/ProceduralStarter.ts +312 -0
- package/packages/demo/StaticAssetPipeline.ts +1631 -0
- package/packages/demo/UnityBridgePipeline.ts +485 -0
- package/packages/demo/index.ts +6 -0
- package/packages/mcp-server/arguments.mjs +81 -0
- package/packages/mcp-server/corpus.mjs +627 -0
- package/packages/mcp-server/film-host.mjs +627 -0
- package/packages/mcp-server/film-session.mjs +95 -0
- package/packages/mcp-server/film-tools.mjs +460 -0
- package/packages/mcp-server/index.mjs +931 -0
- package/packages/mcp-server/quality-route.mjs +332 -0
- package/packages/mcp-server/roots.mjs +72 -0
- package/packages/mcp-server/runtime.mjs +81 -0
- package/packages/types/BitmapFontContract.d.ts +19 -0
- package/packages/types/DeclarativeSDK.d.ts +137 -0
- package/packages/types/IframeSoundAdapter.d.ts +173 -0
- package/packages/types/NoSleepAdapter.d.ts +50 -0
- package/packages/types/PixelCalibrationEngine.d.ts +83 -0
- package/packages/types/Prefab.d.ts +11 -0
- package/packages/types/RealmGuards.d.ts +26 -0
- package/packages/types/ResponsiveLayout.d.ts +10 -0
- package/packages/types/RuntimeGuards.d.ts +55 -0
- package/packages/types/SpineCharacter.d.ts +94 -0
- package/packages/types/SpineVisualContract.d.ts +50 -0
- package/packages/types/SplashSignal.d.ts +27 -0
- package/packages/types/TopologyGraph.d.ts +76 -0
- package/packages/types/VideoSurface.d.ts +21 -0
- package/packages/types/ViewportMatrixEngine.d.ts +27 -0
- package/packages/types/VisualFocusContract.d.ts +32 -0
- package/packages/types/VisualMigrationPipeline.d.ts +53 -0
- package/packages/types/WebViewSurface.d.ts +26 -0
- package/packages/types/audio/OfflineMix.d.ts +10 -0
- package/packages/types/audio/Spatial.d.ts +63 -0
- package/packages/types/audio/StreamVoice.d.ts +31 -0
- package/packages/types/browser.d.ts +44 -0
- package/packages/types/csg/Bsp.d.ts +85 -0
- package/packages/types/csg/index.d.ts +81 -0
- package/packages/types/demo/BenchmarkEngine.d.ts +61 -0
- package/packages/types/demo/PixelCalibrationEngine.d.ts +13 -0
- package/packages/types/demo/ProceduralStarter.d.ts +11 -0
- package/packages/types/demo/StaticAssetPipeline.d.ts +87 -0
- package/packages/types/demo/UnityBridgePipeline.d.ts +49 -0
- package/packages/types/demo/index.d.ts +7 -0
- package/packages/types/editor-preview.d.ts +27 -0
- package/packages/types/effects/Effect2D.d.ts +65 -0
- package/packages/types/effects/Effect3D.d.ts +42 -0
- package/packages/types/effects/EffectBudget.d.ts +179 -0
- package/packages/types/effects/EffectDirector.d.ts +68 -0
- package/packages/types/effects/EffectPresets.d.ts +27 -0
- package/packages/types/effects/EffectPresets2D.d.ts +32 -0
- package/packages/types/effects/EffectSprites.d.ts +23 -0
- package/packages/types/effects/ParticleEventLink.d.ts +16 -0
- package/packages/types/effects/VfxMaterial.d.ts +52 -0
- package/packages/types/film/BakeKey.d.ts +9 -0
- package/packages/types/film/ColorValues.d.ts +25 -0
- package/packages/types/film/FilmLint.d.ts +40 -0
- package/packages/types/film/FilmPrefab.d.ts +22 -0
- package/packages/types/film/FilmReview.d.ts +27 -0
- package/packages/types/film/FilmScene.d.ts +1214 -0
- package/packages/types/film/FilmStage.d.ts +237 -0
- package/packages/types/film/Flythrough.d.ts +44 -0
- package/packages/types/film/FlythroughReport.d.ts +132 -0
- package/packages/types/film/FrameMetrics.d.ts +49 -0
- package/packages/types/film/LiveLook.d.ts +60 -0
- package/packages/types/film/LookQuality.d.ts +24 -0
- package/packages/types/film/Projection.d.ts +20 -0
- package/packages/types/film/SceneLook.d.ts +122 -0
- package/packages/types/film/index.d.ts +13 -0
- package/packages/types/index.d.ts +49 -0
- package/packages/types/particles/EffectEnvelope.d.ts +18 -0
- package/packages/types/particles/LayaParticleRenderer.d.ts +30 -0
- package/packages/types/particles/LayaParticleRenderer3D.d.ts +29 -0
- package/packages/types/particles/ParticleExtras.d.ts +50 -0
- package/packages/types/particles/ParticleMesh3D.d.ts +24 -0
- package/packages/types/particles/ParticleSystem.d.ts +52 -0
- package/packages/types/particles/ParticleSystem3D.d.ts +69 -0
- package/packages/types/particles/ParticleTypes.d.ts +89 -0
- package/packages/types/particles/ParticleTypes3D.d.ts +56 -0
- package/packages/types/particles/RibbonPath3D.d.ts +32 -0
- package/packages/types/particles/RibbonTrail.d.ts +38 -0
- package/packages/types/particles/RibbonTrail3D.d.ts +22 -0
- package/packages/types/particles/index.d.ts +13 -0
- package/packages/types/prefabs/PrefabLibrary.d.ts +176 -0
- package/packages/types/prefabs/PrefabTree3D.d.ts +59 -0
- package/packages/types/prefabs/index.d.ts +4 -0
- package/packages/types/procedural/Geometry.d.ts +252 -0
- package/packages/types/procedural/Hand.d.ts +150 -0
- package/packages/types/procedural/Isosurface.d.ts +181 -0
- package/packages/types/procedural/ModuleHarness.d.ts +90 -0
- package/packages/types/procedural/Noise.d.ts +15 -0
- package/packages/types/procedural/PhotoMaterial.d.ts +49 -0
- package/packages/types/procedural/ProceduralAssetProvider.d.ts +31 -0
- package/packages/types/procedural/ProceduralMaterial.d.ts +63 -0
- package/packages/types/procedural/PropFactory.d.ts +94 -0
- package/packages/types/procedural/Random.d.ts +26 -0
- package/packages/types/procedural/SynthAudio.d.ts +49 -0
- package/packages/types/procedural/TerrainMesh.d.ts +55 -0
- package/packages/types/procedural/TextureRecipe.d.ts +125 -0
- package/packages/types/procedural/TriplanarMaterial.d.ts +27 -0
- package/packages/types/procedural/Variation.d.ts +23 -0
- package/packages/types/procedural/index.d.ts +16 -0
- package/packages/types/runtime3d/ActionFrames.d.ts +62 -0
- package/packages/types/runtime3d/AnimationBlend.d.ts +57 -0
- package/packages/types/runtime3d/AnimationBlendMath.d.ts +27 -0
- package/packages/types/runtime3d/AssetProvider.d.ts +167 -0
- package/packages/types/runtime3d/AssetShowcase.d.ts +44 -0
- package/packages/types/runtime3d/Assets.d.ts +166 -0
- package/packages/types/runtime3d/AsyncDeadline.d.ts +6 -0
- package/packages/types/runtime3d/AsyncOperation.d.ts +3 -0
- package/packages/types/runtime3d/BackendChoice.d.ts +130 -0
- package/packages/types/runtime3d/BakedCrowd.d.ts +156 -0
- package/packages/types/runtime3d/BasisTexture.d.ts +169 -0
- package/packages/types/runtime3d/CameraCollision.d.ts +20 -0
- package/packages/types/runtime3d/CameraEffects.d.ts +134 -0
- package/packages/types/runtime3d/CameraRig.d.ts +27 -0
- package/packages/types/runtime3d/CharacterController.d.ts +71 -0
- package/packages/types/runtime3d/CinematicCapture.d.ts +103 -0
- package/packages/types/runtime3d/Clocks.d.ts +200 -0
- package/packages/types/runtime3d/Cloth.d.ts +57 -0
- package/packages/types/runtime3d/Clouds.d.ts +69 -0
- package/packages/types/runtime3d/ColorLut.d.ts +73 -0
- package/packages/types/runtime3d/CombatQueries.d.ts +50 -0
- package/packages/types/runtime3d/ComputePass.d.ts +134 -0
- package/packages/types/runtime3d/CrowdPresentation.d.ts +104 -0
- package/packages/types/runtime3d/DebugDraw.d.ts +161 -0
- package/packages/types/runtime3d/DebugStats.d.ts +24 -0
- package/packages/types/runtime3d/Decals.d.ts +65 -0
- package/packages/types/runtime3d/DensityVolume.d.ts +39 -0
- package/packages/types/runtime3d/DistanceBricks.d.ts +97 -0
- package/packages/types/runtime3d/Dither.d.ts +78 -0
- package/packages/types/runtime3d/DrawWarmUp.d.ts +93 -0
- package/packages/types/runtime3d/EdgeSmoothing.d.ts +10 -0
- package/packages/types/runtime3d/EnvironmentProbe.d.ts +139 -0
- package/packages/types/runtime3d/Filmic.d.ts +243 -0
- package/packages/types/runtime3d/Foliage.d.ts +95 -0
- package/packages/types/runtime3d/GltfIntake.d.ts +236 -0
- package/packages/types/runtime3d/GltfSecondUv.d.ts +54 -0
- package/packages/types/runtime3d/GraphicsGuard.d.ts +18 -0
- package/packages/types/runtime3d/Grass.d.ts +226 -0
- package/packages/types/runtime3d/GroundTruthAO.d.ts +64 -0
- package/packages/types/runtime3d/HalfFloat.d.ts +13 -0
- package/packages/types/runtime3d/HdrEnvironment.d.ts +144 -0
- package/packages/types/runtime3d/Ik.d.ts +123 -0
- package/packages/types/runtime3d/InputBuffer.d.ts +49 -0
- package/packages/types/runtime3d/InstancedMesh.d.ts +116 -0
- package/packages/types/runtime3d/Laya342Adapters.d.ts +306 -0
- package/packages/types/runtime3d/Laya342GltfAdapter.d.ts +105 -0
- package/packages/types/runtime3d/LensFinish.d.ts +38 -0
- package/packages/types/runtime3d/LensFlare.d.ts +114 -0
- package/packages/types/runtime3d/LightFog.d.ts +190 -0
- package/packages/types/runtime3d/LightingDepth.d.ts +128 -0
- package/packages/types/runtime3d/Lightmap.d.ts +55 -0
- package/packages/types/runtime3d/Math3D.d.ts +19 -0
- package/packages/types/runtime3d/MeshQuery.d.ts +107 -0
- package/packages/types/runtime3d/MeshoptModelDecoder.d.ts +34 -0
- package/packages/types/runtime3d/MiniGameSplash.d.ts +4 -0
- package/packages/types/runtime3d/ModelAnimationSampler.d.ts +26 -0
- package/packages/types/runtime3d/ModelCompatibility.d.ts +169 -0
- package/packages/types/runtime3d/ModelDecoder.d.ts +66 -0
- package/packages/types/runtime3d/ModelInspector.d.ts +77 -0
- package/packages/types/runtime3d/ModelLod.d.ts +61 -0
- package/packages/types/runtime3d/ModelPlacements.d.ts +77 -0
- package/packages/types/runtime3d/ObjectMotion.d.ts +43 -0
- package/packages/types/runtime3d/PhysicalCamera.d.ts +51 -0
- package/packages/types/runtime3d/PointShadow.d.ts +71 -0
- package/packages/types/runtime3d/PointShadowSchedule.d.ts +74 -0
- package/packages/types/runtime3d/Pool.d.ts +33 -0
- package/packages/types/runtime3d/ProbeVolume.d.ts +123 -0
- package/packages/types/runtime3d/QualityGovernor.d.ts +201 -0
- package/packages/types/runtime3d/QualityMemory.d.ts +83 -0
- package/packages/types/runtime3d/RenderScale.d.ts +69 -0
- package/packages/types/runtime3d/RenderSpaces.d.ts +44 -0
- package/packages/types/runtime3d/Renderer.d.ts +62 -0
- package/packages/types/runtime3d/ResultPlayback.d.ts +70 -0
- package/packages/types/runtime3d/Runtime.d.ts +136 -0
- package/packages/types/runtime3d/RuntimeDriver.d.ts +42 -0
- package/packages/types/runtime3d/SceneLifecycle.d.ts +84 -0
- package/packages/types/runtime3d/SceneMutation.d.ts +34 -0
- package/packages/types/runtime3d/SceneQueries.d.ts +71 -0
- package/packages/types/runtime3d/ScreenReflections.d.ts +78 -0
- package/packages/types/runtime3d/SelectionOutline.d.ts +68 -0
- package/packages/types/runtime3d/ShaderErrors.d.ts +27 -0
- package/packages/types/runtime3d/ShaderRegistry.d.ts +10 -0
- package/packages/types/runtime3d/ShaderWarmUp.d.ts +162 -0
- package/packages/types/runtime3d/ShadowUpdates.d.ts +125 -0
- package/packages/types/runtime3d/SkinBinding.d.ts +53 -0
- package/packages/types/runtime3d/Smaa.d.ts +60 -0
- package/packages/types/runtime3d/SmaaTables.d.ts +12 -0
- package/packages/types/runtime3d/SpringBones.d.ts +69 -0
- package/packages/types/runtime3d/SurfaceBuffer.d.ts +28 -0
- package/packages/types/runtime3d/Surfaces.d.ts +326 -0
- package/packages/types/runtime3d/Themes.d.ts +70 -0
- package/packages/types/runtime3d/Timeline.d.ts +88 -0
- package/packages/types/runtime3d/ToneCurves.d.ts +59 -0
- package/packages/types/runtime3d/TransformGizmo.d.ts +139 -0
- package/packages/types/runtime3d/TriangleMask.d.ts +84 -0
- package/packages/types/runtime3d/Underwater.d.ts +120 -0
- package/packages/types/runtime3d/Utf8.d.ts +12 -0
- package/packages/types/runtime3d/Vrm.d.ts +120 -0
- package/packages/types/runtime3d/VrmDocument.d.ts +381 -0
- package/packages/types/runtime3d/WalkGrid.d.ts +94 -0
- package/packages/types/runtime3d/WebGPU342Adapters.d.ts +27 -0
- package/packages/types/runtime3d/index.d.ts +102 -0
- package/packages/types/shaders/Laya342ShaderTemplates.d.ts +3 -0
- package/packages/types/shaders/LitSurfaceMaterial.d.ts +257 -0
- package/packages/types/shaders/LitSurfaceTemplates.d.ts +7 -0
- package/packages/types/shaders/ReflectiveSurface.d.ts +58 -0
- package/packages/types/shaders/ShaderMaterials.d.ts +60 -0
- package/packages/types/shaders/ToonMaterial.d.ts +176 -0
- package/packages/types/shaders/WaterRipples.d.ts +48 -0
- package/packages/types/shaders/WaterSurface.d.ts +110 -0
- package/packages/types/shaders/ZhudaCommon.d.ts +31 -0
- package/packages/types/shaders/index.d.ts +7 -0
- package/packages/types/simulation/Cloth.d.ts +381 -0
- package/packages/types/simulation/ParticleCore.d.ts +125 -0
- package/packages/types/simulation/SpringBones.d.ts +107 -0
- package/packages/types/simulation/index.d.ts +4 -0
- package/packages/types/terrain/Heightfield.d.ts +67 -0
- package/packages/types/terrain/Terrain2D.d.ts +81 -0
- package/packages/types/terrain/Terrain3D.d.ts +80 -0
- package/packages/types/terrain/TerrainShell.d.ts +8 -0
- package/packages/types/terrain/index.d.ts +4 -0
- package/packages/types/vendor/LayaAir.runtime.d.ts +97440 -0
- package/packages/types/vendor/REPAIRS.md +30 -0
- package/packages/types/vendor/restored-3.4.2.json +142 -0
- package/packages/types/vendor/spine.runtime.d.ts +1507 -0
- package/packages/types/vendor/wechat-media.d.ts +877 -0
- package/packages/types/zhuda-2d-ui.d.ts +244 -0
- package/packages/types/zhuda-3d-physics.d.ts +34 -0
- package/packages/types/zhuda-audio.d.ts +128 -0
- package/packages/types/zhuda-bootstrap.d.ts +100 -0
- package/packages/types/zhuda-branding.d.ts +6 -0
- package/packages/types/zhuda-core.d.ts +46 -0
- package/packages/types/zhuda-declarative.d.ts +81 -0
- package/packages/types/zhuda-effects.d.ts +302 -0
- package/packages/types/zhuda-layout.d.ts +96 -0
- package/packages/types/zhuda-particles.d.ts +477 -0
- package/packages/types/zhuda-spine42.d.ts +23 -0
- package/packages/types/zhuda-static-assets.d.ts +389 -0
- package/packages/types/zhuda-video.d.ts +24 -0
- package/packages/types/zhuda-visual-contract.d.ts +52 -0
- package/packages/types/zhuda-webview.d.ts +43 -0
- package/vendor/basis/LICENSE.txt +55 -0
- package/vendor/basis/README.md +25 -0
- package/vendor/basis/basis_transcoder.js +19 -0
- package/vendor/basis/basis_transcoder.wasm +0 -0
- package/vendor/laya-3.4.2/WEBGPU-LICENSES.txt +1259 -0
- package/vendor/laya-3.4.2/libs/laya.ani.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.box2D.js +1209 -0
- package/vendor/laya-3.4.2/libs/laya.bridge.js +2273 -0
- package/vendor/laya-3.4.2/libs/laya.bullet.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.core.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.d3.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.device.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.gltf.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.ik.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.light2D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.line2D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.native-spine42.js +7672 -0
- package/vendor/laya-3.4.2/libs/laya.navMesh2d.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.navMesh3d.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.navMeshCommon.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.particle.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.particle3D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.particleCommon.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.physics2D.js +3774 -0
- package/vendor/laya-3.4.2/libs/laya.physics3D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.postProcess.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.spine.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.spine3D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.tilemap.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.trail2D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.trail3D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.trailCommon.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.ui.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.ui2.js +9904 -0
- package/vendor/laya-3.4.2/libs/laya.vfx.js +6754 -0
- package/vendor/laya-3.4.2/libs/laya.webgl_2D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.webgl_3D.js +1 -0
- package/vendor/laya-3.4.2/libs/laya.webgpu_2D.js +18576 -0
- package/vendor/laya-3.4.2/libs/laya.webgpu_3D.js +6729 -0
- package/vendor/laya-3.4.2/libs/nagabind.js +395 -0
- package/vendor/laya-3.4.2/libs/nagabind_bg.wasm +0 -0
- package/vendor/laya-3.4.2/libs/shader_compiler_web.js +22 -0
- package/vendor/laya-3.4.2/libs/shader_compiler_web.wasm +0 -0
- package/vendor/laya-3.4.2/libs/spine-core-3.8.js +1 -0
- package/vendor/laya-3.4.2/libs/spine-core-4.2.js +10216 -0
- package/vendor/laya-3.4.2/webgpu-provenance.json +41 -0
- package/vendor/meshoptimizer/LICENSE.txt +21 -0
- package/vendor/meshoptimizer/README.md +13 -0
- package/vendor/threejs-post/LICENSE.txt +53 -0
- package/vendor/threejs-post/README.md +54 -0
- package/zhuda.config.json +22 -0
|
@@ -0,0 +1,1824 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single WebAudio authority for embedded games.
|
|
3
|
+
*
|
|
4
|
+
* The adapter owns context creation, the master/channel mixer, autoplay
|
|
5
|
+
* unlocking, bridge security and every voice's lifetime. Consumers submit
|
|
6
|
+
* logical events through scheduleTone; they must not create another
|
|
7
|
+
* AudioContext for the same event.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type {
|
|
11
|
+
AudioVoiceHandle,
|
|
12
|
+
IframeAudioChannel,
|
|
13
|
+
IframeSoundAdapterOptions,
|
|
14
|
+
IframeSoundAdapterDiagnostics,
|
|
15
|
+
IframeSoundDiagnostics,
|
|
16
|
+
IframeToneOptions,
|
|
17
|
+
IframeSampleOptions,
|
|
18
|
+
IframeSampleInfo,
|
|
19
|
+
} from '../types/index.ts';
|
|
20
|
+
|
|
21
|
+
import { createProviderAssetCache, normalizeAssetId } from './runtime3d/AssetProvider.ts';
|
|
22
|
+
import type { AssetStreamLease } from './runtime3d/AssetProvider.ts';
|
|
23
|
+
import { ZhudaAssetCache, type AssetLease } from './runtime3d/Assets.ts';
|
|
24
|
+
import type {
|
|
25
|
+
IframeVoiceOptions,
|
|
26
|
+
IframeVoiceEvent,
|
|
27
|
+
IframeStreamOptions,
|
|
28
|
+
IframeStreamInfo,
|
|
29
|
+
IframeSampleBackend,
|
|
30
|
+
IframeBackendVoice,
|
|
31
|
+
} from '../types/zhuda-audio.ts';
|
|
32
|
+
import { StreamVoice } from './audio/StreamVoice.ts';
|
|
33
|
+
import { renderOfflineMix } from './audio/OfflineMix.ts';
|
|
34
|
+
import { awaitAbortable } from './runtime3d/AsyncOperation.ts';
|
|
35
|
+
import type { IframeOfflineMixOptions, IframeOfflineMix } from '../types/zhuda-audio.ts';
|
|
36
|
+
import type { IframeListenerPose } from '../types/zhuda-audio.ts';
|
|
37
|
+
import {
|
|
38
|
+
DEFAULT_LISTENER,
|
|
39
|
+
fallbackPlacement,
|
|
40
|
+
placeListener,
|
|
41
|
+
placePanner,
|
|
42
|
+
resolveListener,
|
|
43
|
+
resolvePosition,
|
|
44
|
+
resolveRamp,
|
|
45
|
+
resolveSpatial,
|
|
46
|
+
setParam,
|
|
47
|
+
type ResolvedListener,
|
|
48
|
+
type ResolvedSpatial,
|
|
49
|
+
} from './audio/Spatial.ts';
|
|
50
|
+
|
|
51
|
+
export interface QueuedAudioTask {
|
|
52
|
+
sampleId?: string;
|
|
53
|
+
streamId?: string;
|
|
54
|
+
id: string;
|
|
55
|
+
channel: IframeAudioChannel;
|
|
56
|
+
createdAt: number;
|
|
57
|
+
execute: () => boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type Cleanup = () => void;
|
|
61
|
+
/** A voice's place in the world: a PannerNode, or the gain (and stereo pan) fallback. */
|
|
62
|
+
interface SpatialState {
|
|
63
|
+
options: ResolvedSpatial;
|
|
64
|
+
input: AudioNode;
|
|
65
|
+
output: AudioNode;
|
|
66
|
+
nodes: AudioNode[];
|
|
67
|
+
panner?: PannerNode;
|
|
68
|
+
gain?: GainNode;
|
|
69
|
+
stereo?: StereoPannerNode;
|
|
70
|
+
}
|
|
71
|
+
type VoiceState = IframeVoiceOptions & {
|
|
72
|
+
logicalId: string;
|
|
73
|
+
channel: IframeAudioChannel;
|
|
74
|
+
source: AudioScheduledSourceNode | IframeBackendVoice;
|
|
75
|
+
gain?: GainNode;
|
|
76
|
+
spatial?: SpatialState;
|
|
77
|
+
sampleId?: string;
|
|
78
|
+
streamId?: string;
|
|
79
|
+
stopping?: boolean;
|
|
80
|
+
stopped: boolean;
|
|
81
|
+
/** Sample voices: context time it started at, where in the sample, and its loop. */
|
|
82
|
+
startedAt?: number;
|
|
83
|
+
startOffset?: number;
|
|
84
|
+
loopRange?: readonly [number, number];
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const CHANNELS: readonly IframeAudioChannel[] = ['bgm', 'sfx', 'ui'];
|
|
88
|
+
const AUDIO_WAVE_TYPES: readonly OscillatorType[] = ['sine', 'square', 'sawtooth', 'triangle'];
|
|
89
|
+
const CONTEXT_STATES = new Set(['suspended', 'running', 'closed']);
|
|
90
|
+
|
|
91
|
+
function isAudioChannel(value: unknown): value is IframeAudioChannel {
|
|
92
|
+
return value === 'master' || value === 'bgm' || value === 'sfx' || value === 'ui';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isFiniteNumber(value: unknown): value is number {
|
|
96
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class IframeSoundAdapter {
|
|
100
|
+
private static instance: IframeSoundAdapter | null = null;
|
|
101
|
+
|
|
102
|
+
private readonly options: Required<
|
|
103
|
+
Pick<
|
|
104
|
+
IframeSoundAdapterOptions,
|
|
105
|
+
'queueMaxAgeMs' | 'maxPendingQueue' | 'maxActiveVoices' | 'syncLayaSoundManager'
|
|
106
|
+
>
|
|
107
|
+
> &
|
|
108
|
+
IframeSoundAdapterOptions;
|
|
109
|
+
private readonly allowedParentOrigins: ReadonlySet<string>;
|
|
110
|
+
private readonly now: () => number;
|
|
111
|
+
private readonly cleanupFns: Cleanup[] = [];
|
|
112
|
+
private readonly gestureCleanupFns: Cleanup[] = [];
|
|
113
|
+
|
|
114
|
+
private ctx: AudioContext | null = null;
|
|
115
|
+
private masterGain: GainNode | null = null;
|
|
116
|
+
private channelGains: Partial<Record<IframeAudioChannel, GainNode>> = {};
|
|
117
|
+
|
|
118
|
+
private inIframe = false;
|
|
119
|
+
private unlockedByGesture = false;
|
|
120
|
+
private unlockGestureType = 'none';
|
|
121
|
+
private pageVisible = true;
|
|
122
|
+
private windowFocused = true;
|
|
123
|
+
private autoSuspendedByBlur = false;
|
|
124
|
+
private userMuted = false;
|
|
125
|
+
private postMessageBridgeActive = false;
|
|
126
|
+
private lastBridgeCommand = 'init';
|
|
127
|
+
private lastError: string | null = null;
|
|
128
|
+
private disposed = false;
|
|
129
|
+
private unlockAttempt = 0;
|
|
130
|
+
|
|
131
|
+
private volumes: Record<IframeAudioChannel, number> = {
|
|
132
|
+
master: 0.85,
|
|
133
|
+
bgm: 0.6,
|
|
134
|
+
sfx: 0.9,
|
|
135
|
+
ui: 0.85,
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
private pendingQueue: QueuedAudioTask[] = [];
|
|
139
|
+
private queuedBeforeUnlockCount = 0;
|
|
140
|
+
private droppedQueue = 0;
|
|
141
|
+
private activeVoices = new Map<string, VoiceState>();
|
|
142
|
+
private droppedVoices = 0;
|
|
143
|
+
private playedEventsCount = 0;
|
|
144
|
+
private voiceSerial = 0;
|
|
145
|
+
private sampleCache?: ZhudaAssetCache<AudioBuffer>;
|
|
146
|
+
private readonly samples = new Map<string, AssetLease<AudioBuffer>>();
|
|
147
|
+
private readonly sampleLoads = new Map<AbortController, string>();
|
|
148
|
+
private readonly sampleTimeoutMs: number;
|
|
149
|
+
private readonly maxSamples: number;
|
|
150
|
+
private readonly maxDecodedSampleBytes: number;
|
|
151
|
+
private readonly maxRetainedStreamBytes: number;
|
|
152
|
+
private streamCache?: ZhudaAssetCache<AssetStreamLease>;
|
|
153
|
+
private readonly streams = new Map<string, AssetLease<AssetStreamLease>>();
|
|
154
|
+
private readonly streamLoads = new Map<AbortController, string>();
|
|
155
|
+
private readonly admissions = new Map<string, Omit<QueuedAudioTask, 'createdAt'>>();
|
|
156
|
+
private retiredVoices = 0;
|
|
157
|
+
private sampleBackend?: IframeSampleBackend;
|
|
158
|
+
private backendPreparing?: AbortController;
|
|
159
|
+
private backendContextLost = false;
|
|
160
|
+
private offlineMix: AbortController | null = null;
|
|
161
|
+
private listener: ResolvedListener = DEFAULT_LISTENER;
|
|
162
|
+
|
|
163
|
+
public static getShared(): IframeSoundAdapter {
|
|
164
|
+
if (!this.instance || this.instance.disposed) {
|
|
165
|
+
this.instance = new IframeSoundAdapter();
|
|
166
|
+
}
|
|
167
|
+
return this.instance;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
constructor(options: IframeSoundAdapterOptions = {}) {
|
|
171
|
+
this.options = {
|
|
172
|
+
...options,
|
|
173
|
+
queueMaxAgeMs: options.queueMaxAgeMs ?? 500,
|
|
174
|
+
maxPendingQueue: options.maxPendingQueue ?? 32,
|
|
175
|
+
maxActiveVoices: options.maxActiveVoices ?? 32,
|
|
176
|
+
syncLayaSoundManager: options.syncLayaSoundManager ?? false,
|
|
177
|
+
};
|
|
178
|
+
this.sampleTimeoutMs = options.sampleTimeoutMs ?? 15_000;
|
|
179
|
+
this.maxSamples = options.maxSamples ?? 32;
|
|
180
|
+
this.maxRetainedStreamBytes = options.maxRetainedStreamBytes ?? 64 * 1024 * 1024;
|
|
181
|
+
this.maxDecodedSampleBytes = options.maxDecodedSampleBytes ?? 64 * 1024 * 1024;
|
|
182
|
+
if (!['reject', 'fifo', 'priority'].includes(options.voiceOverflow ?? 'reject'))
|
|
183
|
+
throw Error('Invalid voice overflow');
|
|
184
|
+
if (
|
|
185
|
+
!Number.isFinite(options.retireFadeSec ?? 0.005) ||
|
|
186
|
+
(options.retireFadeSec ?? 0.005) < 0 ||
|
|
187
|
+
(options.retireFadeSec ?? 0.005) > 1
|
|
188
|
+
)
|
|
189
|
+
throw Error('Invalid retirement fade');
|
|
190
|
+
if (options.protectedChannels?.some((channel) => !isAudioChannel(channel)))
|
|
191
|
+
throw Error('Invalid protected channel');
|
|
192
|
+
const streamProvider = options.streamProvider ?? options.sampleProvider;
|
|
193
|
+
if (streamProvider?.openStream)
|
|
194
|
+
this.streamCache = new ZhudaAssetCache(
|
|
195
|
+
async (id, signal) => {
|
|
196
|
+
const lease = await streamProvider.openStream!(id, { signal });
|
|
197
|
+
if (signal.aborted || this.disposed) {
|
|
198
|
+
lease.release();
|
|
199
|
+
throw new DOMException('Stream load cancelled', 'AbortError');
|
|
200
|
+
}
|
|
201
|
+
if (
|
|
202
|
+
lease.id !== id ||
|
|
203
|
+
!lease.url ||
|
|
204
|
+
!['native', 'verified-blob'].includes(lease.delivery) ||
|
|
205
|
+
!['sha256', 'transport'].includes(lease.integrity) ||
|
|
206
|
+
!Number.isSafeInteger(lease.retainedBytes) ||
|
|
207
|
+
lease.retainedBytes < 0
|
|
208
|
+
) {
|
|
209
|
+
lease.release();
|
|
210
|
+
throw Error('Invalid stream lease');
|
|
211
|
+
}
|
|
212
|
+
return lease;
|
|
213
|
+
},
|
|
214
|
+
(lease) => lease.release(),
|
|
215
|
+
0,
|
|
216
|
+
);
|
|
217
|
+
for (const [name, value] of Object.entries({
|
|
218
|
+
sampleTimeoutMs: this.sampleTimeoutMs,
|
|
219
|
+
maxSamples: this.maxSamples,
|
|
220
|
+
maxRetainedStreamBytes: this.maxRetainedStreamBytes,
|
|
221
|
+
maxDecodedSampleBytes: this.maxDecodedSampleBytes,
|
|
222
|
+
maxActiveVoices: this.options.maxActiveVoices,
|
|
223
|
+
maxPendingQueue: this.options.maxPendingQueue,
|
|
224
|
+
queueMaxAgeMs: this.options.queueMaxAgeMs,
|
|
225
|
+
}))
|
|
226
|
+
if (!Number.isSafeInteger(value) || value <= 0) throw Error(`Invalid audio limit: ${name}`);
|
|
227
|
+
if (options.sampleProvider)
|
|
228
|
+
this.sampleCache = createProviderAssetCache(
|
|
229
|
+
options.sampleProvider,
|
|
230
|
+
async (asset, signal) => {
|
|
231
|
+
const context = this.ensureAudioContext();
|
|
232
|
+
if (!context) throw Error('WebAudio decoder unavailable');
|
|
233
|
+
if (signal.aborted) throw new DOMException('Sample decode cancelled', 'AbortError');
|
|
234
|
+
let cancel: () => void = () => {};
|
|
235
|
+
try {
|
|
236
|
+
const decoded = await Promise.race([
|
|
237
|
+
context.decodeAudioData(new Uint8Array(asset.bytes).buffer),
|
|
238
|
+
new Promise<never>((_, reject) => {
|
|
239
|
+
cancel = () => reject(new DOMException('Sample decode cancelled', 'AbortError'));
|
|
240
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
241
|
+
if (signal.aborted) cancel();
|
|
242
|
+
}),
|
|
243
|
+
]);
|
|
244
|
+
if (signal.aborted || this.disposed)
|
|
245
|
+
throw new DOMException('Sample decode cancelled', 'AbortError');
|
|
246
|
+
const bytes = decoded.length * decoded.numberOfChannels * 4;
|
|
247
|
+
if (
|
|
248
|
+
!Number.isSafeInteger(bytes) ||
|
|
249
|
+
bytes <= 0 ||
|
|
250
|
+
bytes > this.maxDecodedSampleBytes ||
|
|
251
|
+
!Number.isFinite(decoded.duration) ||
|
|
252
|
+
decoded.duration <= 0
|
|
253
|
+
)
|
|
254
|
+
throw Error('Decoded sample exceeds PCM bound or is empty');
|
|
255
|
+
return decoded;
|
|
256
|
+
} finally {
|
|
257
|
+
signal.removeEventListener('abort', cancel);
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
() => {},
|
|
261
|
+
);
|
|
262
|
+
this.allowedParentOrigins = new Set(
|
|
263
|
+
(options.allowedParentOrigins ?? []).filter(
|
|
264
|
+
(origin): origin is string =>
|
|
265
|
+
typeof origin === 'string' && origin.length > 0 && origin !== '*',
|
|
266
|
+
),
|
|
267
|
+
);
|
|
268
|
+
this.now = options.now ?? (() => Date.now());
|
|
269
|
+
|
|
270
|
+
this.detectIframeContext();
|
|
271
|
+
this.installGestureUnlockGuards();
|
|
272
|
+
this.installVisibilityAndFocusGuards();
|
|
273
|
+
this.installPostMessageBridge();
|
|
274
|
+
this.syncLayaSoundManager();
|
|
275
|
+
this.syncDomTelemetry();
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private recordError(error: unknown): void {
|
|
279
|
+
this.lastError = error instanceof Error ? error.message : String(error);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private voiceEvent(event: IframeVoiceEvent): void {
|
|
283
|
+
try {
|
|
284
|
+
this.options.onVoiceEvent?.(event);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
this.recordError(error);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
private validVoice(options: IframeVoiceOptions): boolean {
|
|
291
|
+
return (
|
|
292
|
+
(options.priority === undefined || Number.isFinite(options.priority)) &&
|
|
293
|
+
(options.protected === undefined || typeof options.protected === 'boolean')
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private admit(
|
|
298
|
+
options: IframeVoiceOptions,
|
|
299
|
+
task: Omit<QueuedAudioTask, 'createdAt'>,
|
|
300
|
+
exclude: readonly string[] = [],
|
|
301
|
+
): 'ready' | 'queued' | 'rejected' {
|
|
302
|
+
if (this.activeVoices.size < this.options.maxActiveVoices) return 'ready';
|
|
303
|
+
const mode = this.options.voiceOverflow ?? 'reject';
|
|
304
|
+
const protectedChannels = this.options.protectedChannels ?? ['bgm'];
|
|
305
|
+
const candidates = [...this.activeVoices].filter(
|
|
306
|
+
([key, voice]) =>
|
|
307
|
+
!exclude.includes(key) &&
|
|
308
|
+
!voice.stopping &&
|
|
309
|
+
!this.admissions.has(key) &&
|
|
310
|
+
!voice.protected &&
|
|
311
|
+
!protectedChannels.includes(voice.channel) &&
|
|
312
|
+
(mode !== 'priority' || (voice.priority ?? 0) <= (options.priority ?? 0)),
|
|
313
|
+
);
|
|
314
|
+
if (mode === 'priority') candidates.sort((a, b) => (a[1].priority ?? 0) - (b[1].priority ?? 0));
|
|
315
|
+
const victim = candidates[0];
|
|
316
|
+
if (mode === 'reject' || !victim || this.admissions.size >= this.options.maxPendingQueue) {
|
|
317
|
+
this.droppedVoices++;
|
|
318
|
+
this.voiceEvent({
|
|
319
|
+
type: 'rejected',
|
|
320
|
+
id: task.id,
|
|
321
|
+
channel: task.channel,
|
|
322
|
+
reason: 'voice-capacity',
|
|
323
|
+
});
|
|
324
|
+
this.syncDomTelemetry();
|
|
325
|
+
return 'rejected';
|
|
326
|
+
}
|
|
327
|
+
this.admissions.set(victim[0], task);
|
|
328
|
+
this.retiredVoices++;
|
|
329
|
+
this.voiceEvent({
|
|
330
|
+
type: 'retiring',
|
|
331
|
+
id: victim[1].logicalId,
|
|
332
|
+
channel: victim[1].channel,
|
|
333
|
+
replacedBy: task.id,
|
|
334
|
+
reason: mode,
|
|
335
|
+
});
|
|
336
|
+
this.stopVoice(victim[0], this.options.retireFadeSec ?? 0.005);
|
|
337
|
+
this.syncDomTelemetry();
|
|
338
|
+
return 'queued';
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private detectIframeContext(): void {
|
|
342
|
+
if (typeof window === 'undefined') {
|
|
343
|
+
this.inIframe = false;
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
this.inIframe = window.self !== window.top;
|
|
348
|
+
} catch (_crossOriginErr) {
|
|
349
|
+
this.inIframe = true;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private defaultAudioContextFactory(): AudioContext | null {
|
|
354
|
+
if (typeof window === 'undefined') return null;
|
|
355
|
+
const AudioCtx =
|
|
356
|
+
window.AudioContext ||
|
|
357
|
+
(window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
|
358
|
+
if (!AudioCtx) return null;
|
|
359
|
+
return new AudioCtx();
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private ensureAudioContext(recreateClosed = true): AudioContext | null {
|
|
363
|
+
if (this.disposed || this.backendContextLost) return null;
|
|
364
|
+
if (this.ctx && this.ctx.state !== 'closed') return this.ctx;
|
|
365
|
+
if (this.ctx?.state === 'closed') {
|
|
366
|
+
this.recordError('AudioContext is closed');
|
|
367
|
+
this.unlockedByGesture = false;
|
|
368
|
+
for (const key of [...this.activeVoices.keys()]) this.finishVoice(key);
|
|
369
|
+
if (this.sampleBackend) {
|
|
370
|
+
this.backendContextLost = true;
|
|
371
|
+
try {
|
|
372
|
+
this.sampleBackend.dispose();
|
|
373
|
+
} catch (error) {
|
|
374
|
+
this.recordError(error);
|
|
375
|
+
}
|
|
376
|
+
this.recordError('Sample backend context closed; dispose and recreate the adapter');
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
this.ctx = null;
|
|
380
|
+
this.masterGain = null;
|
|
381
|
+
this.channelGains = {};
|
|
382
|
+
// A new context must be resumed from a fresh user gesture. Callers that
|
|
383
|
+
// are already inside playback must not recreate it behind the gesture.
|
|
384
|
+
if (!recreateClosed) return null;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
let context: AudioContext | null = null;
|
|
388
|
+
try {
|
|
389
|
+
context = this.options.audioContextFactory
|
|
390
|
+
? this.options.audioContextFactory()
|
|
391
|
+
: this.defaultAudioContextFactory();
|
|
392
|
+
if (!context) return null;
|
|
393
|
+
this.ctx = context;
|
|
394
|
+
this.masterGain = context.createGain();
|
|
395
|
+
this.masterGain.gain.value = this.getEffectiveMasterVolume();
|
|
396
|
+
this.masterGain.connect(context.destination);
|
|
397
|
+
this.channelGains = {};
|
|
398
|
+
for (const channel of CHANNELS) {
|
|
399
|
+
const gain = context.createGain();
|
|
400
|
+
gain.gain.value = this.volumes[channel];
|
|
401
|
+
gain.connect(this.masterGain);
|
|
402
|
+
this.channelGains[channel] = gain;
|
|
403
|
+
}
|
|
404
|
+
this.applyListener(context, 0);
|
|
405
|
+
return context;
|
|
406
|
+
} catch (error) {
|
|
407
|
+
this.recordError(error);
|
|
408
|
+
try {
|
|
409
|
+
if (context && context.state !== 'closed') void context.close();
|
|
410
|
+
} catch (_closeError) {
|
|
411
|
+
// Keep the original construction error as the actionable diagnostic.
|
|
412
|
+
}
|
|
413
|
+
this.ctx = null;
|
|
414
|
+
this.masterGain = null;
|
|
415
|
+
this.channelGains = {};
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private getEffectiveMasterVolume(): number {
|
|
421
|
+
return this.userMuted || this.autoSuspendedByBlur ? 0 : this.volumes.master;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private setGainValue(node: GainNode, value: number): void {
|
|
425
|
+
if (!this.ctx) return;
|
|
426
|
+
try {
|
|
427
|
+
node.gain.setValueAtTime(value, this.ctx.currentTime);
|
|
428
|
+
} catch (_error) {
|
|
429
|
+
node.gain.value = value;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private updateGainNodes(): void {
|
|
434
|
+
if (this.masterGain) this.setGainValue(this.masterGain, this.getEffectiveMasterVolume());
|
|
435
|
+
for (const channel of CHANNELS) {
|
|
436
|
+
const node = this.channelGains[channel];
|
|
437
|
+
if (node) this.setGainValue(node, this.volumes[channel]);
|
|
438
|
+
}
|
|
439
|
+
this.syncLayaSoundManager();
|
|
440
|
+
this.syncStreamFocus();
|
|
441
|
+
this.syncDomTelemetry();
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
private syncStreamFocus(): void {
|
|
445
|
+
const paused =
|
|
446
|
+
this.autoSuspendedByBlur || !this.unlockedByGesture || this.ctx?.state !== 'running';
|
|
447
|
+
for (const voice of this.activeVoices.values())
|
|
448
|
+
if (voice.source instanceof StreamVoice) voice.source.setPaused(paused);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Optional state mirroring for consumers that explicitly still use Laya SoundManager. */
|
|
452
|
+
private syncLayaSoundManager(): void {
|
|
453
|
+
if (!this.options.syncLayaSoundManager) return;
|
|
454
|
+
const g = globalThis as unknown as {
|
|
455
|
+
Laya?: {
|
|
456
|
+
SoundManager?: {
|
|
457
|
+
muted?: boolean;
|
|
458
|
+
autoStopMusic?: boolean;
|
|
459
|
+
setMusicVolume?: (volume: number) => void;
|
|
460
|
+
setSoundVolume?: (volume: number) => void;
|
|
461
|
+
};
|
|
462
|
+
};
|
|
463
|
+
};
|
|
464
|
+
const soundManager = g.Laya?.SoundManager;
|
|
465
|
+
if (!soundManager) return;
|
|
466
|
+
soundManager.muted = this.userMuted || this.autoSuspendedByBlur;
|
|
467
|
+
soundManager.autoStopMusic = true;
|
|
468
|
+
soundManager.setMusicVolume?.(Number((this.volumes.master * this.volumes.bgm).toFixed(2)));
|
|
469
|
+
soundManager.setSoundVolume?.(Number((this.volumes.master * this.volumes.sfx).toFixed(2)));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private addEventListener(
|
|
473
|
+
target: EventTarget,
|
|
474
|
+
type: string,
|
|
475
|
+
listener: EventListener,
|
|
476
|
+
options?: AddEventListenerOptions,
|
|
477
|
+
gesture = false,
|
|
478
|
+
): void {
|
|
479
|
+
target.addEventListener(type, listener, options);
|
|
480
|
+
const cleanup = () => target.removeEventListener(type, listener, options);
|
|
481
|
+
this.cleanupFns.push(cleanup);
|
|
482
|
+
if (gesture) this.gestureCleanupFns.push(cleanup);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private removeGestureUnlockGuards(): void {
|
|
486
|
+
for (const cleanup of this.gestureCleanupFns.splice(0)) {
|
|
487
|
+
cleanup();
|
|
488
|
+
const index = this.cleanupFns.indexOf(cleanup);
|
|
489
|
+
if (index >= 0) this.cleanupFns.splice(index, 1);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
private installGestureUnlockGuards(): void {
|
|
494
|
+
if (typeof window === 'undefined') return;
|
|
495
|
+
const events = ['pointerdown', 'touchstart', 'mousedown', 'keydown'];
|
|
496
|
+
const onFirstGesture: EventListener = (event) => {
|
|
497
|
+
this.unlockAudio(event.type || 'gesture');
|
|
498
|
+
if (this.unlockedByGesture) this.removeGestureUnlockGuards();
|
|
499
|
+
};
|
|
500
|
+
for (const event of events) {
|
|
501
|
+
this.addEventListener(window, event, onFirstGesture, { capture: true, passive: true }, true);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private markUnlocked(gestureSource: string): void {
|
|
506
|
+
this.unlockedByGesture = true;
|
|
507
|
+
this.unlockGestureType = gestureSource;
|
|
508
|
+
this.playSilentUnlockSample();
|
|
509
|
+
this.flushPendingQueue();
|
|
510
|
+
this.syncStreamFocus();
|
|
511
|
+
this.syncDomTelemetry();
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
private playSilentUnlockSample(): void {
|
|
515
|
+
if (!this.ctx) return;
|
|
516
|
+
try {
|
|
517
|
+
const silentBuffer = this.ctx.createBuffer(1, 1, 22050);
|
|
518
|
+
const source = this.ctx.createBufferSource();
|
|
519
|
+
source.buffer = silentBuffer;
|
|
520
|
+
source.onended = () => source.disconnect?.();
|
|
521
|
+
source.connect(this.ctx.destination);
|
|
522
|
+
source.start(0);
|
|
523
|
+
} catch (error) {
|
|
524
|
+
this.recordError(error);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Unlocks only after a real context exists and resume succeeds or is already running. */
|
|
529
|
+
public unlockAudio(gestureSource = 'programmatic-unlock'): boolean {
|
|
530
|
+
if (this.disposed) return false;
|
|
531
|
+
// Record the attempted source separately from unlockedByGesture. A headless
|
|
532
|
+
// or blocked context may receive a gesture without becoming playable.
|
|
533
|
+
this.unlockGestureType = gestureSource;
|
|
534
|
+
const context = this.ensureAudioContext();
|
|
535
|
+
if (!context) {
|
|
536
|
+
this.recordError('WebAudio is unavailable');
|
|
537
|
+
this.syncDomTelemetry();
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const attempt = ++this.unlockAttempt;
|
|
542
|
+
if (context.state === 'running') {
|
|
543
|
+
this.markUnlocked(gestureSource);
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
if (context.state !== 'suspended' || typeof context.resume !== 'function') {
|
|
547
|
+
this.recordError(`AudioContext cannot resume from ${context.state}`);
|
|
548
|
+
this.syncDomTelemetry();
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
try {
|
|
553
|
+
const result = context.resume();
|
|
554
|
+
Promise.resolve(result).then(
|
|
555
|
+
() => {
|
|
556
|
+
if (this.disposed || attempt !== this.unlockAttempt || this.ctx !== context) return;
|
|
557
|
+
if (context.state === 'running') {
|
|
558
|
+
this.markUnlocked(gestureSource);
|
|
559
|
+
this.removeGestureUnlockGuards();
|
|
560
|
+
} else {
|
|
561
|
+
this.recordError(`AudioContext resume ended in ${context.state}`);
|
|
562
|
+
this.unlockedByGesture = false;
|
|
563
|
+
this.syncDomTelemetry();
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
(error) => {
|
|
567
|
+
if (this.disposed || attempt !== this.unlockAttempt) return;
|
|
568
|
+
this.unlockedByGesture = false;
|
|
569
|
+
this.recordError(error);
|
|
570
|
+
this.syncDomTelemetry();
|
|
571
|
+
},
|
|
572
|
+
);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
this.unlockedByGesture = false;
|
|
575
|
+
this.recordError(error);
|
|
576
|
+
this.syncDomTelemetry();
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
this.syncDomTelemetry();
|
|
580
|
+
return this.unlockedByGesture;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
private flushPendingQueue(): void {
|
|
584
|
+
if (!this.unlockedByGesture) return;
|
|
585
|
+
if (this.userMuted || this.autoSuspendedByBlur) {
|
|
586
|
+
this.pendingQueue = [];
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const now = this.now();
|
|
590
|
+
const tasks = this.pendingQueue.splice(0);
|
|
591
|
+
for (const task of tasks) {
|
|
592
|
+
if (now - task.createdAt > this.options.queueMaxAgeMs) {
|
|
593
|
+
this.droppedQueue++;
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
try {
|
|
597
|
+
if (!task.execute()) this.droppedQueue++;
|
|
598
|
+
} catch (error) {
|
|
599
|
+
this.droppedQueue++;
|
|
600
|
+
this.recordError(error);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
this.syncDomTelemetry();
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
private installVisibilityAndFocusGuards(): void {
|
|
607
|
+
if (typeof window === 'undefined' || typeof document === 'undefined') return;
|
|
608
|
+
|
|
609
|
+
this.addEventListener(document, 'visibilitychange', () => {
|
|
610
|
+
this.handleFocusOrVisibilityChange(document.visibilityState !== 'hidden', this.windowFocused);
|
|
611
|
+
});
|
|
612
|
+
// A phone sends `blur` when its address bar, keyboard or a system sheet
|
|
613
|
+
// takes focus, and often never sends `focus` back: the music would stay
|
|
614
|
+
// silent on a visible page. There, leaving the page is told by visibility
|
|
615
|
+
// and pagehide alone; a desktop window still goes quiet on blur. Input on
|
|
616
|
+
// a visible page means the player is here, whatever focus said.
|
|
617
|
+
const media = (query: string) =>
|
|
618
|
+
typeof globalThis.matchMedia === 'function' && globalThis.matchMedia(query).matches;
|
|
619
|
+
const touchOnly = media('(pointer: coarse)') && !media('(pointer: fine)');
|
|
620
|
+
this.addEventListener(window, 'blur', () => {
|
|
621
|
+
if (!touchOnly) this.handleFocusOrVisibilityChange(this.pageVisible, false);
|
|
622
|
+
});
|
|
623
|
+
this.addEventListener(window, 'focus', () => {
|
|
624
|
+
this.handleFocusOrVisibilityChange(true, true);
|
|
625
|
+
});
|
|
626
|
+
const back = () => {
|
|
627
|
+
if (!this.windowFocused && document.visibilityState !== 'hidden')
|
|
628
|
+
this.handleFocusOrVisibilityChange(true, true);
|
|
629
|
+
};
|
|
630
|
+
this.addEventListener(window, 'pointerdown', back, { capture: true });
|
|
631
|
+
this.addEventListener(window, 'keydown', back, { capture: true });
|
|
632
|
+
this.addEventListener(window, 'pagehide', () => {
|
|
633
|
+
this.handleFocusOrVisibilityChange(false, false);
|
|
634
|
+
});
|
|
635
|
+
this.addEventListener(window, 'pageshow', () => {
|
|
636
|
+
this.handleFocusOrVisibilityChange(true, true);
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
public handleFocusOrVisibilityChange(visible: boolean, focused: boolean): void {
|
|
641
|
+
if (this.disposed) return;
|
|
642
|
+
this.pageVisible = Boolean(visible);
|
|
643
|
+
this.windowFocused = Boolean(focused);
|
|
644
|
+
this.autoSuspendedByBlur = !this.pageVisible || !this.windowFocused;
|
|
645
|
+
|
|
646
|
+
if (this.ctx) {
|
|
647
|
+
if (
|
|
648
|
+
this.autoSuspendedByBlur &&
|
|
649
|
+
this.ctx.state === 'running' &&
|
|
650
|
+
typeof this.ctx.suspend === 'function'
|
|
651
|
+
) {
|
|
652
|
+
try {
|
|
653
|
+
Promise.resolve(this.ctx.suspend()).catch((error) => this.recordError(error));
|
|
654
|
+
} catch (error) {
|
|
655
|
+
this.recordError(error);
|
|
656
|
+
}
|
|
657
|
+
} else if (
|
|
658
|
+
!this.autoSuspendedByBlur &&
|
|
659
|
+
!this.userMuted &&
|
|
660
|
+
this.unlockedByGesture &&
|
|
661
|
+
this.ctx.state === 'suspended' &&
|
|
662
|
+
typeof this.ctx.resume === 'function'
|
|
663
|
+
) {
|
|
664
|
+
try {
|
|
665
|
+
Promise.resolve(this.ctx.resume()).then(
|
|
666
|
+
() => this.syncStreamFocus(),
|
|
667
|
+
(error) => this.recordError(error),
|
|
668
|
+
);
|
|
669
|
+
} catch (error) {
|
|
670
|
+
this.recordError(error);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
this.updateGainNodes();
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
private isAllowedBridgeOrigin(origin: string): boolean {
|
|
678
|
+
if (!origin || origin === 'null') return false;
|
|
679
|
+
if (this.allowedParentOrigins.size > 0) return this.allowedParentOrigins.has(origin);
|
|
680
|
+
if (typeof window === 'undefined' || !window.location) return false;
|
|
681
|
+
return origin === window.location.origin;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
private installPostMessageBridge(): void {
|
|
685
|
+
if (typeof window === 'undefined') return;
|
|
686
|
+
const listener = (event: Event) => {
|
|
687
|
+
const messageEvent = event as MessageEvent;
|
|
688
|
+
if (!this.isAllowedBridgeOrigin(messageEvent.origin)) return;
|
|
689
|
+
const data = messageEvent.data;
|
|
690
|
+
if (!data || typeof data !== 'object' || typeof data.type !== 'string') return;
|
|
691
|
+
if (!data.type.startsWith('zhuda:')) return;
|
|
692
|
+
|
|
693
|
+
this.handleBridgeMessage(data);
|
|
694
|
+
const source = messageEvent.source as WindowProxy | null;
|
|
695
|
+
if (source && typeof source.postMessage === 'function') {
|
|
696
|
+
try {
|
|
697
|
+
source.postMessage(
|
|
698
|
+
{
|
|
699
|
+
type: 'zhuda:telemetry:ack',
|
|
700
|
+
receivedCommand: data.type,
|
|
701
|
+
diagnostics: this.getDiagnostics(),
|
|
702
|
+
},
|
|
703
|
+
messageEvent.origin,
|
|
704
|
+
);
|
|
705
|
+
} catch (error) {
|
|
706
|
+
this.recordError(error);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
this.addEventListener(window, 'message', listener);
|
|
711
|
+
this.postMessageBridgeActive = true;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
public handleBridgeMessage(msg: {
|
|
715
|
+
type: string;
|
|
716
|
+
channel?: IframeAudioChannel;
|
|
717
|
+
volume?: number;
|
|
718
|
+
}): IframeSoundAdapterDiagnostics {
|
|
719
|
+
if (this.disposed) return this.getDiagnostics();
|
|
720
|
+
this.lastBridgeCommand = typeof msg?.type === 'string' ? msg.type : 'invalid';
|
|
721
|
+
switch (msg?.type) {
|
|
722
|
+
case 'zhuda:audio:mute':
|
|
723
|
+
this.setMuted(true);
|
|
724
|
+
break;
|
|
725
|
+
case 'zhuda:audio:unmute':
|
|
726
|
+
this.setMuted(false);
|
|
727
|
+
this.unlockAudio('bridge-unmute');
|
|
728
|
+
break;
|
|
729
|
+
case 'zhuda:audio:setVolume':
|
|
730
|
+
if (isAudioChannel(msg.channel) && isFiniteNumber(msg.volume)) {
|
|
731
|
+
this.setChannelVolume(msg.channel, msg.volume);
|
|
732
|
+
}
|
|
733
|
+
break;
|
|
734
|
+
case 'zhuda:lifecycle:pause':
|
|
735
|
+
this.handleFocusOrVisibilityChange(false, false);
|
|
736
|
+
break;
|
|
737
|
+
case 'zhuda:lifecycle:resume':
|
|
738
|
+
this.handleFocusOrVisibilityChange(true, true);
|
|
739
|
+
break;
|
|
740
|
+
case 'zhuda:audio:unlock':
|
|
741
|
+
this.unlockAudio('bridge-unlock');
|
|
742
|
+
break;
|
|
743
|
+
default:
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
this.syncDomTelemetry();
|
|
747
|
+
return this.getDiagnostics();
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
public setMuted(muted: boolean): void {
|
|
751
|
+
if (this.disposed) return;
|
|
752
|
+
this.userMuted = Boolean(muted);
|
|
753
|
+
this.updateGainNodes();
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
public isMuted(): boolean {
|
|
757
|
+
return this.userMuted;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
public setChannelVolume(channel: IframeAudioChannel, volume: number): boolean {
|
|
761
|
+
if (!isAudioChannel(channel) || !isFiniteNumber(volume) || volume < 0 || volume > 1)
|
|
762
|
+
return false;
|
|
763
|
+
this.volumes[channel] = volume;
|
|
764
|
+
this.updateGainNodes();
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
public getChannelVolume(channel: IframeAudioChannel): number {
|
|
769
|
+
return this.volumes[channel];
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
private validateTone(options: IframeToneOptions): IframeAudioChannel | null {
|
|
773
|
+
if (
|
|
774
|
+
!options ||
|
|
775
|
+
typeof options.id !== 'string' ||
|
|
776
|
+
options.id.trim().length === 0 ||
|
|
777
|
+
!this.validVoice(options)
|
|
778
|
+
)
|
|
779
|
+
return null;
|
|
780
|
+
const channel = options.channel ?? 'sfx';
|
|
781
|
+
if (!isAudioChannel(channel)) return null;
|
|
782
|
+
if (!isFiniteNumber(options.startFreq) || options.startFreq <= 0 || options.startFreq > 24000)
|
|
783
|
+
return null;
|
|
784
|
+
if (
|
|
785
|
+
options.endFreq !== undefined &&
|
|
786
|
+
(!isFiniteNumber(options.endFreq) || options.endFreq <= 0 || options.endFreq > 24000)
|
|
787
|
+
)
|
|
788
|
+
return null;
|
|
789
|
+
if (
|
|
790
|
+
!isFiniteNumber(options.durationSec) ||
|
|
791
|
+
options.durationSec <= 0 ||
|
|
792
|
+
options.durationSec > 30
|
|
793
|
+
)
|
|
794
|
+
return null;
|
|
795
|
+
if (
|
|
796
|
+
options.peakGain !== undefined &&
|
|
797
|
+
(!isFiniteNumber(options.peakGain) || options.peakGain < 0 || options.peakGain > 1)
|
|
798
|
+
)
|
|
799
|
+
return null;
|
|
800
|
+
if (
|
|
801
|
+
options.delaySec !== undefined &&
|
|
802
|
+
(!isFiniteNumber(options.delaySec) || options.delaySec < 0 || options.delaySec > 60)
|
|
803
|
+
)
|
|
804
|
+
return null;
|
|
805
|
+
if (options.waveType !== undefined && !AUDIO_WAVE_TYPES.includes(options.waveType)) return null;
|
|
806
|
+
return channel;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
private runSynthesis(
|
|
810
|
+
options: IframeToneOptions,
|
|
811
|
+
channel: IframeAudioChannel,
|
|
812
|
+
): AudioVoiceHandle | true | null {
|
|
813
|
+
const context = this.ensureAudioContext(false);
|
|
814
|
+
const channelGain = channel === 'master' ? this.masterGain : this.channelGains[channel];
|
|
815
|
+
if (!context || !this.masterGain || !channelGain) {
|
|
816
|
+
this.recordError('WebAudio mixer is unavailable');
|
|
817
|
+
this.syncDomTelemetry();
|
|
818
|
+
return null;
|
|
819
|
+
}
|
|
820
|
+
const admission = this.admit(options, {
|
|
821
|
+
id: options.id,
|
|
822
|
+
channel,
|
|
823
|
+
execute: () => this.runSynthesis(options, channel) !== null,
|
|
824
|
+
});
|
|
825
|
+
if (admission !== 'ready') return admission === 'queued' ? true : null;
|
|
826
|
+
|
|
827
|
+
const voiceKey = `${options.id}:${++this.voiceSerial}`;
|
|
828
|
+
const when = context.currentTime + (options.delaySec ?? 0);
|
|
829
|
+
const duration = options.durationSec;
|
|
830
|
+
const state: VoiceState = {
|
|
831
|
+
logicalId: options.id,
|
|
832
|
+
channel,
|
|
833
|
+
priority: options.priority,
|
|
834
|
+
protected: options.protected,
|
|
835
|
+
source: null as unknown as OscillatorNode,
|
|
836
|
+
stopped: false,
|
|
837
|
+
};
|
|
838
|
+
try {
|
|
839
|
+
const source = context.createOscillator();
|
|
840
|
+
const gain = context.createGain();
|
|
841
|
+
state.source = source;
|
|
842
|
+
state.gain = gain;
|
|
843
|
+
source.type = options.waveType ?? 'triangle';
|
|
844
|
+
source.frequency.setValueAtTime(options.startFreq, when);
|
|
845
|
+
if (options.endFreq !== undefined && options.endFreq !== options.startFreq) {
|
|
846
|
+
source.frequency.exponentialRampToValueAtTime(options.endFreq, when + duration);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const peak = options.peakGain ?? 0.18;
|
|
850
|
+
// Master and channel volumes are applied only by the mixer gain chain.
|
|
851
|
+
gain.gain.setValueAtTime(Math.max(0.001, peak), when);
|
|
852
|
+
gain.gain.exponentialRampToValueAtTime(0.0008, when + duration);
|
|
853
|
+
source.connect(gain);
|
|
854
|
+
gain.connect(channelGain);
|
|
855
|
+
|
|
856
|
+
source.onended = () => this.finishVoice(voiceKey);
|
|
857
|
+
this.activeVoices.set(voiceKey, state);
|
|
858
|
+
source.start(when);
|
|
859
|
+
source.stop(when + duration);
|
|
860
|
+
this.playedEventsCount++;
|
|
861
|
+
this.voiceEvent({ type: 'started', id: options.id, channel });
|
|
862
|
+
|
|
863
|
+
const handle: AudioVoiceHandle = {
|
|
864
|
+
id: options.id,
|
|
865
|
+
channel,
|
|
866
|
+
get stopped() {
|
|
867
|
+
return state.stopped;
|
|
868
|
+
},
|
|
869
|
+
stop: () => this.stopVoice(voiceKey),
|
|
870
|
+
};
|
|
871
|
+
this.syncDomTelemetry();
|
|
872
|
+
return handle;
|
|
873
|
+
} catch (error) {
|
|
874
|
+
this.recordError(error);
|
|
875
|
+
state.stopped = true;
|
|
876
|
+
try {
|
|
877
|
+
state.source?.disconnect?.();
|
|
878
|
+
state.gain?.disconnect?.();
|
|
879
|
+
} catch {
|
|
880
|
+
/* failed setup */
|
|
881
|
+
}
|
|
882
|
+
this.activeVoices.delete(voiceKey);
|
|
883
|
+
this.syncDomTelemetry();
|
|
884
|
+
return null;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
private submit(task: Omit<QueuedAudioTask, 'createdAt'>, replace = false): boolean {
|
|
889
|
+
if (this.disposed || this.userMuted || this.autoSuspendedByBlur) return false;
|
|
890
|
+
if ([...this.admissions.values()].some((value) => value.id === task.id)) return false;
|
|
891
|
+
if (this.unlockedByGesture) return task.execute();
|
|
892
|
+
const old = this.pendingQueue.findIndex((value) => value.id === task.id);
|
|
893
|
+
if (old >= 0 && !replace) {
|
|
894
|
+
this.droppedQueue++;
|
|
895
|
+
this.syncDomTelemetry();
|
|
896
|
+
return false;
|
|
897
|
+
}
|
|
898
|
+
if (old < 0 && this.pendingQueue.length >= this.options.maxPendingQueue) {
|
|
899
|
+
this.droppedQueue++;
|
|
900
|
+
this.syncDomTelemetry();
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
const queued = { ...task, createdAt: this.now() };
|
|
904
|
+
if (old >= 0) this.pendingQueue[old] = queued;
|
|
905
|
+
else this.pendingQueue.push(queued);
|
|
906
|
+
this.queuedBeforeUnlockCount++;
|
|
907
|
+
this.syncDomTelemetry();
|
|
908
|
+
return true;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** Queues once before unlock, then starts one voice through the shared mixer. */
|
|
912
|
+
public scheduleTone(options: IframeToneOptions): boolean {
|
|
913
|
+
const channel = this.validateTone(options);
|
|
914
|
+
if (!channel) return false;
|
|
915
|
+
const snapshot = { ...options };
|
|
916
|
+
return this.submit({
|
|
917
|
+
id: snapshot.id,
|
|
918
|
+
channel,
|
|
919
|
+
execute: () => this.runSynthesis(snapshot, channel) !== null,
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
private sampleInfo(id: string, buffer: AudioBuffer): IframeSampleInfo {
|
|
924
|
+
return {
|
|
925
|
+
id,
|
|
926
|
+
durationSec: buffer.duration,
|
|
927
|
+
channels: buffer.numberOfChannels,
|
|
928
|
+
sampleRate: buffer.sampleRate,
|
|
929
|
+
frames: buffer.length,
|
|
930
|
+
decodedBytes: buffer.length * buffer.numberOfChannels * 4,
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** Load and decode a provider logical ID. Repeated callers share the existing cache work. */
|
|
935
|
+
public async loadSample(
|
|
936
|
+
id: string,
|
|
937
|
+
options: { signal?: AbortSignal } = {},
|
|
938
|
+
): Promise<IframeSampleInfo> {
|
|
939
|
+
normalizeAssetId(id);
|
|
940
|
+
if (this.disposed || !this.sampleCache)
|
|
941
|
+
throw Error('Sample loading requires a live adapter with sampleProvider');
|
|
942
|
+
if (options.signal?.aborted) throw new DOMException('Sample load cancelled', 'AbortError');
|
|
943
|
+
const existing = this.samples.get(id);
|
|
944
|
+
if (existing) return this.sampleInfo(id, existing.value);
|
|
945
|
+
const reserved = new Set([...this.samples.keys(), ...this.sampleLoads.values(), id]);
|
|
946
|
+
if (reserved.size > this.maxSamples) throw Error('Audio sample capacity exceeded');
|
|
947
|
+
const controller = new AbortController();
|
|
948
|
+
const abort = () => controller.abort();
|
|
949
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
950
|
+
this.sampleLoads.set(controller, id);
|
|
951
|
+
let timedOut = false;
|
|
952
|
+
const timer = setTimeout(() => {
|
|
953
|
+
timedOut = true;
|
|
954
|
+
abort();
|
|
955
|
+
}, this.sampleTimeoutMs);
|
|
956
|
+
let lease: AssetLease<AudioBuffer> | undefined;
|
|
957
|
+
try {
|
|
958
|
+
lease = await this.sampleCache.acquire(id, { signal: controller.signal });
|
|
959
|
+
if (controller.signal.aborted || this.disposed)
|
|
960
|
+
throw new DOMException('Sample load cancelled', 'AbortError');
|
|
961
|
+
const info = this.sampleInfo(id, lease.value);
|
|
962
|
+
if (!this.samples.has(id)) {
|
|
963
|
+
if (
|
|
964
|
+
this.getDiagnostics().decodedSampleBytes + info.decodedBytes >
|
|
965
|
+
this.maxDecodedSampleBytes
|
|
966
|
+
)
|
|
967
|
+
throw Error('Total decoded sample PCM bound exceeded');
|
|
968
|
+
this.samples.set(id, lease);
|
|
969
|
+
lease = undefined;
|
|
970
|
+
}
|
|
971
|
+
return info;
|
|
972
|
+
} catch (error) {
|
|
973
|
+
const failure = timedOut ? new Error(`Audio sample load/decode timeout: ${id}`) : error;
|
|
974
|
+
this.recordError(failure);
|
|
975
|
+
throw failure;
|
|
976
|
+
} finally {
|
|
977
|
+
lease?.release();
|
|
978
|
+
clearTimeout(timer);
|
|
979
|
+
options.signal?.removeEventListener('abort', abort);
|
|
980
|
+
this.sampleLoads.delete(controller);
|
|
981
|
+
if (this.disposed && !this.sampleLoads.size) this.sampleCache.dispose();
|
|
982
|
+
this.syncDomTelemetry();
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/** Stops this sample's queued/active voices, cancels pending loads and releases its PCM lease. */
|
|
987
|
+
public unloadSample(id: string): boolean {
|
|
988
|
+
let changed = false;
|
|
989
|
+
for (const [controller, sampleId] of this.sampleLoads)
|
|
990
|
+
if (sampleId === id) {
|
|
991
|
+
controller.abort();
|
|
992
|
+
changed = true;
|
|
993
|
+
}
|
|
994
|
+
for (const [key, task] of this.admissions)
|
|
995
|
+
if (task.sampleId === id) {
|
|
996
|
+
this.admissions.delete(key);
|
|
997
|
+
changed = true;
|
|
998
|
+
}
|
|
999
|
+
for (const [key, voice] of [...this.activeVoices])
|
|
1000
|
+
if (voice.sampleId === id) {
|
|
1001
|
+
this.stopVoice(key);
|
|
1002
|
+
changed = true;
|
|
1003
|
+
}
|
|
1004
|
+
const before = this.pendingQueue.length;
|
|
1005
|
+
this.pendingQueue = this.pendingQueue.filter((task) => task.sampleId !== id);
|
|
1006
|
+
changed ||= before !== this.pendingQueue.length;
|
|
1007
|
+
const lease = this.samples.get(id);
|
|
1008
|
+
if (lease) {
|
|
1009
|
+
this.samples.delete(id);
|
|
1010
|
+
lease.release();
|
|
1011
|
+
changed = true;
|
|
1012
|
+
}
|
|
1013
|
+
this.syncDomTelemetry();
|
|
1014
|
+
return changed;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** Install one sample backend before playback. No implicit fallback after
|
|
1018
|
+
* failure: the caller may retry or retain native playback explicitly. */
|
|
1019
|
+
public async prepareSampleBackend(
|
|
1020
|
+
backend: IframeSampleBackend,
|
|
1021
|
+
options: { signal?: AbortSignal } = {},
|
|
1022
|
+
): Promise<void> {
|
|
1023
|
+
if (
|
|
1024
|
+
this.disposed ||
|
|
1025
|
+
this.sampleBackend ||
|
|
1026
|
+
this.backendPreparing ||
|
|
1027
|
+
this.activeVoices.size ||
|
|
1028
|
+
this.pendingQueue.length ||
|
|
1029
|
+
this.admissions.size
|
|
1030
|
+
)
|
|
1031
|
+
throw Error('Backend preparation requires an idle, live adapter without a backend');
|
|
1032
|
+
const provider = this.options.sampleProvider;
|
|
1033
|
+
const context = this.ensureAudioContext();
|
|
1034
|
+
if (!provider || !context || !backend?.name)
|
|
1035
|
+
throw Error('Backend requires provider, context and name');
|
|
1036
|
+
const controller = (this.backendPreparing = new AbortController());
|
|
1037
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
1038
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
1039
|
+
if (options.signal?.aborted) abort();
|
|
1040
|
+
const timer = setTimeout(
|
|
1041
|
+
() => controller.abort(new DOMException('Backend prepare timeout', 'TimeoutError')),
|
|
1042
|
+
this.sampleTimeoutMs,
|
|
1043
|
+
);
|
|
1044
|
+
let cancel: () => void = () => {};
|
|
1045
|
+
let accepted = false;
|
|
1046
|
+
const work = Promise.resolve().then(() => {
|
|
1047
|
+
if (controller.signal.aborted)
|
|
1048
|
+
throw controller.signal.reason ?? new DOMException('Cancelled', 'AbortError');
|
|
1049
|
+
return backend.prepare({ context, provider, signal: controller.signal });
|
|
1050
|
+
});
|
|
1051
|
+
// An uncooperative late preparation may allocate after the first dispose.
|
|
1052
|
+
void work.then(
|
|
1053
|
+
() => {
|
|
1054
|
+
if (controller.signal.aborted || this.disposed) {
|
|
1055
|
+
try {
|
|
1056
|
+
backend.dispose();
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
this.recordError(error);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
},
|
|
1062
|
+
() => {},
|
|
1063
|
+
);
|
|
1064
|
+
try {
|
|
1065
|
+
await Promise.race([
|
|
1066
|
+
work,
|
|
1067
|
+
new Promise<never>((_, reject) => {
|
|
1068
|
+
cancel = () =>
|
|
1069
|
+
reject(controller.signal.reason ?? new DOMException('Cancelled', 'AbortError'));
|
|
1070
|
+
controller.signal.addEventListener('abort', cancel, { once: true });
|
|
1071
|
+
if (controller.signal.aborted) cancel();
|
|
1072
|
+
}),
|
|
1073
|
+
]);
|
|
1074
|
+
if (this.disposed || controller.signal.aborted)
|
|
1075
|
+
throw new DOMException('Backend cancelled', 'AbortError');
|
|
1076
|
+
this.sampleBackend = backend;
|
|
1077
|
+
accepted = true;
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
this.recordError(error);
|
|
1080
|
+
throw error;
|
|
1081
|
+
} finally {
|
|
1082
|
+
clearTimeout(timer);
|
|
1083
|
+
options.signal?.removeEventListener('abort', abort);
|
|
1084
|
+
controller.signal.removeEventListener('abort', cancel);
|
|
1085
|
+
this.backendPreparing = undefined;
|
|
1086
|
+
if (!accepted) {
|
|
1087
|
+
try {
|
|
1088
|
+
backend.dispose();
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
this.recordError(error);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
public async loadStream(
|
|
1097
|
+
id: string,
|
|
1098
|
+
options: { signal?: AbortSignal } = {},
|
|
1099
|
+
): Promise<IframeStreamInfo> {
|
|
1100
|
+
id = normalizeAssetId(id);
|
|
1101
|
+
if (this.disposed || !this.streamCache)
|
|
1102
|
+
throw Error('Stream loading requires a live provider with openStream');
|
|
1103
|
+
if (options.signal?.aborted) throw new DOMException('Stream cancelled', 'AbortError');
|
|
1104
|
+
const info = (lease: AssetStreamLease): IframeStreamInfo => ({
|
|
1105
|
+
id,
|
|
1106
|
+
integrity: lease.integrity,
|
|
1107
|
+
delivery: lease.delivery,
|
|
1108
|
+
retainedBytes: lease.retainedBytes,
|
|
1109
|
+
});
|
|
1110
|
+
const existing = this.streams.get(id);
|
|
1111
|
+
if (existing) return info(existing.value);
|
|
1112
|
+
if (new Set([...this.streams.keys(), ...this.streamLoads.values(), id]).size > this.maxSamples)
|
|
1113
|
+
throw Error('Stream capacity exceeded');
|
|
1114
|
+
const controller = new AbortController();
|
|
1115
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
1116
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
1117
|
+
this.streamLoads.set(controller, id);
|
|
1118
|
+
let timeout = false;
|
|
1119
|
+
const timer = setTimeout(() => {
|
|
1120
|
+
timeout = true;
|
|
1121
|
+
controller.abort();
|
|
1122
|
+
}, this.sampleTimeoutMs);
|
|
1123
|
+
let lease: AssetLease<AssetStreamLease> | undefined;
|
|
1124
|
+
try {
|
|
1125
|
+
lease = await this.streamCache.acquire(id, { signal: controller.signal });
|
|
1126
|
+
if (controller.signal.aborted || this.disposed)
|
|
1127
|
+
throw new DOMException('Stream cancelled', 'AbortError');
|
|
1128
|
+
const result = info(lease.value);
|
|
1129
|
+
if (!this.streams.has(id)) {
|
|
1130
|
+
if (
|
|
1131
|
+
this.getDiagnostics().retainedStreamBytes + result.retainedBytes >
|
|
1132
|
+
this.maxRetainedStreamBytes
|
|
1133
|
+
)
|
|
1134
|
+
throw Error('Total retained stream byte bound exceeded');
|
|
1135
|
+
this.streams.set(id, lease);
|
|
1136
|
+
lease = undefined;
|
|
1137
|
+
}
|
|
1138
|
+
return result;
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
const failure = timeout ? Error(`Stream load timeout: ${id}`) : error;
|
|
1141
|
+
this.recordError(failure);
|
|
1142
|
+
throw failure;
|
|
1143
|
+
} finally {
|
|
1144
|
+
lease?.release();
|
|
1145
|
+
clearTimeout(timer);
|
|
1146
|
+
options.signal?.removeEventListener('abort', abort);
|
|
1147
|
+
this.streamLoads.delete(controller);
|
|
1148
|
+
if (this.disposed && !this.streamLoads.size) this.streamCache.dispose();
|
|
1149
|
+
this.syncDomTelemetry();
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
public unloadStream(id: string): boolean {
|
|
1154
|
+
let changed = false;
|
|
1155
|
+
for (const [controller, value] of this.streamLoads)
|
|
1156
|
+
if (value === id) {
|
|
1157
|
+
controller.abort();
|
|
1158
|
+
changed = true;
|
|
1159
|
+
}
|
|
1160
|
+
for (const [key, task] of this.admissions)
|
|
1161
|
+
if (task.streamId === id) {
|
|
1162
|
+
this.admissions.delete(key);
|
|
1163
|
+
changed = true;
|
|
1164
|
+
}
|
|
1165
|
+
const before = this.pendingQueue.length;
|
|
1166
|
+
this.pendingQueue = this.pendingQueue.filter((task) => task.streamId !== id);
|
|
1167
|
+
changed ||= before !== this.pendingQueue.length;
|
|
1168
|
+
for (const [key, voice] of [...this.activeVoices])
|
|
1169
|
+
if (voice.streamId === id) {
|
|
1170
|
+
this.stopVoice(key);
|
|
1171
|
+
changed = true;
|
|
1172
|
+
}
|
|
1173
|
+
const lease = this.streams.get(id);
|
|
1174
|
+
if (lease) {
|
|
1175
|
+
this.streams.delete(id);
|
|
1176
|
+
lease.release();
|
|
1177
|
+
changed = true;
|
|
1178
|
+
}
|
|
1179
|
+
this.syncDomTelemetry();
|
|
1180
|
+
return changed;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
public playStream(options: IframeStreamOptions): boolean {
|
|
1184
|
+
if (!options || !options.id?.trim() || !this.validVoice(options)) return false;
|
|
1185
|
+
const lease = this.streams.get(options.streamId),
|
|
1186
|
+
channel = options.channel ?? 'bgm';
|
|
1187
|
+
if (!lease || !isAudioChannel(channel)) return false;
|
|
1188
|
+
const offset = options.offsetSec ?? 0,
|
|
1189
|
+
fade = options.fadeInSec ?? options.crossFadeSec ?? 0,
|
|
1190
|
+
crossFade = options.crossFadeSec ?? 0,
|
|
1191
|
+
peak = options.peakGain ?? 1;
|
|
1192
|
+
if (
|
|
1193
|
+
![offset, fade, crossFade, peak].every((v) => Number.isFinite(v) && v >= 0) ||
|
|
1194
|
+
peak > 1 ||
|
|
1195
|
+
fade > 60 ||
|
|
1196
|
+
crossFade > 60 ||
|
|
1197
|
+
(crossFade > 0 && !options.replace) ||
|
|
1198
|
+
(options.loop !== undefined && typeof options.loop !== 'boolean') ||
|
|
1199
|
+
(options.replace !== undefined && typeof options.replace !== 'boolean')
|
|
1200
|
+
)
|
|
1201
|
+
return false;
|
|
1202
|
+
const snapshot = { ...options };
|
|
1203
|
+
const task: Omit<QueuedAudioTask, 'createdAt'> = {
|
|
1204
|
+
id: snapshot.id,
|
|
1205
|
+
streamId: snapshot.streamId,
|
|
1206
|
+
channel,
|
|
1207
|
+
execute: () => {
|
|
1208
|
+
if (
|
|
1209
|
+
this.disposed ||
|
|
1210
|
+
this.userMuted ||
|
|
1211
|
+
this.autoSuspendedByBlur ||
|
|
1212
|
+
this.streams.get(snapshot.streamId) !== lease
|
|
1213
|
+
)
|
|
1214
|
+
return false;
|
|
1215
|
+
const previous = [...this.activeVoices]
|
|
1216
|
+
.filter(([, v]) => v.logicalId === snapshot.id)
|
|
1217
|
+
.map(([k]) => k);
|
|
1218
|
+
if (previous.length && !snapshot.replace) return false;
|
|
1219
|
+
const context = this.ensureAudioContext(false),
|
|
1220
|
+
channelGain = channel === 'master' ? this.masterGain : this.channelGains[channel];
|
|
1221
|
+
if (!context || !channelGain) return false;
|
|
1222
|
+
const admission = this.admit(snapshot, task, previous);
|
|
1223
|
+
if (admission !== 'ready') return admission === 'queued';
|
|
1224
|
+
const key = `${snapshot.id}:${++this.voiceSerial}`;
|
|
1225
|
+
let source: StreamVoice | undefined, gain: GainNode | undefined;
|
|
1226
|
+
try {
|
|
1227
|
+
const media = this.options.mediaElementFactory?.() ?? document.createElement('audio');
|
|
1228
|
+
source = new StreamVoice(
|
|
1229
|
+
context,
|
|
1230
|
+
media,
|
|
1231
|
+
lease.value,
|
|
1232
|
+
snapshot,
|
|
1233
|
+
this.sampleTimeoutMs,
|
|
1234
|
+
(error) => {
|
|
1235
|
+
this.recordError(error);
|
|
1236
|
+
this.voiceEvent({
|
|
1237
|
+
type: 'failed',
|
|
1238
|
+
id: snapshot.id,
|
|
1239
|
+
channel,
|
|
1240
|
+
reason: String(error),
|
|
1241
|
+
});
|
|
1242
|
+
},
|
|
1243
|
+
() => {
|
|
1244
|
+
if (!this.activeVoices.has(key) || this.disposed) return;
|
|
1245
|
+
gain!.gain.setValueAtTime(fade ? 0 : peak, context.currentTime);
|
|
1246
|
+
if (fade) gain!.gain.linearRampToValueAtTime(peak, context.currentTime + fade);
|
|
1247
|
+
for (const old of previous) this.stopVoice(old, crossFade);
|
|
1248
|
+
this.playedEventsCount++;
|
|
1249
|
+
this.voiceEvent({ type: 'started', id: snapshot.id, channel });
|
|
1250
|
+
this.syncDomTelemetry();
|
|
1251
|
+
},
|
|
1252
|
+
);
|
|
1253
|
+
gain = context.createGain();
|
|
1254
|
+
gain.gain.setValueAtTime(fade ? 0 : peak, context.currentTime);
|
|
1255
|
+
source.output.connect(gain);
|
|
1256
|
+
gain.connect(channelGain);
|
|
1257
|
+
source.onended = () => this.finishVoice(key);
|
|
1258
|
+
this.activeVoices.set(key, {
|
|
1259
|
+
logicalId: snapshot.id,
|
|
1260
|
+
channel,
|
|
1261
|
+
source,
|
|
1262
|
+
gain,
|
|
1263
|
+
streamId: snapshot.streamId,
|
|
1264
|
+
stopped: false,
|
|
1265
|
+
priority: snapshot.priority,
|
|
1266
|
+
protected: snapshot.protected,
|
|
1267
|
+
});
|
|
1268
|
+
source.start(context.currentTime, offset);
|
|
1269
|
+
this.syncDomTelemetry();
|
|
1270
|
+
return true;
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
source?.disconnect();
|
|
1273
|
+
gain?.disconnect();
|
|
1274
|
+
this.activeVoices.delete(key);
|
|
1275
|
+
this.recordError(error);
|
|
1276
|
+
return false;
|
|
1277
|
+
}
|
|
1278
|
+
},
|
|
1279
|
+
};
|
|
1280
|
+
return this.submit(task, snapshot.replace);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
public playSample(options: IframeSampleOptions): boolean {
|
|
1284
|
+
if (
|
|
1285
|
+
!options ||
|
|
1286
|
+
typeof options.id !== 'string' ||
|
|
1287
|
+
!options.id.trim() ||
|
|
1288
|
+
!this.validVoice(options) ||
|
|
1289
|
+
this.backendPreparing
|
|
1290
|
+
)
|
|
1291
|
+
return false;
|
|
1292
|
+
const lease = this.samples.get(options.sampleId);
|
|
1293
|
+
const channel = options.channel ?? 'sfx';
|
|
1294
|
+
if (!lease || !isAudioChannel(channel)) return false;
|
|
1295
|
+
const buffer = lease.value;
|
|
1296
|
+
const spatial = options.spatial === undefined ? undefined : resolveSpatial(options.spatial);
|
|
1297
|
+
if (spatial === null) return false;
|
|
1298
|
+
const offset = options.offsetSec ?? 0,
|
|
1299
|
+
loopStart = options.loopStartSec ?? 0,
|
|
1300
|
+
loopEnd = options.loopEndSec ?? buffer.duration;
|
|
1301
|
+
for (const value of [
|
|
1302
|
+
offset,
|
|
1303
|
+
loopStart,
|
|
1304
|
+
loopEnd,
|
|
1305
|
+
options.fadeInSec ?? 0,
|
|
1306
|
+
options.fadeOutSec ?? 0,
|
|
1307
|
+
options.crossFadeSec ?? 0,
|
|
1308
|
+
])
|
|
1309
|
+
if (!Number.isFinite(value) || value < 0) return false;
|
|
1310
|
+
if (
|
|
1311
|
+
offset >= buffer.duration ||
|
|
1312
|
+
loopStart >= loopEnd ||
|
|
1313
|
+
loopEnd > buffer.duration ||
|
|
1314
|
+
(options.loop !== undefined && typeof options.loop !== 'boolean') ||
|
|
1315
|
+
(options.replace !== undefined && typeof options.replace !== 'boolean') ||
|
|
1316
|
+
((options.crossFadeSec ?? 0) > 0 && !options.replace) ||
|
|
1317
|
+
(options.durationSec !== undefined &&
|
|
1318
|
+
(!Number.isFinite(options.durationSec) || options.durationSec <= 0)) ||
|
|
1319
|
+
(options.peakGain !== undefined &&
|
|
1320
|
+
(!Number.isFinite(options.peakGain) || options.peakGain < 0 || options.peakGain > 1))
|
|
1321
|
+
)
|
|
1322
|
+
return false;
|
|
1323
|
+
const duration = options.loop
|
|
1324
|
+
? options.durationSec
|
|
1325
|
+
: Math.min(options.durationSec ?? Infinity, buffer.duration - offset);
|
|
1326
|
+
const fadeIn = options.fadeInSec ?? options.crossFadeSec ?? 0,
|
|
1327
|
+
fadeOut = options.fadeOutSec ?? 0;
|
|
1328
|
+
if (
|
|
1329
|
+
fadeIn > 60 ||
|
|
1330
|
+
fadeOut > 60 ||
|
|
1331
|
+
(options.crossFadeSec ?? 0) > 60 ||
|
|
1332
|
+
(duration === undefined ? fadeOut > 0 : fadeIn + fadeOut > duration)
|
|
1333
|
+
)
|
|
1334
|
+
return false;
|
|
1335
|
+
const snapshot = { ...options };
|
|
1336
|
+
const task: Omit<QueuedAudioTask, 'createdAt'> = {
|
|
1337
|
+
id: snapshot.id,
|
|
1338
|
+
sampleId: snapshot.sampleId,
|
|
1339
|
+
channel,
|
|
1340
|
+
execute: () => {
|
|
1341
|
+
if (
|
|
1342
|
+
this.samples.get(snapshot.sampleId) !== lease ||
|
|
1343
|
+
this.userMuted ||
|
|
1344
|
+
this.autoSuspendedByBlur
|
|
1345
|
+
)
|
|
1346
|
+
return false;
|
|
1347
|
+
const previous = [...this.activeVoices]
|
|
1348
|
+
.filter(([, voice]) => voice.logicalId === snapshot.id)
|
|
1349
|
+
.map(([key]) => key);
|
|
1350
|
+
if (previous.length && !snapshot.replace) return false;
|
|
1351
|
+
const context = this.ensureAudioContext(false);
|
|
1352
|
+
const channelGain = channel === 'master' ? this.masterGain : this.channelGains[channel];
|
|
1353
|
+
if (!context || !channelGain) return false;
|
|
1354
|
+
const admission = this.admit(snapshot, task, previous);
|
|
1355
|
+
if (admission !== 'ready') return admission === 'queued';
|
|
1356
|
+
const key = `${snapshot.id}:${++this.voiceSerial}`;
|
|
1357
|
+
let source: AudioBufferSourceNode | IframeBackendVoice | undefined,
|
|
1358
|
+
gain: GainNode | undefined,
|
|
1359
|
+
placed: SpatialState | undefined;
|
|
1360
|
+
try {
|
|
1361
|
+
if (this.sampleBackend) source = this.sampleBackend.createVoice(buffer, snapshot);
|
|
1362
|
+
else {
|
|
1363
|
+
source = context.createBufferSource();
|
|
1364
|
+
source.buffer = buffer;
|
|
1365
|
+
source.loop = snapshot.loop ?? false;
|
|
1366
|
+
source.loopStart = loopStart;
|
|
1367
|
+
source.loopEnd = loopEnd;
|
|
1368
|
+
}
|
|
1369
|
+
gain = context.createGain();
|
|
1370
|
+
const now = context.currentTime,
|
|
1371
|
+
peak = snapshot.peakGain ?? 1;
|
|
1372
|
+
gain.gain.setValueAtTime(fadeIn ? 0 : peak, now);
|
|
1373
|
+
if (fadeIn) gain.gain.linearRampToValueAtTime(peak, now + fadeIn);
|
|
1374
|
+
if (duration !== undefined && fadeOut) {
|
|
1375
|
+
gain.gain.setValueAtTime(peak, now + duration - fadeOut);
|
|
1376
|
+
gain.gain.linearRampToValueAtTime(0, now + duration);
|
|
1377
|
+
}
|
|
1378
|
+
('output' in source ? source.output : source).connect(gain);
|
|
1379
|
+
// Voice gain, then its place in the world, then the channel: the
|
|
1380
|
+
// channel and master gains still apply once.
|
|
1381
|
+
if (spatial) {
|
|
1382
|
+
placed = this.createSpatial(context, spatial);
|
|
1383
|
+
gain.connect(placed.input);
|
|
1384
|
+
placed.output.connect(channelGain);
|
|
1385
|
+
} else gain.connect(channelGain);
|
|
1386
|
+
source.onended = () => this.finishVoice(key);
|
|
1387
|
+
this.activeVoices.set(key, {
|
|
1388
|
+
logicalId: snapshot.id,
|
|
1389
|
+
channel,
|
|
1390
|
+
source,
|
|
1391
|
+
gain,
|
|
1392
|
+
spatial: placed,
|
|
1393
|
+
sampleId: snapshot.sampleId,
|
|
1394
|
+
stopped: false,
|
|
1395
|
+
priority: snapshot.priority,
|
|
1396
|
+
protected: snapshot.protected,
|
|
1397
|
+
startedAt: now,
|
|
1398
|
+
startOffset: offset,
|
|
1399
|
+
loopRange: snapshot.loop ? [loopStart, loopEnd] : undefined,
|
|
1400
|
+
});
|
|
1401
|
+
source.start(now, offset);
|
|
1402
|
+
if (duration !== undefined) source.stop(now + duration);
|
|
1403
|
+
for (const old of previous) this.stopVoice(old, snapshot.crossFadeSec ?? 0);
|
|
1404
|
+
this.playedEventsCount++;
|
|
1405
|
+
this.voiceEvent({ type: 'started', id: snapshot.id, channel });
|
|
1406
|
+
this.syncDomTelemetry();
|
|
1407
|
+
return true;
|
|
1408
|
+
} catch (error) {
|
|
1409
|
+
try {
|
|
1410
|
+
source?.stop();
|
|
1411
|
+
} catch {
|
|
1412
|
+
/* not started */
|
|
1413
|
+
}
|
|
1414
|
+
source?.disconnect();
|
|
1415
|
+
gain?.disconnect();
|
|
1416
|
+
for (const node of placed?.nodes ?? [])
|
|
1417
|
+
try {
|
|
1418
|
+
node.disconnect();
|
|
1419
|
+
} catch {
|
|
1420
|
+
/* never connected */
|
|
1421
|
+
}
|
|
1422
|
+
this.activeVoices.delete(key);
|
|
1423
|
+
this.recordError(error);
|
|
1424
|
+
this.syncDomTelemetry();
|
|
1425
|
+
return false;
|
|
1426
|
+
}
|
|
1427
|
+
},
|
|
1428
|
+
};
|
|
1429
|
+
return this.submit(task, snapshot.replace);
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
/** Explicit offline soundtrack using loaded samples and this mixer's gain snapshot.
|
|
1433
|
+
* Does not play live voices, use a second live AudioContext or dispatch events. */
|
|
1434
|
+
public async renderOffline(options: IframeOfflineMixOptions): Promise<IframeOfflineMix> {
|
|
1435
|
+
if (this.disposed || this.offlineMix) throw Error('Offline mixer is disposed or busy');
|
|
1436
|
+
const timeout = options.timeoutMs ?? 30000;
|
|
1437
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2147483647)
|
|
1438
|
+
throw Error('Invalid offline audio deadline');
|
|
1439
|
+
if (options.signal?.aborted)
|
|
1440
|
+
throw options.signal.reason ?? new DOMException('Cancelled', 'AbortError');
|
|
1441
|
+
const controller = (this.offlineMix = new AbortController()),
|
|
1442
|
+
abort = () =>
|
|
1443
|
+
controller.abort(options.signal?.reason ?? new DOMException('Cancelled', 'AbortError'));
|
|
1444
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
1445
|
+
const timer = setTimeout(
|
|
1446
|
+
() => controller.abort(new DOMException('Offline mix timed out', 'TimeoutError')),
|
|
1447
|
+
timeout,
|
|
1448
|
+
);
|
|
1449
|
+
const work = renderOfflineMix(
|
|
1450
|
+
{
|
|
1451
|
+
samples: new Map([...this.samples].map(([id, lease]) => [id, lease.value])),
|
|
1452
|
+
volumes: {
|
|
1453
|
+
...this.volumes,
|
|
1454
|
+
master: this.userMuted ? 0 : this.volumes.master,
|
|
1455
|
+
},
|
|
1456
|
+
maxVoices: this.options.maxActiveVoices,
|
|
1457
|
+
},
|
|
1458
|
+
options,
|
|
1459
|
+
controller.signal,
|
|
1460
|
+
);
|
|
1461
|
+
const drained = () => {
|
|
1462
|
+
if (this.offlineMix === controller) this.offlineMix = null;
|
|
1463
|
+
};
|
|
1464
|
+
void work.then(drained, drained);
|
|
1465
|
+
try {
|
|
1466
|
+
return await awaitAbortable(work, controller.signal);
|
|
1467
|
+
} finally {
|
|
1468
|
+
clearTimeout(timer);
|
|
1469
|
+
options.signal?.removeEventListener('abort', abort);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
private applyListener(context: AudioContext, ramp: number): void {
|
|
1474
|
+
try {
|
|
1475
|
+
placeListener(context.listener, this.listener, context.currentTime, ramp);
|
|
1476
|
+
} catch (error) {
|
|
1477
|
+
this.recordError(error);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
/** A PannerNode where the host has one; otherwise a distance gain and, if it can, a stereo pan. */
|
|
1482
|
+
private createSpatial(context: AudioContext, spatial: ResolvedSpatial): SpatialState {
|
|
1483
|
+
const now = context.currentTime;
|
|
1484
|
+
if (typeof context.createPanner === 'function') {
|
|
1485
|
+
const panner = context.createPanner();
|
|
1486
|
+
// HRTF where the host has it. A browser's setter ignores a word it does
|
|
1487
|
+
// not know and the panner stays at equal power; a host's own stand-in
|
|
1488
|
+
// for Web Audio may throw instead.
|
|
1489
|
+
try {
|
|
1490
|
+
panner.panningModel = spatial.panningModel;
|
|
1491
|
+
} catch {
|
|
1492
|
+
panner.panningModel = 'equalpower';
|
|
1493
|
+
}
|
|
1494
|
+
panner.distanceModel = spatial.distanceModel;
|
|
1495
|
+
panner.refDistance = spatial.refDistance;
|
|
1496
|
+
panner.maxDistance = spatial.maxDistance;
|
|
1497
|
+
panner.rolloffFactor = spatial.rolloffFactor;
|
|
1498
|
+
panner.coneInnerAngle = spatial.coneInnerAngle;
|
|
1499
|
+
panner.coneOuterAngle = spatial.coneOuterAngle;
|
|
1500
|
+
panner.coneOuterGain = spatial.coneOuterGain;
|
|
1501
|
+
placePanner(panner, spatial.position, spatial.orientation, now, 0);
|
|
1502
|
+
return { options: spatial, input: panner, output: panner, nodes: [panner], panner };
|
|
1503
|
+
}
|
|
1504
|
+
const gain = context.createGain(),
|
|
1505
|
+
stereo =
|
|
1506
|
+
typeof context.createStereoPanner === 'function' ? context.createStereoPanner() : undefined;
|
|
1507
|
+
if (stereo) gain.connect(stereo);
|
|
1508
|
+
const state: SpatialState = {
|
|
1509
|
+
options: spatial,
|
|
1510
|
+
input: gain,
|
|
1511
|
+
output: stereo ?? gain,
|
|
1512
|
+
nodes: stereo ? [gain, stereo] : [gain],
|
|
1513
|
+
gain,
|
|
1514
|
+
stereo,
|
|
1515
|
+
};
|
|
1516
|
+
this.placeFallback(state, now, 0);
|
|
1517
|
+
return state;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
private placeFallback(state: SpatialState, now: number, ramp: number): void {
|
|
1521
|
+
const placement = fallbackPlacement(state.options, this.listener);
|
|
1522
|
+
const set = (param: AudioParam, value: number) => {
|
|
1523
|
+
try {
|
|
1524
|
+
setParam(param, value, now, ramp);
|
|
1525
|
+
} catch {
|
|
1526
|
+
param.value = value;
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
if (state.gain) set(state.gain.gain, placement.gain);
|
|
1530
|
+
if (state.stereo) set(state.stereo.pan, placement.pan);
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* Where the listener is and which way it faces, usually the camera's pose
|
|
1535
|
+
* each frame. Spatial voices are heard from here. Returns false for a pose
|
|
1536
|
+
* that is not finite, or whose forward and up are along one line.
|
|
1537
|
+
*/
|
|
1538
|
+
public setListener(pose: IframeListenerPose): boolean {
|
|
1539
|
+
if (this.disposed) return false;
|
|
1540
|
+
const resolved = resolveListener(pose),
|
|
1541
|
+
ramp = resolveRamp(pose?.rampSec);
|
|
1542
|
+
if (!resolved || ramp === null) return false;
|
|
1543
|
+
this.listener = resolved;
|
|
1544
|
+
if (this.ctx && this.ctx.state !== 'closed') {
|
|
1545
|
+
this.applyListener(this.ctx, ramp);
|
|
1546
|
+
const now = this.ctx.currentTime;
|
|
1547
|
+
for (const voice of this.activeVoices.values())
|
|
1548
|
+
if (voice.spatial?.gain) this.placeFallback(voice.spatial, now, ramp);
|
|
1549
|
+
}
|
|
1550
|
+
return true;
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
/**
|
|
1554
|
+
* Moves the active spatial voices of a logical ID (and turns them, with
|
|
1555
|
+
* `orientation`). A voice still queued before unlock starts where it was
|
|
1556
|
+
* asked to. Returns whether a voice was moved.
|
|
1557
|
+
*/
|
|
1558
|
+
public setVoicePosition(
|
|
1559
|
+
id: string,
|
|
1560
|
+
position: readonly [number, number, number],
|
|
1561
|
+
options: { orientation?: readonly [number, number, number]; rampSec?: number } = {},
|
|
1562
|
+
): boolean {
|
|
1563
|
+
if (this.disposed || !this.ctx) return false;
|
|
1564
|
+
const where = resolvePosition(position),
|
|
1565
|
+
facing = options.orientation === undefined ? undefined : resolvePosition(options.orientation),
|
|
1566
|
+
ramp = resolveRamp(options.rampSec);
|
|
1567
|
+
if (!where || facing === null || ramp === null) return false;
|
|
1568
|
+
const now = this.ctx.currentTime;
|
|
1569
|
+
let moved = false;
|
|
1570
|
+
for (const voice of this.activeVoices.values()) {
|
|
1571
|
+
if (voice.logicalId !== id || !voice.spatial || voice.stopped) continue;
|
|
1572
|
+
const spatial = voice.spatial;
|
|
1573
|
+
spatial.options = {
|
|
1574
|
+
...spatial.options,
|
|
1575
|
+
position: where,
|
|
1576
|
+
orientation: facing ?? spatial.options.orientation,
|
|
1577
|
+
};
|
|
1578
|
+
try {
|
|
1579
|
+
if (spatial.panner)
|
|
1580
|
+
placePanner(
|
|
1581
|
+
spatial.panner,
|
|
1582
|
+
spatial.options.position,
|
|
1583
|
+
spatial.options.orientation,
|
|
1584
|
+
now,
|
|
1585
|
+
ramp,
|
|
1586
|
+
);
|
|
1587
|
+
else this.placeFallback(spatial, now, ramp);
|
|
1588
|
+
moved = true;
|
|
1589
|
+
} catch (error) {
|
|
1590
|
+
this.recordError(error);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
return moved;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
/**
|
|
1597
|
+
* Where a playing sample voice is in its sample, in seconds, by the audio
|
|
1598
|
+
* clock: the offset it started at plus the context time since. It stands
|
|
1599
|
+
* still while the context is suspended (page hidden, focus lost) and is the
|
|
1600
|
+
* time to judge against in anything that must stay with the music. Null when
|
|
1601
|
+
* no sample voice of that logical ID is playing (never started, still queued
|
|
1602
|
+
* before unlock, ended or stopped). With several, the newest answers.
|
|
1603
|
+
*/
|
|
1604
|
+
public getSamplePositionSec(id: string): number | null {
|
|
1605
|
+
const context = this.ctx;
|
|
1606
|
+
if (!context) return null;
|
|
1607
|
+
let found: VoiceState | undefined;
|
|
1608
|
+
for (const voice of this.activeVoices.values())
|
|
1609
|
+
if (voice.logicalId === id && voice.startedAt !== undefined && !voice.stopped) found = voice;
|
|
1610
|
+
if (!found) return null;
|
|
1611
|
+
const position = (found.startOffset ?? 0) + Math.max(0, context.currentTime - found.startedAt!);
|
|
1612
|
+
const loop = found.loopRange;
|
|
1613
|
+
return loop && position >= loop[1]
|
|
1614
|
+
? loop[0] + ((position - loop[0]) % (loop[1] - loop[0]))
|
|
1615
|
+
: position;
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
/**
|
|
1619
|
+
* Seconds between a sample being scheduled and it leaving the speaker, as
|
|
1620
|
+
* the host reports it (`outputLatency`, else `baseLatency`); 0 when it does
|
|
1621
|
+
* not say. Bluetooth output is often not included: keep a player setting.
|
|
1622
|
+
*/
|
|
1623
|
+
public getOutputLatencySec(): number {
|
|
1624
|
+
const context = this.ctx as (AudioContext & { outputLatency?: number }) | null;
|
|
1625
|
+
const value = context?.outputLatency || context?.baseLatency || 0;
|
|
1626
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
public stop(id: string, fadeOutSec = 0): boolean {
|
|
1630
|
+
if (!Number.isFinite(fadeOutSec) || fadeOutSec < 0 || fadeOutSec > 60) return false;
|
|
1631
|
+
let stopped = false;
|
|
1632
|
+
for (const [key, task] of this.admissions)
|
|
1633
|
+
if (task.id === id) {
|
|
1634
|
+
this.admissions.delete(key);
|
|
1635
|
+
stopped = true;
|
|
1636
|
+
}
|
|
1637
|
+
for (const [voiceKey, voice] of [...this.activeVoices.entries()]) {
|
|
1638
|
+
if (voice.logicalId === id) stopped = this.stopVoice(voiceKey, fadeOutSec) || stopped;
|
|
1639
|
+
}
|
|
1640
|
+
const before = this.pendingQueue.length;
|
|
1641
|
+
this.pendingQueue = this.pendingQueue.filter((task) => task.id !== id);
|
|
1642
|
+
if (before !== this.pendingQueue.length) stopped = true;
|
|
1643
|
+
this.syncDomTelemetry();
|
|
1644
|
+
return stopped;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
private finishVoice(voiceKey: string): void {
|
|
1648
|
+
const voice = this.activeVoices.get(voiceKey);
|
|
1649
|
+
if (!voice) return;
|
|
1650
|
+
this.activeVoices.delete(voiceKey);
|
|
1651
|
+
voice.stopped = true;
|
|
1652
|
+
voice.source.onended = null;
|
|
1653
|
+
try {
|
|
1654
|
+
voice.source.disconnect?.();
|
|
1655
|
+
} catch {
|
|
1656
|
+
/* already disconnected */
|
|
1657
|
+
}
|
|
1658
|
+
try {
|
|
1659
|
+
voice.gain?.disconnect?.();
|
|
1660
|
+
} catch {
|
|
1661
|
+
/* already disconnected */
|
|
1662
|
+
}
|
|
1663
|
+
for (const node of voice.spatial?.nodes ?? [])
|
|
1664
|
+
try {
|
|
1665
|
+
node.disconnect?.();
|
|
1666
|
+
} catch {
|
|
1667
|
+
/* already disconnected */
|
|
1668
|
+
}
|
|
1669
|
+
const next = this.admissions.get(voiceKey);
|
|
1670
|
+
this.admissions.delete(voiceKey);
|
|
1671
|
+
this.voiceEvent({
|
|
1672
|
+
type: 'ended',
|
|
1673
|
+
id: voice.logicalId,
|
|
1674
|
+
channel: voice.channel,
|
|
1675
|
+
});
|
|
1676
|
+
if (next && !this.disposed && !this.userMuted && !this.autoSuspendedByBlur) next.execute();
|
|
1677
|
+
this.syncDomTelemetry();
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
private stopVoice(voiceKey: string, fadeOutSec = 0): boolean {
|
|
1681
|
+
const voice = this.activeVoices.get(voiceKey);
|
|
1682
|
+
if (!voice) return false;
|
|
1683
|
+
if (fadeOutSec && voice.stopping) return false;
|
|
1684
|
+
try {
|
|
1685
|
+
if (fadeOutSec && this.ctx && voice.gain) {
|
|
1686
|
+
const now = this.ctx.currentTime;
|
|
1687
|
+
voice.gain.gain.cancelScheduledValues(now);
|
|
1688
|
+
voice.gain.gain.setValueAtTime(voice.gain.gain.value, now);
|
|
1689
|
+
voice.gain.gain.linearRampToValueAtTime(0, now + fadeOutSec);
|
|
1690
|
+
voice.source.stop(now + fadeOutSec);
|
|
1691
|
+
voice.stopping = true;
|
|
1692
|
+
return true;
|
|
1693
|
+
}
|
|
1694
|
+
voice.source.stop();
|
|
1695
|
+
} catch (_error) {
|
|
1696
|
+
/* source may have ended */
|
|
1697
|
+
}
|
|
1698
|
+
this.finishVoice(voiceKey);
|
|
1699
|
+
return true;
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
public stopAll(channel?: IframeAudioChannel): number {
|
|
1703
|
+
for (const [key, task] of this.admissions)
|
|
1704
|
+
if (channel === undefined || task.channel === channel) this.admissions.delete(key);
|
|
1705
|
+
const before = this.pendingQueue.length;
|
|
1706
|
+
this.pendingQueue = this.pendingQueue.filter(
|
|
1707
|
+
(task) => channel !== undefined && task.channel !== channel,
|
|
1708
|
+
);
|
|
1709
|
+
let count = before - this.pendingQueue.length;
|
|
1710
|
+
for (const [voiceKey, voice] of [...this.activeVoices.entries()]) {
|
|
1711
|
+
if (channel === undefined || voice.channel === channel) {
|
|
1712
|
+
if (this.stopVoice(voiceKey)) count++;
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
this.syncDomTelemetry();
|
|
1716
|
+
return count;
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
public getDiagnostics(): IframeSoundAdapterDiagnostics {
|
|
1720
|
+
const state =
|
|
1721
|
+
this.ctx && CONTEXT_STATES.has(this.ctx.state)
|
|
1722
|
+
? (this.ctx.state as IframeSoundDiagnostics['contextState'])
|
|
1723
|
+
: 'uninitialized';
|
|
1724
|
+
return {
|
|
1725
|
+
loadedStreams: this.streams.size,
|
|
1726
|
+
pendingStreamLoads: this.streamLoads.size,
|
|
1727
|
+
retainedStreamBytes: [...this.streams.values()].reduce(
|
|
1728
|
+
(sum, lease) => sum + lease.value.retainedBytes,
|
|
1729
|
+
0,
|
|
1730
|
+
),
|
|
1731
|
+
pendingAdmissions: this.admissions.size,
|
|
1732
|
+
retiredVoices: this.retiredVoices,
|
|
1733
|
+
sampleBackend: this.sampleBackend?.name ?? 'native',
|
|
1734
|
+
loadedSamples: this.samples.size,
|
|
1735
|
+
pendingSampleLoads: this.sampleLoads.size,
|
|
1736
|
+
decodedSampleBytes: [...this.samples.values()].reduce(
|
|
1737
|
+
(sum, lease) => sum + lease.value.length * lease.value.numberOfChannels * 4,
|
|
1738
|
+
0,
|
|
1739
|
+
),
|
|
1740
|
+
inIframe: this.inIframe,
|
|
1741
|
+
contextState: state,
|
|
1742
|
+
unlockedByGesture: this.unlockedByGesture,
|
|
1743
|
+
unlockGestureType: this.unlockGestureType,
|
|
1744
|
+
pageVisible: this.pageVisible,
|
|
1745
|
+
windowFocused: this.windowFocused,
|
|
1746
|
+
autoSuspendedByBlur: this.autoSuspendedByBlur,
|
|
1747
|
+
userMuted: this.userMuted,
|
|
1748
|
+
volumes: { ...this.volumes },
|
|
1749
|
+
queuedBeforeUnlockCount: this.queuedBeforeUnlockCount,
|
|
1750
|
+
pendingQueue: this.pendingQueue.length,
|
|
1751
|
+
droppedQueue: this.droppedQueue,
|
|
1752
|
+
activeVoices: this.activeVoices.size,
|
|
1753
|
+
droppedVoices: this.droppedVoices,
|
|
1754
|
+
playedEventsCount: this.playedEventsCount,
|
|
1755
|
+
postMessageBridgeActive: this.postMessageBridgeActive,
|
|
1756
|
+
lastBridgeCommand: this.lastBridgeCommand,
|
|
1757
|
+
backend: this.ctx ? 'webaudio' : 'unavailable',
|
|
1758
|
+
contextAvailable: this.ctx !== null,
|
|
1759
|
+
lastError: this.lastError,
|
|
1760
|
+
spatialVoices: [...this.activeVoices.values()].filter((voice) => voice.spatial).length,
|
|
1761
|
+
spatialBackend: !this.ctx
|
|
1762
|
+
? 'unavailable'
|
|
1763
|
+
: typeof this.ctx.createPanner === 'function'
|
|
1764
|
+
? 'panner'
|
|
1765
|
+
: 'gain',
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
private syncDomTelemetry(): void {
|
|
1770
|
+
const diagnostics = this.getDiagnostics();
|
|
1771
|
+
const win = globalThis as unknown as {
|
|
1772
|
+
__ZHUDA_IFRAME_AUDIO__?: IframeSoundDiagnostics;
|
|
1773
|
+
__ZHUDA_IFRAME_ADAPTER__?: IframeSoundAdapter;
|
|
1774
|
+
};
|
|
1775
|
+
win.__ZHUDA_IFRAME_AUDIO__ = diagnostics;
|
|
1776
|
+
if (!this.disposed) win.__ZHUDA_IFRAME_ADAPTER__ = this;
|
|
1777
|
+
|
|
1778
|
+
if (typeof document !== 'undefined' && document.body) {
|
|
1779
|
+
document.body.dataset.zhudaIframeAudio = this.postMessageBridgeActive ? 'ready' : 'inactive';
|
|
1780
|
+
document.body.dataset.zhudaAudioMuted = String(this.userMuted || this.autoSuspendedByBlur);
|
|
1781
|
+
document.body.dataset.zhudaAudioPlayed = String(this.playedEventsCount);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
/** Stops voices, removes every event listener and closes the owned context. */
|
|
1786
|
+
public dispose(): void {
|
|
1787
|
+
if (this.disposed) return;
|
|
1788
|
+
this.disposed = true;
|
|
1789
|
+
this.offlineMix?.abort(new DOMException('Mixer disposed', 'AbortError'));
|
|
1790
|
+
this.backendPreparing?.abort();
|
|
1791
|
+
this.unlockAttempt++;
|
|
1792
|
+
this.pendingQueue = [];
|
|
1793
|
+
this.stopAll();
|
|
1794
|
+
for (const controller of this.sampleLoads.keys()) controller.abort();
|
|
1795
|
+
for (const id of [...this.samples.keys()]) this.unloadSample(id);
|
|
1796
|
+
for (const controller of this.streamLoads.keys()) controller.abort();
|
|
1797
|
+
for (const id of [...this.streams.keys()]) this.unloadStream(id);
|
|
1798
|
+
if (!this.streamLoads.size) this.streamCache?.dispose();
|
|
1799
|
+
try {
|
|
1800
|
+
this.sampleBackend?.dispose();
|
|
1801
|
+
} catch (error) {
|
|
1802
|
+
this.recordError(error);
|
|
1803
|
+
}
|
|
1804
|
+
if (!this.sampleLoads.size) this.sampleCache?.dispose();
|
|
1805
|
+
try {
|
|
1806
|
+
this.masterGain?.disconnect?.();
|
|
1807
|
+
for (const node of Object.values(this.channelGains)) node.disconnect?.();
|
|
1808
|
+
} catch {
|
|
1809
|
+
/* context already closed */
|
|
1810
|
+
}
|
|
1811
|
+
for (const cleanup of this.cleanupFns.splice(0)) cleanup();
|
|
1812
|
+
this.gestureCleanupFns.splice(0);
|
|
1813
|
+
this.postMessageBridgeActive = false;
|
|
1814
|
+
if (this.ctx && typeof this.ctx.close === 'function' && this.ctx.state !== 'closed') {
|
|
1815
|
+
try {
|
|
1816
|
+
Promise.resolve(this.ctx.close()).catch((error) => this.recordError(error));
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
this.recordError(error);
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
this.syncDomTelemetry();
|
|
1822
|
+
if (IframeSoundAdapter.instance === this) IframeSoundAdapter.instance = null;
|
|
1823
|
+
}
|
|
1824
|
+
}
|